@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,4928 @@
1
+ import { readFileSync, existsSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { findHtmlTagEnd, resolveIconToSvgHtml } from './shared-utils.js';
4
+ import { readComponentSource } from '../hydration/is-interactive.js';
5
+ import { tryParseSource, traverse, markLegacyFallback } from './ast-parser.js';
6
+
7
+ /**
8
+ * Removes every `<WpEditable ...>...</WpEditable>` / self-closing
9
+ * `<WpEditable ... />` block from `content`, using findHtmlTagEnd's
10
+ * brace/quote-aware scan rather than a naive `[^>]*` regex — a WpEditable's
11
+ * onChange handler commonly contains a TypeScript generic cast like
12
+ * `as Partial<Props>`, whose OWN `>` would end a naive regex match early,
13
+ * leaving the WpEditable tag (and its onChange) completely unstripped and
14
+ * silently defeating any check meant to ignore it.
15
+ */
16
+ function stripWpEditableBlocks(content) {
17
+ let result = '';
18
+ let pos = 0;
19
+ while (true) {
20
+ const idx = content.indexOf('<WpEditable', pos);
21
+ if (idx === -1) {
22
+ result += content.slice(pos);
23
+ break;
24
+ }
25
+ const afterName = content[idx + '<WpEditable'.length];
26
+ if (afterName !== undefined && /[a-zA-Z0-9_]/.test(afterName)) {
27
+ // False match (e.g. <WpEditableFoo>) — not our tag, keep scanning past it.
28
+ result += content.slice(pos, idx + '<WpEditable'.length);
29
+ pos = idx + '<WpEditable'.length;
30
+ continue;
31
+ }
32
+ result += content.slice(pos, idx);
33
+ const tagEnd = findHtmlTagEnd(content, idx);
34
+ if (tagEnd === -1) {
35
+ // Malformed/unmatched tag — stop stripping rather than loop forever.
36
+ result += content.slice(idx);
37
+ break;
38
+ }
39
+ const isSelfClosing = content[tagEnd - 1] === '/';
40
+ if (isSelfClosing) {
41
+ pos = tagEnd + 1;
42
+ } else {
43
+ const closeIdx = content.indexOf('</WpEditable>', tagEnd + 1);
44
+ pos = closeIdx === -1 ? tagEnd + 1 : closeIdx + '</WpEditable>'.length;
45
+ }
46
+ }
47
+ return result;
48
+ }
49
+
50
+ /**
51
+ * Parses a JSX tag's attribute text (everything between the tag name and its
52
+ * closing `>`/`/>`) into `{ name, expr }` pairs — `name="literal"` and
53
+ * `name={expr}` forms. Spread attributes (`{...rest}`) and boolean shorthand
54
+ * (bare `name`) are skipped (returned as null entries filtered out) rather
55
+ * than guessed at.
56
+ */
57
+ function parseJsxAttributes(attrsStr) {
58
+ const attrs = [];
59
+ const re =
60
+ /([a-zA-Z_][\w-]*)\s*=\s*(?:\{((?:[^{}]|\{[^{}]*\})*)\}|"([^"]*)"|'([^']*)')/g;
61
+ let m;
62
+ while ((m = re.exec(attrsStr)) !== null) {
63
+ const name = m[1];
64
+ if (m[2] !== undefined) {
65
+ attrs.push({ name, expr: m[2].trim(), isStringLiteral: false });
66
+ } else {
67
+ const literal = m[3] !== undefined ? m[3] : m[4];
68
+ attrs.push({ name, expr: literal, isStringLiteral: true });
69
+ }
70
+ }
71
+ return attrs;
72
+ }
73
+
74
+ /**
75
+ * Builds a PHP expression for `array('name' => value, ...)` from a nested
76
+ * component call site's JSX attributes, for embedding into a
77
+ * data-forgewp-props JSON blob. Handles the shapes actually seen in
78
+ * compiled output — a plain string literal; `attributes.X` / `attributes['X']`
79
+ * (the dual-host prop-alias rewrite — bareAttrRefsSafely and similar earlier
80
+ * passes already rewrite a plain `{searchPlaceholder}` reference into this
81
+ * form by the time expandNestedComponentTags runs, so this is the MORE common
82
+ * real shape, not the bare identifier); and a bare identifier, for whichever
83
+ * call sites reach this before that rewrite. Anything more complex is
84
+ * DROPPED from the props object rather than risking broken PHP, so the other
85
+ * (safely-resolvable) props still come through.
86
+ *
87
+ * For a bare identifier specifically, PHP's `isset()` decides at RUNTIME
88
+ * whether it ended up as a local variable (e.g. `$searchPlaceholder =
89
+ * $searchPlaceholderProp ?? $searchPlaceholderMeta;`, computed by the
90
+ * separate local-var-extraction pass elsewhere in this compiler) or falls
91
+ * back to the block's own $attributes entry of the same name — this
92
+ * sidesteps needing to know, at the point this JSX is being expanded, which
93
+ * of those two the compiler's other passes will end up choosing (they run
94
+ * at a different stage).
95
+ */
96
+ function buildPhpPropsArrayExpr(attrsStr) {
97
+ const attrs = parseJsxAttributes(attrsStr);
98
+ const parts = [];
99
+ for (const { name, expr, isStringLiteral } of attrs) {
100
+ // setAttributes is a Gutenberg-editor-only callback — always null/inert
101
+ // on the frontend, never a real data prop worth serializing for hydration.
102
+ if (name === 'key' || name === 'ref' || name === 'setAttributes') continue;
103
+ let phpValue;
104
+ const attrAccessMatch = expr.match(
105
+ /^attributes(?:\.([a-zA-Z_$][\w$]*)|\[\s*['"]([^'"]+)['"]\s*\])$/,
106
+ );
107
+ if (isStringLiteral) {
108
+ phpValue = `'${expr.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
109
+ } else if (attrAccessMatch) {
110
+ const attrKey = attrAccessMatch[1] || attrAccessMatch[2];
111
+ phpValue = `($attributes['${attrKey}'] ?? null)`;
112
+ } else if (/^[a-zA-Z_$][\w$]*$/.test(expr)) {
113
+ phpValue = `(isset($${expr}) ? $${expr} : ($attributes['${expr}'] ?? null))`;
114
+ } else {
115
+ continue; // complex expression — skip rather than risk broken PHP
116
+ }
117
+ parts.push(`'${name}' => ${phpValue}`);
118
+ }
119
+ return `array(${parts.join(', ')})`;
120
+ }
121
+
122
+ /**
123
+ * Extract the JSX an `edit`/`save` property (or a named function/const
124
+ * declaration) returns from `code`.
125
+ *
126
+ * AST-based (see ast-parser.js): parses `code` once, locates the target
127
+ * function or object property by name, and reads its returned
128
+ * JSXElement/JSXFragment node directly off the AST — no more brace-balancing
129
+ * text scan trying to (re-)discover where that already-parsed JSX begins and
130
+ * ends, which was misidentifying ternary/paren boundaries (scratch category
131
+ * H: nested ternaries containing fragments, etc.).
132
+ *
133
+ * `code` is frequently a substring produced by older text-slicing callers
134
+ * (`code.substring(searchIndex)`) rather than a standalone-parseable module,
135
+ * so a parse failure falls back to the legacy text-scanning implementation.
136
+ */
137
+ export function extractJsx(code, propertyName) {
138
+ const ast = tryParseSource(code);
139
+ if (ast) {
140
+ try {
141
+ const jsxNode = locateTargetJsx(ast, propertyName, false);
142
+ if (jsxNode) return code.slice(jsxNode.start, jsxNode.end).trim();
143
+ } catch {
144
+ // Fall through to the legacy scanner below.
145
+ }
146
+ }
147
+ // Legacy text-scan fallback deleted (Phase 4 — zero contributions across
148
+ // the entire known theme surface). Marker stays as a field signal.
149
+ markLegacyFallback('php-transpiler:extractJsx-would-have-tried-legacy');
150
+ return null;
151
+ }
152
+
153
+ function isJsxNode(node) {
154
+ return !!node && (node.type === 'JSXElement' || node.type === 'JSXFragment');
155
+ }
156
+
157
+ function isFunctionLikeNode(node) {
158
+ return (
159
+ !!node &&
160
+ (node.type === 'ArrowFunctionExpression' ||
161
+ node.type === 'FunctionExpression')
162
+ );
163
+ }
164
+
165
+ /**
166
+ * Collect the JSX arguments of every `return` statement reachable from
167
+ * `bodyNode` without crossing into a nested function's own body — a
168
+ * `.map(item => { return <li/> })` inside the target function must not be
169
+ * mistaken for the target function's own return.
170
+ */
171
+ function collectTopLevelReturnJsx(bodyNode, out) {
172
+ if (!bodyNode) return;
173
+ switch (bodyNode.type) {
174
+ case 'BlockStatement':
175
+ for (const stmt of bodyNode.body) collectTopLevelReturnJsx(stmt, out);
176
+ break;
177
+ case 'ReturnStatement':
178
+ if (isJsxNode(bodyNode.argument)) out.push(bodyNode.argument);
179
+ break;
180
+ case 'IfStatement':
181
+ collectTopLevelReturnJsx(bodyNode.consequent, out);
182
+ if (bodyNode.alternate) collectTopLevelReturnJsx(bodyNode.alternate, out);
183
+ break;
184
+ case 'TryStatement':
185
+ collectTopLevelReturnJsx(bodyNode.block, out);
186
+ if (bodyNode.handler)
187
+ collectTopLevelReturnJsx(bodyNode.handler.body, out);
188
+ if (bodyNode.finalizer) collectTopLevelReturnJsx(bodyNode.finalizer, out);
189
+ break;
190
+ case 'SwitchStatement':
191
+ for (const c of bodyNode.cases) {
192
+ for (const stmt of c.consequent) collectTopLevelReturnJsx(stmt, out);
193
+ }
194
+ break;
195
+ case 'ForStatement':
196
+ case 'ForInStatement':
197
+ case 'ForOfStatement':
198
+ case 'WhileStatement':
199
+ case 'DoWhileStatement':
200
+ case 'LabeledStatement':
201
+ collectTopLevelReturnJsx(bodyNode.body, out);
202
+ break;
203
+ default:
204
+ break; // Don't descend into function-like nodes or plain expressions.
205
+ }
206
+ }
207
+
208
+ /** `fnNode` is an Arrow/Function/ObjectMethod — anything with a `.body`. */
209
+ function extractJsxFromFunctionNode(fnNode, preferLast) {
210
+ const body = fnNode && fnNode.body;
211
+ if (isJsxNode(body)) return body; // Concise arrow body: () => <div/>
212
+ if (body && body.type === 'BlockStatement') {
213
+ const found = [];
214
+ collectTopLevelReturnJsx(body, found);
215
+ if (found.length === 0) return null;
216
+ return preferLast ? found[found.length - 1] : found[0];
217
+ }
218
+ return null;
219
+ }
220
+
221
+ /**
222
+ * Find a function/property named `name`: an object property/method (the
223
+ * `edit:`/`save:` shape defineBlock({...}) uses), a function declaration, or
224
+ * a const-assigned function — in that priority order, matching the legacy
225
+ * scanner's `propertyName:` → `function propertyName` → `const propertyName`
226
+ * search order.
227
+ */
228
+ function findNamedFunction(ast, name) {
229
+ let objectMatch = null;
230
+ let funcDeclMatch = null;
231
+ let varDeclMatch = null;
232
+
233
+ traverse(ast, {
234
+ ObjectProperty(path) {
235
+ if (objectMatch) return;
236
+ const key = path.node.key;
237
+ const keyName =
238
+ key.type === 'Identifier'
239
+ ? key.name
240
+ : key.type === 'StringLiteral'
241
+ ? key.value
242
+ : null;
243
+ if (keyName === name && isFunctionLikeNode(path.node.value)) {
244
+ objectMatch = path.node.value;
245
+ }
246
+ },
247
+ ObjectMethod(path) {
248
+ if (objectMatch) return;
249
+ const key = path.node.key;
250
+ const keyName =
251
+ key.type === 'Identifier'
252
+ ? key.name
253
+ : key.type === 'StringLiteral'
254
+ ? key.value
255
+ : null;
256
+ if (keyName === name) objectMatch = path.node;
257
+ },
258
+ FunctionDeclaration(path) {
259
+ if (!funcDeclMatch && path.node.id && path.node.id.name === name)
260
+ funcDeclMatch = path.node;
261
+ },
262
+ VariableDeclarator(path) {
263
+ if (
264
+ !varDeclMatch &&
265
+ path.node.id.type === 'Identifier' &&
266
+ path.node.id.name === name &&
267
+ isFunctionLikeNode(path.node.init)
268
+ ) {
269
+ varDeclMatch = path.node.init;
270
+ }
271
+ },
272
+ });
273
+
274
+ return objectMatch || funcDeclMatch || varDeclMatch || null;
275
+ }
276
+
277
+ /** Whole-program fallback: the first function (in source order) that returns JSX. */
278
+ function findFirstJsxReturningFunction(ast, preferLast) {
279
+ let result = null;
280
+ traverse(ast, {
281
+ 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod'(
282
+ path,
283
+ ) {
284
+ if (result) return;
285
+ const jsx = extractJsxFromFunctionNode(path.node, preferLast);
286
+ if (jsx) {
287
+ result = jsx;
288
+ path.stop();
289
+ }
290
+ },
291
+ });
292
+ return result;
293
+ }
294
+
295
+ function locateTargetJsx(ast, propertyName, preferLast) {
296
+ if (propertyName) {
297
+ const fnNode = findNamedFunction(ast, propertyName);
298
+ // Found the named property/decl but it has no JSX (e.g. `edit: () => null`)
299
+ // — legacy never widens the search back out in this case, so neither do we.
300
+ if (fnNode) return extractJsxFromFunctionNode(fnNode, preferLast);
301
+ // Name not found at all — mirrors legacy's `propIndex = 0` whole-code fallback.
302
+ return findFirstJsxReturningFunction(ast, preferLast);
303
+ }
304
+ return findFirstJsxReturningFunction(ast, preferLast);
305
+ }
306
+
307
+ /** AST twin of extractJsxPreferLastReturn: locate `name`'s function and take
308
+ * its LAST top-level returned JSX (the main render path, after early
309
+ * loading/empty-state returns). Null when `code` doesn't parse. */
310
+ function extractJsxAstPreferLast(code, name) {
311
+ const ast = tryParseSource(code);
312
+ if (!ast) return null;
313
+ try {
314
+ const jsxNode = locateTargetJsx(ast, name, true);
315
+ if (jsxNode) return code.slice(jsxNode.start, jsxNode.end).trim();
316
+ } catch {
317
+ // fall through to the legacy scanners at the call site
318
+ }
319
+ return null;
320
+ }
321
+
322
+ export function isFullyParenthesized(expr) {
323
+ if (!expr.startsWith('(') || !expr.endsWith(')')) return false;
324
+ let depth = 0;
325
+ for (let i = 0; i < expr.length; i++) {
326
+ if (expr[i] === '(') depth++;
327
+ else if (expr[i] === ')') {
328
+ depth--;
329
+ if (depth === 0 && i < expr.length - 1) {
330
+ return false;
331
+ }
332
+ }
333
+ }
334
+ return depth === 0;
335
+ }
336
+
337
+ export function parenthesizeTernaryExpression(expr) {
338
+ const questionCount = (expr.replace(/\?\?/g, '').match(/\?/g) || []).length;
339
+ if (questionCount <= 1) return expr;
340
+
341
+ let depth = 0;
342
+ let firstQuestionIdx = -1;
343
+ let firstColonIdx = -1;
344
+ let inSingleQuote = false;
345
+ let inDoubleQuote = false;
346
+ let inBacktick = false;
347
+
348
+ for (let i = 0; i < expr.length; i++) {
349
+ const char = expr[i];
350
+
351
+ if (char === '\\') {
352
+ i++;
353
+ continue;
354
+ }
355
+ if (char === "'" && !inDoubleQuote && !inBacktick) {
356
+ inSingleQuote = !inSingleQuote;
357
+ continue;
358
+ }
359
+ if (char === '"' && !inSingleQuote && !inBacktick) {
360
+ inDoubleQuote = !inDoubleQuote;
361
+ continue;
362
+ }
363
+ if (char === '`' && !inSingleQuote && !inDoubleQuote) {
364
+ inBacktick = !inBacktick;
365
+ continue;
366
+ }
367
+
368
+ if (inSingleQuote || inDoubleQuote || inBacktick) {
369
+ continue;
370
+ }
371
+
372
+ if (char === '(' || char === '{' || char === '[') depth++;
373
+ else if (char === ')' || char === '}' || char === ']') depth--;
374
+ else if (depth === 0) {
375
+ if (char === '?' && (expr[i + 1] === '?' || expr[i + 1] === ':')) {
376
+ i++;
377
+ continue;
378
+ }
379
+ if (char === '?' && firstQuestionIdx === -1) {
380
+ firstQuestionIdx = i;
381
+ } else if (
382
+ char === ':' &&
383
+ firstQuestionIdx !== -1 &&
384
+ firstColonIdx === -1
385
+ ) {
386
+ if (expr[i + 1] === ':') {
387
+ i++;
388
+ continue;
389
+ }
390
+ firstColonIdx = i;
391
+ break;
392
+ }
393
+ }
394
+ }
395
+
396
+ if (firstQuestionIdx === -1 || firstColonIdx === -1) {
397
+ return expr;
398
+ }
399
+
400
+ const cond = expr.substring(0, firstQuestionIdx).trim();
401
+ const truthy = expr.substring(firstQuestionIdx + 1, firstColonIdx).trim();
402
+ const falsy = expr.substring(firstColonIdx + 1).trim();
403
+
404
+ const newTruthy = parenthesizeTernaryExpression(truthy);
405
+ const newFalsy = parenthesizeTernaryExpression(falsy);
406
+
407
+ const wrapTruthy =
408
+ truthy.replace(/\?\?/g, '').includes('?') && !isFullyParenthesized(truthy)
409
+ ? `(${newTruthy})`
410
+ : newTruthy;
411
+ const wrapFalsy =
412
+ falsy.replace(/\?\?/g, '').includes('?') && !isFullyParenthesized(falsy)
413
+ ? `(${newFalsy})`
414
+ : newFalsy;
415
+
416
+ return `${cond} ? ${wrapTruthy} : ${wrapFalsy}`;
417
+ }
418
+
419
+ /**
420
+ * @param {string} jsExpr
421
+ * @param {string[]} blockAttrKeys
422
+ * @param {Set<string>} localVars
423
+ * @param {Set<string>} [freeFunctions] PHP function names that must stay bare (not $var)
424
+ */
425
+ /**
426
+ * Replace calls to unknown JS functions with a safe PHP empty string.
427
+ * Prevents `($resolveBlockPaddingY ?? null)(...)` fatals when imported
428
+ * helpers (or other browser-only functions) have no PHP equivalent.
429
+ *
430
+ * Known PHP helpers / freeFunctions stay as real calls.
431
+ */
432
+ export function neutralizeUnknownJsCalls(expr, freeFunctions = new Set()) {
433
+ if (!expr || typeof expr !== 'string') return expr;
434
+
435
+ const callable = new Set([
436
+ 'esc_attr',
437
+ 'esc_html',
438
+ 'esc_url',
439
+ 'esc_js',
440
+ 'esc_textarea',
441
+ 'is_string',
442
+ 'is_array',
443
+ 'is_object',
444
+ 'is_numeric',
445
+ 'isset',
446
+ 'empty',
447
+ 'floatval',
448
+ 'intval',
449
+ 'strval',
450
+ 'boolval',
451
+ 'count',
452
+ 'strlen',
453
+ 'trim',
454
+ 'sprintf',
455
+ 'printf',
456
+ 'json_encode',
457
+ 'json_decode',
458
+ 'absint',
459
+ 'preg_replace',
460
+ 'explode',
461
+ 'forgewp_resolve_page_link',
462
+ 'wp_kses_post',
463
+ 'wpautop',
464
+ 'Number',
465
+ 'String',
466
+ 'Boolean',
467
+ 'parseInt',
468
+ 'parseFloat',
469
+ 'Math.max',
470
+ 'Math.min',
471
+ 'Math.round',
472
+ 'Math.floor',
473
+ 'Math.ceil',
474
+ 'Math.abs',
475
+ ...freeFunctions,
476
+ ]);
477
+
478
+ let result = '';
479
+ let i = 0;
480
+ while (i < expr.length) {
481
+ const c = expr[i];
482
+ // Preserve string literals
483
+ if (c === "'" || c === '"' || c === '`') {
484
+ const q = c;
485
+ result += c;
486
+ i++;
487
+ while (i < expr.length) {
488
+ if (expr[i] === '\\') {
489
+ result += expr[i] + (expr[i + 1] || '');
490
+ i += 2;
491
+ continue;
492
+ }
493
+ result += expr[i];
494
+ if (expr[i] === q) {
495
+ i++;
496
+ break;
497
+ }
498
+ i++;
499
+ }
500
+ continue;
501
+ }
502
+
503
+ const rest = expr.slice(i);
504
+ const m = rest.match(/^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/);
505
+ if (m) {
506
+ const name = m[1];
507
+ const openIdx = i + m[0].length - 1;
508
+ if (!callable.has(name) && !name.startsWith('forgewp_')) {
509
+ // Find matching close paren for the whole call
510
+ let depth = 0;
511
+ let j = openIdx;
512
+ let inStr = null;
513
+ let esc = false;
514
+ for (; j < expr.length; j++) {
515
+ const ch = expr[j];
516
+ if (inStr) {
517
+ if (esc) esc = false;
518
+ else if (ch === '\\') esc = true;
519
+ else if (ch === inStr) inStr = null;
520
+ continue;
521
+ }
522
+ if (ch === "'" || ch === '"' || ch === '`') {
523
+ inStr = ch;
524
+ continue;
525
+ }
526
+ if (ch === '(') depth++;
527
+ else if (ch === ')') {
528
+ depth--;
529
+ if (depth === 0) {
530
+ // Drop entire call — SSR must not invoke missing JS helpers
531
+ result += "''";
532
+ i = j + 1;
533
+ break;
534
+ }
535
+ }
536
+ }
537
+ if (j < expr.length && depth === 0) continue;
538
+ } else {
539
+ result += m[0];
540
+ i += m[0].length;
541
+ continue;
542
+ }
543
+ }
544
+
545
+ result += c;
546
+ i++;
547
+ }
548
+ return result;
549
+ }
550
+
551
+ // Translates EXPR.replace(<regex literal>, 'replacement') (optionally chained
552
+ // with .trim() and/or .split('sep')) into PHP's preg_replace('/pattern/flags',
553
+ // 'replacement', EXPR) (wrapped in trim(...)/explode('sep', ...) as chained).
554
+ // Without this, a call chain stripping border-prefixed classes out of a
555
+ // dynamic color string (row.color, optional chained, regex-replaced,
556
+ // trimmed, with an || fallback) had no translation path at all and leaked as
557
+ // literal, unexecuted JS text straight into an HTML attribute on the visitor
558
+ // page (e.g. a className prop). JS's "g" flag has no PCRE equivalent —
559
+ // preg_replace already replaces every match by default — so it's simply
560
+ // dropped; other flags (i, m, s, u) pass straight through since they're
561
+ // valid PCRE modifiers too.
562
+ export function translateReplaceTrim(jsExpr) {
563
+ if (!jsExpr || typeof jsExpr !== 'string') return jsExpr;
564
+ const callRegex =
565
+ /([A-Za-z_$][\w$.\[\]'"]*)\.replace\(\s*\/((?:\\.|[^\/\\])*)\/([a-z]*)\s*,\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\s*\)/g;
566
+ let result = jsExpr.replace(
567
+ callRegex,
568
+ (match, subject, pattern, flags, replacement) => {
569
+ const pcreModifiers = flags.replace(/g/g, '');
570
+ return `preg_replace('/${pattern}/${pcreModifiers}', ${replacement}, ${subject})`;
571
+ },
572
+ );
573
+ // Fold a directly-chained `.trim()` or `.split('sep')` into the wrapping
574
+ // call — only when it immediately follows a replace we just translated
575
+ // (identified via the preg_replace(...) text we just produced), so an
576
+ // unrelated `.trim()`/`.split()` elsewhere in the expression is left for
577
+ // the generic handling below. `.split()`'s regex has no PHP method-call
578
+ // equivalent to chain onto a bare function-call result the way JS does
579
+ // (`preg_replace(...).split(...)` isn't valid PHP), so it must be folded
580
+ // into an outer explode(...) call here rather than left to a later,
581
+ // identifier-only `.split()` rule.
582
+ result = result.replace(
583
+ /(preg_replace\((?:[^()]|\([^()]*\))*\))\.trim\(\)/g,
584
+ 'trim($1)',
585
+ );
586
+ result = result.replace(
587
+ /(preg_replace\((?:[^()]|\([^()]*\))*\)|trim\((?:[^()]|\([^()]*\))*\))\.split\(\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\s*\)/g,
588
+ (match, inner, sep) => `explode(${sep}, ${inner})`,
589
+ );
590
+ // A standalone `.trim()` with no preceding `.replace()` (e.g. a plain
591
+ // `facebookUrl.trim()` filter-condition check) — the fold above only
592
+ // covers one already chained onto a just-translated preg_replace(...).
593
+ result = result.replace(
594
+ /([A-Za-z_$][\w$]*(?:\[[^\]]*\])*(?:\.[A-Za-z_$][\w$]*(?:\[[^\]]*\])*)*)\.trim\(\)/g,
595
+ (m, subject) => `trim(${subject})`,
596
+ );
597
+ return result;
598
+ }
599
+
600
+ export function translateJsonParse(jsExpr) {
601
+ if (!jsExpr || typeof jsExpr !== 'string') return jsExpr;
602
+ let result = '';
603
+ let i = 0;
604
+ while (i < jsExpr.length) {
605
+ const rest = jsExpr.slice(i);
606
+ const match = rest.match(/^JSON\s*\.\s*parse\s*\(/);
607
+ if (match) {
608
+ const openIdx = i + match[0].length - 1;
609
+ const closeIdx = findMatchingParenClose(jsExpr, openIdx);
610
+ if (closeIdx !== -1) {
611
+ const inner = jsExpr.substring(openIdx + 1, closeIdx);
612
+ const translatedInner = translateJsonParse(inner);
613
+ result += `json_decode(${translatedInner}, true)`;
614
+ i = closeIdx + 1;
615
+ continue;
616
+ }
617
+ }
618
+ result += jsExpr[i];
619
+ i++;
620
+ }
621
+ return result;
622
+ }
623
+
624
+ /**
625
+ * Finds the index of the backtick that closes a template literal opened at
626
+ * `openIdx`, skipping over `${...}` interpolation bodies (which may contain
627
+ * their own nested braces and quoted strings) so a `}` or a quote character
628
+ * inside an interpolation can't be mistaken for the end of the literal.
629
+ * Returns -1 if unterminated.
630
+ */
631
+ function findMatchingBacktickClose(str, openIdx) {
632
+ let i = openIdx + 1;
633
+ let braceDepth = 0;
634
+ while (i < str.length) {
635
+ const c = str[i];
636
+ if (c === '\\') {
637
+ i += 2;
638
+ continue;
639
+ }
640
+ if (braceDepth === 0 && c === '`') return i;
641
+ if (braceDepth === 0 && c === '$' && str[i + 1] === '{') {
642
+ braceDepth = 1;
643
+ i += 2;
644
+ continue;
645
+ }
646
+ if (braceDepth > 0) {
647
+ if (c === '{') {
648
+ braceDepth++;
649
+ } else if (c === '}') {
650
+ braceDepth--;
651
+ } else if (c === "'" || c === '"') {
652
+ const q = c;
653
+ i++;
654
+ while (i < str.length && str[i] !== q) {
655
+ if (str[i] === '\\') i++;
656
+ i++;
657
+ }
658
+ }
659
+ }
660
+ i++;
661
+ }
662
+ return -1;
663
+ }
664
+
665
+ /**
666
+ * Converts the raw text between a template literal's backticks into a PHP
667
+ * string-concatenation expression. Literal text segments become escaped
668
+ * PHP string literals; each `${...}` interpolation becomes a parenthesized,
669
+ * still-raw-JS fragment (`(expr)`) left for the rest of
670
+ * translateJsExpressionToPhp's pipeline to translate exactly as it would any
671
+ * other part of the expression — this function only unwraps the template
672
+ * literal's own syntax, it doesn't translate the interpolated JS itself.
673
+ */
674
+ function translateTemplateLiteralBody(inner) {
675
+ const parts = [];
676
+ let textBuf = '';
677
+ const flushText = () => {
678
+ if (textBuf !== '') {
679
+ parts.push(`'${textBuf.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`);
680
+ textBuf = '';
681
+ }
682
+ };
683
+ let i = 0;
684
+ while (i < inner.length) {
685
+ const c = inner[i];
686
+ if (c === '\\') {
687
+ textBuf += inner[i + 1] || '';
688
+ i += 2;
689
+ continue;
690
+ }
691
+ if (c === '$' && inner[i + 1] === '{') {
692
+ flushText();
693
+ let depth = 1;
694
+ let j = i + 2;
695
+ while (j < inner.length && depth > 0) {
696
+ const cj = inner[j];
697
+ if (cj === '{') {
698
+ depth++;
699
+ } else if (cj === '}') {
700
+ depth--;
701
+ if (depth === 0) break;
702
+ } else if (cj === "'" || cj === '"') {
703
+ const q = cj;
704
+ j++;
705
+ while (j < inner.length && inner[j] !== q) {
706
+ if (inner[j] === '\\') j++;
707
+ j++;
708
+ }
709
+ }
710
+ j++;
711
+ }
712
+ const exprText = inner.slice(i + 2, j).trim();
713
+ parts.push(exprText === '' ? "''" : `(${exprText})`);
714
+ i = j + 1;
715
+ continue;
716
+ }
717
+ textBuf += c;
718
+ i++;
719
+ }
720
+ flushText();
721
+ if (parts.length === 0) return "''";
722
+ return parts.join(' . ');
723
+ }
724
+
725
+ // Translates a JS template literal (backtick string, optionally with ${}
726
+ // interpolation) into PHP string concatenation. Without this, backtick
727
+ // delimiters pass straight through every later, non-quote-aware regex pass
728
+ // in this pipeline untouched — and a PHP backtick is the shell-exec
729
+ // operator, not a string literal, so the result is syntactically valid but
730
+ // semantically wrong PHP (attempts to shell-exec a garbage string) with no
731
+ // visible error anywhere. Must run first, before any other pass in
732
+ // translateJsExpressionToPhp touches the expression text, so backtick
733
+ // content is converted to safe PHP syntax before anything else can mangle it.
734
+ //
735
+ // `/hotelvergleich/${l.id}` -> '/hotelvergleich/' . (l.id)
736
+ export function translateTemplateLiteral(jsExpr) {
737
+ if (!jsExpr || typeof jsExpr !== 'string') return jsExpr;
738
+ let result = '';
739
+ let i = 0;
740
+ while (i < jsExpr.length) {
741
+ const c = jsExpr[i];
742
+ if (c === "'" || c === '"') {
743
+ const q = c;
744
+ result += c;
745
+ i++;
746
+ while (i < jsExpr.length) {
747
+ if (jsExpr[i] === '\\') {
748
+ result += jsExpr[i] + (jsExpr[i + 1] || '');
749
+ i += 2;
750
+ continue;
751
+ }
752
+ result += jsExpr[i];
753
+ if (jsExpr[i] === q) {
754
+ i++;
755
+ break;
756
+ }
757
+ i++;
758
+ }
759
+ continue;
760
+ }
761
+ if (c === '`') {
762
+ const closeIdx = findMatchingBacktickClose(jsExpr, i);
763
+ if (closeIdx === -1) {
764
+ // Unterminated/unsupported shape — leave untouched rather than risk
765
+ // mangling something this pass doesn't understand.
766
+ result += c;
767
+ i++;
768
+ continue;
769
+ }
770
+ const inner = jsExpr.slice(i + 1, closeIdx);
771
+ result += translateTemplateLiteralBody(inner);
772
+ i = closeIdx + 1;
773
+ continue;
774
+ }
775
+ result += c;
776
+ i++;
777
+ }
778
+ return result;
779
+ }
780
+
781
+ function phpStringLiteral(value) {
782
+ return `'${String(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
783
+ }
784
+
785
+ const WP_DATA_HOOKS = new Set([
786
+ 'useWpTitle',
787
+ 'useWpContent',
788
+ 'useWpExcerpt',
789
+ 'useWpPermalink',
790
+ 'useWpDate',
791
+ 'useWpModifiedDate',
792
+ 'useWpAuthor',
793
+ 'useWpFeaturedImage',
794
+ 'useWpCustomField',
795
+ 'useWpField',
796
+ 'useWpMeta',
797
+ ]);
798
+
799
+ function translateWpDataHookCall(node, source, blockAttrKeys, localVars, freeFunctions) {
800
+ if (
801
+ node.callee.type !== 'Identifier' ||
802
+ !WP_DATA_HOOKS.has(node.callee.name) ||
803
+ node.arguments.some((arg) => arg.type === 'SpreadElement')
804
+ ) {
805
+ return null;
806
+ }
807
+
808
+ const name = node.callee.name;
809
+ const noArgHooks = {
810
+ useWpTitle: 'get_the_title()',
811
+ useWpContent: 'get_the_content()',
812
+ useWpExcerpt: 'get_the_excerpt()',
813
+ useWpPermalink: 'get_permalink()',
814
+ useWpDate: 'get_the_date()',
815
+ useWpModifiedDate: 'get_the_modified_date()',
816
+ useWpAuthor: 'get_the_author()',
817
+ useWpFeaturedImage: "get_the_post_thumbnail_url(get_the_ID(), 'full')",
818
+ };
819
+ if (Object.prototype.hasOwnProperty.call(noArgHooks, name)) {
820
+ return node.arguments.length === 0 ? noArgHooks[name] : null;
821
+ }
822
+ if (node.arguments.length < 1 || node.arguments.length > 2) return null;
823
+
824
+ const fieldNode = node.arguments[0];
825
+ const fieldExpr =
826
+ fieldNode.type === 'StringLiteral'
827
+ ? phpStringLiteral(fieldNode.value)
828
+ : `sanitize_key((string)(${translateJsExpressionToPhp(
829
+ source.slice(fieldNode.start, fieldNode.end),
830
+ blockAttrKeys,
831
+ localVars,
832
+ freeFunctions,
833
+ )}))`;
834
+ const fallbackExpr =
835
+ node.arguments.length === 2
836
+ ? translateJsExpressionToPhp(
837
+ source.slice(node.arguments[1].start, node.arguments[1].end),
838
+ blockAttrKeys,
839
+ localVars,
840
+ freeFunctions,
841
+ )
842
+ : "''";
843
+
844
+ return `forgewp_get_meta_value(${fieldExpr}, ${fallbackExpr}, false, null, false)`;
845
+ }
846
+
847
+ function extractWpDataHookCalls(expression, blockAttrKeys, localVars, freeFunctions) {
848
+ if (!/\buseWp(?:Title|Content|Excerpt|Permalink|Date|ModifiedDate|Author|FeaturedImage|CustomField|Field|Meta)\s*\(/.test(expression)) {
849
+ return { expression, replacements: [] };
850
+ }
851
+
852
+ const ast = tryParseSource(expression);
853
+ if (!ast) return { expression, replacements: [] };
854
+
855
+ const replacements = [];
856
+ traverse(ast, {
857
+ CallExpression(path) {
858
+ const phpExpression = translateWpDataHookCall(
859
+ path.node,
860
+ expression,
861
+ blockAttrKeys,
862
+ localVars,
863
+ freeFunctions,
864
+ );
865
+ if (!phpExpression) return;
866
+
867
+ let ancestor = path.parentPath;
868
+ while (ancestor) {
869
+ if (
870
+ ancestor.node?.type === 'CallExpression' &&
871
+ ancestor.node.callee?.type === 'Identifier' &&
872
+ WP_DATA_HOOKS.has(ancestor.node.callee.name)
873
+ ) {
874
+ return;
875
+ }
876
+ ancestor = ancestor.parentPath;
877
+ }
878
+
879
+ replacements.push({
880
+ start: path.node.start,
881
+ end: path.node.end,
882
+ phpExpression,
883
+ });
884
+ },
885
+ });
886
+
887
+ let translated = expression;
888
+ const tokens = [];
889
+ for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
890
+ const token = phpStringLiteral(`__FORGEWP_DATA_HOOK_${tokens.length}__`);
891
+ translated =
892
+ translated.slice(0, replacement.start) +
893
+ token +
894
+ translated.slice(replacement.end);
895
+ tokens.push({ token, phpExpression: replacement.phpExpression });
896
+ }
897
+ return { expression: translated, replacements: tokens };
898
+ }
899
+
900
+ export function translateJsExpressionToPhp(
901
+ jsExpr,
902
+ blockAttrKeys = [],
903
+ localVars = new Set(),
904
+ freeFunctions = new Set(),
905
+ ) {
906
+ const wpHookResult = extractWpDataHookCalls(
907
+ jsExpr,
908
+ blockAttrKeys,
909
+ localVars,
910
+ freeFunctions,
911
+ );
912
+ const skipWords = new Set([
913
+ 'true',
914
+ 'false',
915
+ 'null',
916
+ 'undefined',
917
+ 'attributes',
918
+ 'props',
919
+ 'esc_attr',
920
+ 'esc_html',
921
+ 'esc_url',
922
+ 'esc_js',
923
+ 'esc_textarea',
924
+ 'is_string',
925
+ 'is_array',
926
+ 'is_object',
927
+ 'is_numeric',
928
+ 'isset',
929
+ 'empty',
930
+ 'json_decode',
931
+ 'json_encode',
932
+ 'Number',
933
+ 'String',
934
+ 'Boolean',
935
+ 'parseInt',
936
+ 'parseFloat',
937
+ 'useWpPageLink',
938
+ 'forgewp_resolve_image_source',
939
+ 'count',
940
+ 'array_filter',
941
+ 'array_map',
942
+ 'explode',
943
+ 'trim',
944
+ 'array',
945
+ 'preg_replace',
946
+ ]);
947
+ for (const fn of freeFunctions) {
948
+ skipWords.add(fn);
949
+ }
950
+
951
+ // Replace ?. with . first
952
+ let cleanedExpr = wpHookResult.expression
953
+ .replace(/\?\./g, '.')
954
+ .replace(/\bresolveWpAsset\s*\(/g, 'forgewp_resolve_image_source(');
955
+
956
+ // Must run before every other pass below — they aren't backtick-aware and
957
+ // would otherwise mangle a template literal's text/interpolation syntax.
958
+ cleanedExpr = translateTemplateLiteral(cleanedExpr);
959
+
960
+ cleanedExpr = translateJsonParse(cleanedExpr);
961
+ cleanedExpr = translateReplaceTrim(cleanedExpr);
962
+
963
+ // Replace .length with count((array)(...)) for PHP 8 compatibility
964
+ cleanedExpr = cleanedExpr.replace(
965
+ /([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^\]]+\])*)\.length\b/g,
966
+ 'count((array)($1))',
967
+ );
968
+
969
+ // Neutralize browser/theme helpers with no PHP twin (padding maps, etc.)
970
+ cleanedExpr = neutralizeUnknownJsCalls(cleanedExpr, freeFunctions);
971
+
972
+ // First convert dot notation for properties: someVar.prop -> someVar['prop']
973
+ let phpExpr = cleanedExpr.replace(
974
+ /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`[^`]*`|(\b(?:attributes|props))\b\.([a-zA-Z0-9_-]+)(?![a-zA-Z0-9_-])(?!\.)|(\b(?:attributes|props))\b\.([a-zA-Z0-9_-]+)(?![a-zA-Z0-9_-])(?=\.)|(?<!\b(?:attributes|props))\.([a-zA-Z0-9_-]+)/g,
975
+ (
976
+ match,
977
+ attrGroup,
978
+ attrNextGroup,
979
+ attrGroup2,
980
+ attrNextGroup2,
981
+ generalProp,
982
+ ) => {
983
+ if (
984
+ match.startsWith("'") ||
985
+ match.startsWith('"') ||
986
+ match.startsWith('`')
987
+ ) {
988
+ return match;
989
+ }
990
+ if (generalProp) {
991
+ return `['${generalProp}']`;
992
+ }
993
+ if (attrGroup && attrNextGroup) {
994
+ if (localVars.has(attrNextGroup)) {
995
+ return `($${attrNextGroup} ?? null)`;
996
+ }
997
+ return `($attributes['${attrNextGroup}'] ?? null)`;
998
+ }
999
+ if (attrGroup2 && attrNextGroup2) {
1000
+ if (localVars.has(attrNextGroup2)) {
1001
+ return `$${attrNextGroup2}`;
1002
+ }
1003
+ return `$attributes['${attrNextGroup2}']`;
1004
+ }
1005
+ return match;
1006
+ },
1007
+ );
1008
+
1009
+ phpExpr = phpExpr.replace(
1010
+ /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,
1011
+ (match, offset, str) => {
1012
+ if (match.startsWith("'") || match.startsWith('"')) {
1013
+ return match;
1014
+ }
1015
+ // Already a PHP variable ($row, $attributes, …) — do not re-wrap
1016
+ if (offset > 0 && str[offset - 1] === '$') {
1017
+ return match;
1018
+ }
1019
+ if (skipWords.has(match)) {
1020
+ return match;
1021
+ }
1022
+ // Free function call: name( → keep bare name
1023
+ if (freeFunctions.has(match)) {
1024
+ return match;
1025
+ }
1026
+ if (localVars.has(match)) {
1027
+ const nextChar = str[offset + match.length];
1028
+ if (nextChar === '.' || nextChar === '[') {
1029
+ return `$${match}`;
1030
+ }
1031
+ return `($${match} ?? null)`;
1032
+ }
1033
+ if (blockAttrKeys.includes(match)) {
1034
+ const nextChar = str[offset + match.length];
1035
+ if (nextChar === '.' || nextChar === '[') {
1036
+ return `$attributes['${match}']`;
1037
+ }
1038
+ return `($attributes['${match}'] ?? null)`;
1039
+ }
1040
+ // "XProp" is the dual-host naming convention for a function parameter
1041
+ // destructured from a block's own attribute of the same name (e.g.
1042
+ // `{ title: titleProp }`, fed in via `<HeroSection {...props.attributes} />`
1043
+ // in the compiled editor). `titleProp` itself never appears in
1044
+ // blockAttrKeys (only `title` does), so without this it fell through to
1045
+ // the generic bare-identifier case below — `($titleProp ?? null)`, a PHP
1046
+ // variable that's never actually assigned anywhere, always null. That
1047
+ // silently discarded every block's own attribute values (edited/saved
1048
+ // in the block editor) on the frontend, permanently falling back to
1049
+ // whichever *Meta (useWpMeta / page-template ACF) value the component
1050
+ // also reads — confirmed live: block edits persisted correctly and
1051
+ // showed in the editor, but never appeared for visitors.
1052
+ if (match.endsWith('Prop') && match.length > 4 && !localVars.has(match)) {
1053
+ const attrKey = match.slice(0, -4);
1054
+ if (blockAttrKeys.includes(attrKey)) {
1055
+ const nextChar = str[offset + match.length];
1056
+ if (nextChar === '.' || nextChar === '[') {
1057
+ return `$attributes['${attrKey}']`;
1058
+ }
1059
+ return `($attributes['${attrKey}'] ?? null)`;
1060
+ }
1061
+ }
1062
+ // Loop vars already rewritten to $row['x'] may still leave bare identifiers in mixed expr —
1063
+ // only $prefix when clearly a simple JS identifier (not PHP keywords we missed)
1064
+ const nextChar = str[offset + match.length];
1065
+ if (nextChar === '[' || nextChar === '-') {
1066
+ // e.g. leftover from broken `$($row` — leave alone if looks wrong
1067
+ return match;
1068
+ }
1069
+ return `($${match} ?? null)`;
1070
+ },
1071
+ );
1072
+
1073
+ // Wrap any raw multi-level property access chains in ( ... ?? null)
1074
+ phpExpr = phpExpr.replace(
1075
+ /(\$(?:attributes|[a-zA-Z0-9_]+)(?:\[\s*(['"])[a-zA-Z0-9_-]+\2\s*\]){2,})/g,
1076
+ '($1 ?? null)',
1077
+ );
1078
+
1079
+ const parenthesized = parenthesizeTernaryExpression(phpExpr);
1080
+
1081
+ // Replace JS logical OR (||) with PHP Elvis operator (?:)
1082
+ let finalPhpExpr = parenthesized.replace(/\|\|/g, '?:');
1083
+
1084
+ const questionCount = (
1085
+ finalPhpExpr.replace(/\?\?/g, '').replace(/\?:/g, '').match(/\?/g) || []
1086
+ ).length;
1087
+ if (questionCount >= 1 && !isFullyParenthesized(finalPhpExpr)) {
1088
+ finalPhpExpr = `(${finalPhpExpr})`;
1089
+ }
1090
+
1091
+ for (const replacement of wpHookResult.replacements) {
1092
+ finalPhpExpr = finalPhpExpr.replace(
1093
+ replacement.token,
1094
+ replacement.phpExpression,
1095
+ );
1096
+ }
1097
+ return finalPhpExpr;
1098
+ }
1099
+
1100
+ export function extractCurlyExpression(str, startPos) {
1101
+ let depth = 1;
1102
+ let pos = startPos;
1103
+ let inQuote = false;
1104
+ let quoteChar = null;
1105
+ while (pos < str.length && depth > 0) {
1106
+ const char = str[pos];
1107
+ if (inQuote) {
1108
+ if (char === '\\') {
1109
+ pos += 2;
1110
+ continue;
1111
+ }
1112
+ if (char === quoteChar) {
1113
+ inQuote = false;
1114
+ }
1115
+ } else {
1116
+ if (char === '"' || char === "'" || char === '`') {
1117
+ inQuote = true;
1118
+ quoteChar = char;
1119
+ } else if (char === '{') {
1120
+ depth++;
1121
+ } else if (char === '}') {
1122
+ depth--;
1123
+ }
1124
+ }
1125
+ pos++;
1126
+ }
1127
+ if (depth === 0) {
1128
+ return str.substring(startPos, pos - 1);
1129
+ }
1130
+ return null;
1131
+ }
1132
+
1133
+ export function extractJsxByTagBalancing(code) {
1134
+ const startMatch = code.match(/<[a-zA-Z]|<>/);
1135
+ if (!startMatch) return null;
1136
+ const startIndex = startMatch.index;
1137
+
1138
+ let index = startIndex;
1139
+ let tagStack = [];
1140
+ let curlyDepth = 0;
1141
+ let inQuote = null;
1142
+ let esc = false;
1143
+
1144
+ while (index < code.length) {
1145
+ const c = code[index];
1146
+
1147
+ if (curlyDepth > 0) {
1148
+ if (inQuote) {
1149
+ if (esc) {
1150
+ esc = false;
1151
+ } else if (c === '\\') {
1152
+ esc = true;
1153
+ } else if (c === inQuote) {
1154
+ inQuote = null;
1155
+ }
1156
+ index++;
1157
+ continue;
1158
+ }
1159
+ if (c === "'" || c === '"' || c === '`') {
1160
+ inQuote = c;
1161
+ index++;
1162
+ continue;
1163
+ }
1164
+ if (c === '{') {
1165
+ curlyDepth++;
1166
+ index++;
1167
+ continue;
1168
+ }
1169
+ if (c === '}') {
1170
+ curlyDepth--;
1171
+ index++;
1172
+ continue;
1173
+ }
1174
+ } else {
1175
+ if (c === '{') {
1176
+ curlyDepth = 1;
1177
+ index++;
1178
+ continue;
1179
+ }
1180
+ }
1181
+
1182
+ if (c === '<') {
1183
+ if (code.substring(index, index + 5) === '<?php') {
1184
+ const phpEnd = code.indexOf('?>', index);
1185
+ if (phpEnd !== -1) {
1186
+ index = phpEnd + 2;
1187
+ continue;
1188
+ }
1189
+ }
1190
+ if (code.substring(index, index + 4) === '<!--') {
1191
+ const commentEnd = code.indexOf('-->', index);
1192
+ if (commentEnd !== -1) {
1193
+ index = commentEnd + 3;
1194
+ continue;
1195
+ }
1196
+ }
1197
+
1198
+ const isCloseTag = code[index + 1] === '/';
1199
+ const tagMatch = isCloseTag
1200
+ ? code.substring(index).match(/^<\/([A-Za-z][A-Za-z0-9_-]*|<>)/)
1201
+ : code.substring(index).match(/^<([A-Za-z][A-Za-z0-9_-]*|<>)/);
1202
+
1203
+ if (tagMatch) {
1204
+ if (isCloseTag) {
1205
+ const tagEnd = findHtmlTagEnd(code, index);
1206
+ if (tagEnd === -1) break;
1207
+ const tagName = tagMatch[1];
1208
+ if (
1209
+ tagStack.length > 0 &&
1210
+ tagStack[tagStack.length - 1] === tagName
1211
+ ) {
1212
+ tagStack.pop();
1213
+ if (tagStack.length === 0) {
1214
+ return code.substring(startIndex, tagEnd + 1);
1215
+ }
1216
+ }
1217
+ index = tagEnd + 1;
1218
+ continue;
1219
+ } else {
1220
+ const tagEnd = findHtmlTagEnd(code, index);
1221
+ if (tagEnd === -1) break;
1222
+ const tagName = tagMatch[1];
1223
+ const tagContent = code.substring(index + 1, tagEnd).trim();
1224
+ const isSelfClosing =
1225
+ tagContent.endsWith('/') ||
1226
+ ['img', 'input', 'br', 'hr', 'meta', 'link'].includes(
1227
+ tagName.toLowerCase(),
1228
+ );
1229
+ if (!isSelfClosing) {
1230
+ tagStack.push(tagName);
1231
+ } else {
1232
+ if (tagStack.length === 0) {
1233
+ return code.substring(startIndex, tagEnd + 1);
1234
+ }
1235
+ }
1236
+ index = tagEnd + 1;
1237
+ continue;
1238
+ }
1239
+ }
1240
+ }
1241
+ index++;
1242
+ }
1243
+ return null;
1244
+ }
1245
+
1246
+ const SKIP_NESTED_COMPONENTS = new Set([
1247
+ 'WpLink',
1248
+ 'WpEditable',
1249
+ 'Button',
1250
+ 'Hydrate',
1251
+ 'WpHead',
1252
+ 'WpImage',
1253
+ 'WpRepeater',
1254
+ 'WpIcon',
1255
+ ]);
1256
+
1257
+ function findSameFileComponentSource(compName, sourceCode) {
1258
+ const ast = tryParseSource(sourceCode);
1259
+ if (!ast) return null;
1260
+
1261
+ let componentNode = null;
1262
+ traverse(ast, {
1263
+ FunctionDeclaration(path) {
1264
+ if (path.node.id?.name === compName) {
1265
+ componentNode = path.node;
1266
+ path.stop();
1267
+ }
1268
+ },
1269
+ VariableDeclarator(path) {
1270
+ if (
1271
+ path.node.id.type === 'Identifier' &&
1272
+ path.node.id.name === compName &&
1273
+ ['ArrowFunctionExpression', 'FunctionExpression'].includes(
1274
+ path.node.init?.type,
1275
+ )
1276
+ ) {
1277
+ componentNode = path.node.init;
1278
+ path.stop();
1279
+ }
1280
+ },
1281
+ });
1282
+
1283
+ return componentNode
1284
+ ? sourceCode.slice(componentNode.start, componentNode.end)
1285
+ : null;
1286
+ }
1287
+
1288
+ function canInlineSameFileEditorComponent(
1289
+ compName,
1290
+ componentSource,
1291
+ callSiteAttrsStr,
1292
+ ) {
1293
+ const ast = tryParseSource(componentSource);
1294
+ if (!ast) return false;
1295
+ const component = findNamedFunction(ast, compName);
1296
+ if (!component) return false;
1297
+
1298
+ let bodyExpression = component.body;
1299
+ if (bodyExpression?.type === 'BlockStatement') {
1300
+ const statements = bodyExpression.body;
1301
+ const returnIndex = statements.length - 1;
1302
+ if (
1303
+ returnIndex < 0 ||
1304
+ statements[returnIndex].type !== 'ReturnStatement' ||
1305
+ statements
1306
+ .slice(0, returnIndex)
1307
+ .some((statement) => statement.type !== 'VariableDeclaration')
1308
+ ) {
1309
+ return false;
1310
+ }
1311
+ bodyExpression = statements[returnIndex].argument;
1312
+ }
1313
+ if (
1314
+ bodyExpression?.type !== 'JSXElement' &&
1315
+ bodyExpression?.type !== 'JSXFragment'
1316
+ ) {
1317
+ return false;
1318
+ }
1319
+
1320
+ const firstParam =
1321
+ component.params?.[0]?.type === 'TSParameterProperty'
1322
+ ? component.params[0].parameter
1323
+ : component.params?.[0];
1324
+ if (firstParam?.type !== 'ObjectPattern') {
1325
+ return !firstParam
1326
+ ? callSiteAttrsStr.trim() === ''
1327
+ : firstParam.type === 'Identifier' &&
1328
+ /\.\.\.\s*attributes\b/.test(callSiteAttrsStr);
1329
+ }
1330
+
1331
+ const hasAttributeSpread = /\.\.\.\s*attributes\b/.test(callSiteAttrsStr);
1332
+ const callSiteProps = new Set(
1333
+ parseJsxAttributes(callSiteAttrsStr).map(({ name }) => name),
1334
+ );
1335
+ return firstParam.properties.every((property) => {
1336
+ if (property.type === 'RestElement') return true;
1337
+ if (property.type !== 'ObjectProperty') return false;
1338
+ const key = property.key.name || property.key.value;
1339
+ if (key === 'children') return true;
1340
+ return callSiteProps.has(key) || (hasAttributeSpread && key !== 'setAttributes');
1341
+ });
1342
+ }
1343
+
1344
+ export function resolveImportedComponentJsx(
1345
+ compName,
1346
+ sourceCode,
1347
+ sourceFilePath,
1348
+ themeRoot,
1349
+ mode = 'editor',
1350
+ callSiteAttrsStr = '',
1351
+ callSiteChildrenStr = '',
1352
+ ) {
1353
+ const importRegex = new RegExp(
1354
+ `import\\s+(?:\\{\\s*${compName}\\s*\\}|${compName})\\s+from\\s+["']([^"']+)["']`,
1355
+ );
1356
+ const match = sourceCode.match(importRegex);
1357
+ let finalPath = '';
1358
+ if (match) {
1359
+ const importPath = match[1];
1360
+ let resolvedPath = '';
1361
+ if (importPath.startsWith('@/')) {
1362
+ resolvedPath = path.resolve(
1363
+ themeRoot,
1364
+ importPath.replace('@/', './src/'),
1365
+ );
1366
+ } else {
1367
+ resolvedPath = path.resolve(path.dirname(sourceFilePath), importPath);
1368
+ }
1369
+ for (const ext of ['.tsx', '.jsx', '/index.tsx', '/index.jsx']) {
1370
+ if (existsSync(resolvedPath + ext)) {
1371
+ finalPath = resolvedPath + ext;
1372
+ break;
1373
+ }
1374
+ }
1375
+ if (
1376
+ !finalPath &&
1377
+ existsSync(resolvedPath) &&
1378
+ statSync(resolvedPath).isFile()
1379
+ ) {
1380
+ finalPath = resolvedPath;
1381
+ }
1382
+ } else {
1383
+ const sameFileSource = findSameFileComponentSource(compName, sourceCode);
1384
+ if (
1385
+ sameFileSource &&
1386
+ (mode === 'php' ||
1387
+ canInlineSameFileEditorComponent(
1388
+ compName,
1389
+ sameFileSource,
1390
+ callSiteAttrsStr,
1391
+ ))
1392
+ ) {
1393
+ finalPath = sourceFilePath;
1394
+ }
1395
+ }
1396
+ if (!finalPath) return null;
1397
+
1398
+ try {
1399
+ // readComponentSource (not raw readFileSync): the nested component may
1400
+ // itself have been auto-split, in which case its rewritten shell — not
1401
+ // the dev's original file content — is the real source of truth.
1402
+ const compContent = readComponentSource(finalPath);
1403
+ const componentSource =
1404
+ finalPath === sourceFilePath
1405
+ ? findSameFileComponentSource(compName, compContent)
1406
+ : compContent;
1407
+ if (!componentSource) return null;
1408
+
1409
+ // Strip <WpEditable ...>...</WpEditable> before the handler check below —
1410
+ // same reasoning as is-interactive.js's isAttributeOfWpEditable: WpEditable's
1411
+ // onChange is inert on the frontend and shouldn't by itself count as live-data.
1412
+ const compContentForHandlerCheck = stripWpEditableBlocks(componentSource);
1413
+
1414
+ // Strip import statements before the hook-usage checks below — an
1415
+ // auto-split shell keeps its original (now partly unused) import list
1416
+ // verbatim (island-split.js's buildShellSource never trims imports, only
1417
+ // the relocated declarations/JSX), so a leftover `import { useWpQuery }`
1418
+ // whose only call site moved into an extracted island would otherwise
1419
+ // still match these word-boundary regexes against the bare import line
1420
+ // and falsely brand the whole shell a live-data island.
1421
+ const compContentForHookCheck = componentSource.replace(
1422
+ /^\s*import\s[^;]*;/gm,
1423
+ '',
1424
+ );
1425
+
1426
+ // Live-data / stateful islands cannot be safely inlined into the editor IIFE:
1427
+ // - React hooks (useState/useEffect/…) won't run in new Function()
1428
+ // - useWpQuery / useWpTerms early-return JSX leaves free vars like `terms`
1429
+ // undefined when only the last return is extracted
1430
+ // - an inline on[A-Z] handler (e.g. onClick) is just as real an
1431
+ // interactivity signal as a hook — a purely event-driven island (no
1432
+ // hooks at all, e.g. a click handler auto-extracted by the island-split
1433
+ // compiler pass) would otherwise fall through and get silently inlined
1434
+ // as static markup, never wired up to any hydration boundary
1435
+ // Show a stable placeholder; the real island still hydrates on the visitor page.
1436
+ const isLiveDataIsland =
1437
+ /\buse(State|Effect|Reducer|LayoutEffect|ImperativeHandle)\b/.test(
1438
+ compContentForHookCheck,
1439
+ ) ||
1440
+ /\bReact\.use(State|Effect|Reducer)\b/.test(compContentForHookCheck) ||
1441
+ /\buseWp(Query|Terms|SearchParams|Location|Search)\b/.test(
1442
+ compContentForHookCheck,
1443
+ ) ||
1444
+ /\buseIsEditorPreview\b/.test(compContentForHookCheck) ||
1445
+ /\bon[A-Z][a-zA-Z]*\s*=/.test(compContentForHandlerCheck);
1446
+
1447
+ if (isLiveDataIsland) {
1448
+ // render.php is the block's real frontend output — the editor-only "interactive
1449
+ // preview" placeholder must never end up here (it would replace the actual
1450
+ // component for every visitor). Emit a proper nested hydration boundary instead,
1451
+ // matching the same data-forgewp-hydrate contract used for the top-level block
1452
+ // wrapper; Smart Discovery already builds this component its own JS chunk since
1453
+ // it uses live-data hooks, so the client hydrator can mount it directly.
1454
+ if (mode === 'php') {
1455
+ const islandSlug = compName
1456
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
1457
+ .toLowerCase();
1458
+ // Nested islands need their own props the same way the top-level block
1459
+ // wrapper does (data-forgewp-props) — without this, whatever the JSX
1460
+ // call site actually passed (e.g. searchPlaceholder={searchPlaceholder})
1461
+ // never reaches the client-hydrated component at all, silently landing
1462
+ // as undefined post-hydration even though the attribute clearly has a
1463
+ // value server-side.
1464
+ const propsArrayExpr = buildPhpPropsArrayExpr(callSiteAttrsStr);
1465
+ const propsAttr = `data-forgewp-props="<?php echo esc_attr( json_encode( ${propsArrayExpr} ) ); ?>" `;
1466
+ const hydrationBoundary =
1467
+ `<div className="forgewp-hydrate-boundary" ` +
1468
+ `data-forgewp-hydrate="${islandSlug}" ` +
1469
+ propsAttr +
1470
+ `data-forgewp-trigger="visible" ` +
1471
+ `style={{display:'block'}}>` +
1472
+ `</div>`;
1473
+ return {
1474
+ jsx: hydrationBoundary,
1475
+ sourceCode: compContent,
1476
+ sourceFilePath: finalPath,
1477
+ };
1478
+ }
1479
+
1480
+ // Parent may own dual-host / WpEditable fields even when the nested island
1481
+ // is interactive — guide editors to the sidebar and any canvas fields.
1482
+ const parentHasEditables =
1483
+ /\bWpEditable\b/.test(sourceCode) ||
1484
+ /\bsetAttributes\b/.test(sourceCode) ||
1485
+ /\bpickEditable\b/.test(sourceCode) ||
1486
+ /\bdefineEditable\b/.test(sourceCode) ||
1487
+ /\bmergeEditable\b/.test(sourceCode);
1488
+
1489
+ const hasLiveQuery = /\buseWp(Query|Terms)\b/.test(compContent);
1490
+
1491
+ // Keep guidance free of double-quotes so JSX → createElement string
1492
+ // coercion never breaks the editor Function() body.
1493
+ const guidance = parentHasEditables
1494
+ ? hasLiveQuery
1495
+ ? `This section loads live data (hotels, terms, posts) on the visitor page. ` +
1496
+ `Edit headings and labels in the block sidebar under Block Settings, ` +
1497
+ `or use any inline fields shown on the canvas above this box. ` +
1498
+ `The live grid/list appears on the frontend after save.`
1499
+ : `This section is interactive on the live site (forms, state, live data). ` +
1500
+ `Edit text and options in the block sidebar under Block Settings, ` +
1501
+ `or use any inline fields shown on the canvas above/below this box. ` +
1502
+ `The full interactive UI appears on the visitor page.`
1503
+ : hasLiveQuery
1504
+ ? `This section loads live data on the visitor page (not in the editor canvas). ` +
1505
+ `Preview the full grid/list on the frontend after publishing.`
1506
+ : `This section is interactive on the live site (forms, state, live data). ` +
1507
+ `The full UI appears on the visitor page - use the canvas/sidebar when ` +
1508
+ `this block exposes editable fields.`;
1509
+
1510
+ const placeholder =
1511
+ `<div className="forgewp-editor-island-placeholder" ` +
1512
+ `style={{padding:'14px 16px',border:'1px dashed #c3c4c7',borderRadius:'8px',` +
1513
+ `background:'#f6f7f7',color:'#646970',fontSize:'12px',lineHeight:'1.55'}}>` +
1514
+ `<strong style={{display:'block',marginBottom:'6px',color:'#1d2327',fontSize:'13px'}}>` +
1515
+ `${compName} - interactive preview</strong>` +
1516
+ `<span style={{display:'block'}}>${guidance}</span>` +
1517
+ `</div>`;
1518
+ return {
1519
+ jsx: placeholder,
1520
+ sourceCode: compContent,
1521
+ sourceFilePath: finalPath,
1522
+ };
1523
+ }
1524
+
1525
+ const funcIndex = compContent.indexOf(`function ${compName}`);
1526
+ const constIndex = compContent.indexOf(`const ${compName}`);
1527
+ // default export: export default function Comp / export default Comp
1528
+ const defaultFn = compContent.indexOf(
1529
+ `export default function ${compName}`,
1530
+ );
1531
+ const searchIndex =
1532
+ defaultFn !== -1 ? defaultFn : funcIndex !== -1 ? funcIndex : constIndex;
1533
+ if (searchIndex === -1) return null;
1534
+
1535
+ // Prefer the last top-level return in the function body (main render
1536
+ // path). Early returns inside if/try often are loading/success branches
1537
+ // and must not be the only thing expanded into the parent block canvas.
1538
+ // AST-first (locateTargetJsx with preferLast — the whole module is clean
1539
+ // TSX here, so this virtually always succeeds); the legacy brace-depth
1540
+ // text scans below remain as the fallback chain.
1541
+ let compJsx = extractJsxAstPreferLast(compContent, compName);
1542
+ if (!compJsx) {
1543
+ markLegacyFallback(
1544
+ 'php-transpiler:resolveImportedComponentJsx-extraction',
1545
+ );
1546
+ compJsx =
1547
+ extractJsx(compContent.substring(searchIndex), compName) ||
1548
+ extractJsx(compContent, compName);
1549
+ }
1550
+ if (!compJsx) {
1551
+ const sub = compContent.substring(searchIndex);
1552
+ const returnMatch = sub.match(/return\s*\(\s*(<[\s\S]*?>)\s*\)/);
1553
+ if (returnMatch) {
1554
+ compJsx = returnMatch[1];
1555
+ } else {
1556
+ const returnMatchSingle = sub.match(/return\s+(<[\s\S]*?>);/);
1557
+ if (returnMatchSingle) {
1558
+ compJsx = returnMatchSingle[1];
1559
+ }
1560
+ }
1561
+ }
1562
+ if (!compJsx) return null;
1563
+ if (mode === 'editor') {
1564
+ let componentParams = null;
1565
+ let componentPath = null;
1566
+ const componentAst = tryParseSource(componentSource);
1567
+ if (componentAst) {
1568
+ traverse(componentAst, {
1569
+ FunctionDeclaration(path) {
1570
+ if (path.node.id?.name === compName) {
1571
+ componentParams = path.node.params;
1572
+ componentPath = path;
1573
+ path.stop();
1574
+ }
1575
+ },
1576
+ FunctionExpression(path) {
1577
+ if (path.node.id?.name === compName) {
1578
+ componentParams = path.node.params;
1579
+ componentPath = path;
1580
+ path.stop();
1581
+ }
1582
+ },
1583
+ VariableDeclarator(path) {
1584
+ if (
1585
+ path.node.id.type === 'Identifier' &&
1586
+ path.node.id.name === compName &&
1587
+ ['ArrowFunctionExpression', 'FunctionExpression'].includes(
1588
+ path.node.init?.type,
1589
+ )
1590
+ ) {
1591
+ componentParams = path.node.init.params;
1592
+ componentPath = path.get('init');
1593
+ path.stop();
1594
+ }
1595
+ },
1596
+ });
1597
+ }
1598
+
1599
+ const firstParam =
1600
+ componentParams?.[0]?.type === 'TSParameterProperty'
1601
+ ? componentParams[0].parameter
1602
+ : componentParams?.[0];
1603
+ let childrenName = null;
1604
+ let restName = null;
1605
+ if (firstParam?.type === 'ObjectPattern') {
1606
+ for (const property of firstParam.properties) {
1607
+ if (property.type === 'RestElement') {
1608
+ restName = property.argument.name || null;
1609
+ } else if (
1610
+ property.type === 'ObjectProperty' &&
1611
+ (property.key.name || property.key.value) === 'children'
1612
+ ) {
1613
+ childrenName =
1614
+ property.value.type === 'Identifier'
1615
+ ? property.value.name
1616
+ : property.key.name || 'children';
1617
+ }
1618
+ }
1619
+ }
1620
+
1621
+ if (childrenName) {
1622
+ const childrenRef = new RegExp(
1623
+ `\\{\\s*${childrenName.replace(/[$]/g, '\\$') }\\s*\\}`,
1624
+ 'g',
1625
+ );
1626
+ compJsx = compJsx.replace(
1627
+ childrenRef,
1628
+ callSiteChildrenStr || '',
1629
+ );
1630
+ }
1631
+ if (restName) {
1632
+ const spreadRef = new RegExp(
1633
+ `\\{\\s*\\.\\.\\.${restName.replace(/[$]/g, '\\$')}\\s*\\}`,
1634
+ 'g',
1635
+ );
1636
+ const forwardedAttrs = callSiteAttrsStr.replace(
1637
+ /\s+ref\s*=\s*(?:\{[^{}]*\}|["'][^"']*["'])/g,
1638
+ '',
1639
+ );
1640
+ compJsx = compJsx.replace(spreadRef, forwardedAttrs);
1641
+ }
1642
+ if (componentPath && firstParam?.type === 'ObjectPattern') {
1643
+ const callSiteProps = new Map(
1644
+ parseJsxAttributes(callSiteAttrsStr).map((attribute) => [
1645
+ attribute.name,
1646
+ attribute.isStringLiteral
1647
+ ? JSON.stringify(attribute.expr)
1648
+ : attribute.expr,
1649
+ ]),
1650
+ );
1651
+ const hasAttributeSpread = /\{\s*\.\.\.\s*attributes\b/.test(
1652
+ callSiteAttrsStr,
1653
+ );
1654
+ const propExpressions = new Map();
1655
+ for (const property of firstParam.properties) {
1656
+ if (
1657
+ property.type !== 'ObjectProperty' ||
1658
+ property.key.name === 'children' ||
1659
+ property.key.value === 'children'
1660
+ ) {
1661
+ continue;
1662
+ }
1663
+ const key = property.key.name || property.key.value;
1664
+ const value =
1665
+ property.value.type === 'AssignmentPattern'
1666
+ ? property.value.left
1667
+ : property.value;
1668
+ if (value.type !== 'Identifier') continue;
1669
+ if (key === 'setAttributes' && value.name === 'setAttributes') {
1670
+ continue;
1671
+ }
1672
+
1673
+ if (callSiteProps.has(key)) {
1674
+ propExpressions.set(value.name, callSiteProps.get(key));
1675
+ } else if (hasAttributeSpread && key !== 'setAttributes') {
1676
+ const attributeValue = /^[A-Za-z_$][\w$]*$/.test(key)
1677
+ ? `attributes.${key}`
1678
+ : `attributes[${JSON.stringify(key)}]`;
1679
+ const fallback =
1680
+ property.value.type === 'AssignmentPattern'
1681
+ ? componentSource.slice(
1682
+ property.value.right.start,
1683
+ property.value.right.end,
1684
+ )
1685
+ : null;
1686
+ propExpressions.set(
1687
+ value.name,
1688
+ fallback
1689
+ ? `${attributeValue} === undefined ? (${fallback}) : ${attributeValue}`
1690
+ : attributeValue,
1691
+ );
1692
+ }
1693
+ }
1694
+
1695
+ const jsxStart = componentSource.indexOf(compJsx, componentPath.node.start);
1696
+ if (jsxStart !== -1 && propExpressions.size > 0) {
1697
+ const jsxEnd = jsxStart + compJsx.length;
1698
+ const replacements = [];
1699
+ traverse(componentAst, {
1700
+ Identifier(identifierPath) {
1701
+ const replacement = propExpressions.get(
1702
+ identifierPath.node.name,
1703
+ );
1704
+ if (
1705
+ !replacement ||
1706
+ !identifierPath.isReferencedIdentifier() ||
1707
+ identifierPath.node.start < jsxStart ||
1708
+ identifierPath.node.end > jsxEnd ||
1709
+ identifierPath.scope.getBinding(identifierPath.node.name) !==
1710
+ componentPath.scope.getBinding(identifierPath.node.name)
1711
+ ) {
1712
+ return;
1713
+ }
1714
+ replacements.push({
1715
+ start: identifierPath.node.start - jsxStart,
1716
+ end: identifierPath.node.end - jsxStart,
1717
+ text: `(${replacement})`,
1718
+ });
1719
+ },
1720
+ });
1721
+ replacements.sort((a, b) => b.start - a.start);
1722
+ for (const replacement of replacements) {
1723
+ compJsx =
1724
+ compJsx.slice(0, replacement.start) +
1725
+ replacement.text +
1726
+ compJsx.slice(replacement.end);
1727
+ }
1728
+ }
1729
+ }
1730
+ const refParam =
1731
+ componentParams?.[1]?.type === 'Identifier'
1732
+ ? componentParams[1].name
1733
+ : null;
1734
+ if (refParam) {
1735
+ compJsx = compJsx.replace(
1736
+ new RegExp(
1737
+ `\\s+ref\\s*=\\s*\\{\\s*${refParam.replace(/[$]/g, '\\$')}\\s*\\}`,
1738
+ 'g',
1739
+ ),
1740
+ '',
1741
+ );
1742
+ }
1743
+ }
1744
+ // Return the resolved file's own content/path alongside its JSX so callers can
1745
+ // recurse into it using ITS imports — a component nested two or more levels deep
1746
+ // (e.g. wrapper -> BlockComponent -> Grid) has an import that only exists in
1747
+ // BlockComponent's source, not the wrapper's, so re-using the original sourceCode/
1748
+ // sourceFilePath at every depth would never find it.
1749
+ return { jsx: compJsx, sourceCode: compContent, sourceFilePath: finalPath };
1750
+ } catch {
1751
+ return null;
1752
+ }
1753
+ }
1754
+
1755
+ /**
1756
+ * AST pass for expandNestedComponentTags: parse the JSX text, walk for
1757
+ * PascalCase component call sites, resolve + recursively expand each, and
1758
+ * splice replacements by exact node byte offsets — no close-tag `indexOf`
1759
+ * scan that a nested same-name component (`<Card><Card/></Card>`) or a `>`
1760
+ * inside an attribute expression could derail.
1761
+ *
1762
+ * Returns the (possibly unchanged) text, or null when jsxText isn't
1763
+ * parseable — after a PHP-mode island splice the output contains a literal
1764
+ * `<?php … ?>` hydration attribute, at which point the caller falls back to
1765
+ * the legacy text scan for any remaining tags.
1766
+ */
1767
+ function expandNestedTagsAstPass(
1768
+ jsxText,
1769
+ sourceCode,
1770
+ sourceFilePath,
1771
+ themeRoot,
1772
+ _depth,
1773
+ mode,
1774
+ ) {
1775
+ const ast = tryParseSource(jsxText);
1776
+ if (!ast) return null;
1777
+
1778
+ const splices = [];
1779
+ const walk = (node) => {
1780
+ if (!node || typeof node !== 'object' || typeof node.type !== 'string')
1781
+ return;
1782
+ if (node.type === 'JSXElement') {
1783
+ const name =
1784
+ node.openingElement.name.type === 'JSXIdentifier'
1785
+ ? node.openingElement.name.name
1786
+ : '';
1787
+ if (name && /^[A-Z]/.test(name) && !SKIP_NESTED_COMPONENTS.has(name)) {
1788
+ const selfClosing = node.openingElement.selfClosing;
1789
+ const attrsEnd = node.openingElement.end - (selfClosing ? 2 : 1);
1790
+ const callSiteAttrsStr = jsxText.slice(
1791
+ node.openingElement.name.end,
1792
+ attrsEnd,
1793
+ );
1794
+ const callSiteChildrenStr =
1795
+ !selfClosing && node.closingElement
1796
+ ? jsxText.slice(node.openingElement.end, node.closingElement.start)
1797
+ : '';
1798
+ const resolved = resolveImportedComponentJsx(
1799
+ name,
1800
+ sourceCode,
1801
+ sourceFilePath,
1802
+ themeRoot,
1803
+ mode,
1804
+ callSiteAttrsStr,
1805
+ callSiteChildrenStr,
1806
+ );
1807
+ if (resolved) {
1808
+ const compJsx = expandNestedComponentTags(
1809
+ resolved.jsx,
1810
+ resolved.sourceCode,
1811
+ resolved.sourceFilePath,
1812
+ themeRoot,
1813
+ _depth + 1,
1814
+ mode,
1815
+ );
1816
+ splices.push({ start: node.start, end: node.end, text: compJsx });
1817
+ return; // replaced wholesale — don't descend into the old children
1818
+ }
1819
+ }
1820
+ }
1821
+ for (const key of Object.keys(node)) {
1822
+ if (AST_PHP_METADATA_KEYS.has(key)) continue;
1823
+ const val = node[key];
1824
+ if (Array.isArray(val)) {
1825
+ for (const item of val) {
1826
+ if (item && typeof item.type === 'string') walk(item);
1827
+ }
1828
+ } else if (val && typeof val.type === 'string') {
1829
+ walk(val);
1830
+ }
1831
+ }
1832
+ };
1833
+ walk(ast.program);
1834
+
1835
+ if (splices.length === 0) return jsxText;
1836
+ splices.sort((a, b) => b.start - a.start); // splice right-to-left, offsets stay valid
1837
+ let out = jsxText;
1838
+ for (const s of splices) {
1839
+ out = out.slice(0, s.start) + s.text + out.slice(s.end);
1840
+ }
1841
+ return out;
1842
+ }
1843
+
1844
+ export function expandNestedComponentTags(
1845
+ jsx,
1846
+ sourceCode,
1847
+ sourceFilePath,
1848
+ themeRoot,
1849
+ _depth = 0,
1850
+ mode = 'editor',
1851
+ ) {
1852
+ if (_depth > 10) return jsx; // guard against pathological/circular import chains
1853
+ let output = jsx;
1854
+ for (let pass = 0; pass < 20; pass++) {
1855
+ const expanded = expandNestedTagsAstPass(
1856
+ output,
1857
+ sourceCode,
1858
+ sourceFilePath,
1859
+ themeRoot,
1860
+ _depth,
1861
+ mode,
1862
+ );
1863
+ if (expanded === null) {
1864
+ // Unparseable (PHP island boundary spliced in on an earlier pass, or
1865
+ // a non-JSX fragment) — legacy text scan handles whatever remains.
1866
+ // Legacy text-scan fallback deleted (Phase 4 — zero entries on the
1867
+ // entire known theme surface). Remaining tags stay as-is; marker kept.
1868
+ markLegacyFallback(
1869
+ 'php-transpiler:expandNestedComponentTags-would-have-tried-legacy',
1870
+ );
1871
+ return output;
1872
+ }
1873
+ if (expanded === output) return output; // fixpoint — nothing left to expand
1874
+ output = expanded;
1875
+ }
1876
+ return output;
1877
+ }
1878
+
1879
+ /**
1880
+ * Inlines calls to a locally-defined "icon wrapper" component — e.g.
1881
+ * `function ValueIcon({ name, className }) { const slug = (name || 'award')
1882
+ * .toLowerCase(); ... return <WpIcon name={slug} className={className}
1883
+ * provider='lucide' />; }` — used so a curated icon set renders as real
1884
+ * tree-shaken Lucide components in the browser while degrading identically
1885
+ * server-side: forgewp_render_theme_icon's PHP registry covers the same
1886
+ * curated slugs, and its sanitize_title() call already lowercases, so only
1887
+ * the bare `|| 'default'` fallback needs preserving.
1888
+ *
1889
+ * expandNestedComponentTags only resolves IMPORTED components (matched via
1890
+ * `import … from`) — a same-file helper like this is invisible to it, so
1891
+ * without this pass, `<ValueIcon name={row.icon} .../>` silently renders
1892
+ * nothing on the visitor page.
1893
+ */
1894
+ export function inlineIconWrapperTags(jsx, sourceCode) {
1895
+ if (!jsx || !sourceCode || !/<WpIcon\b/.test(sourceCode)) return jsx;
1896
+
1897
+ let output = jsx;
1898
+ const fnRegex =
1899
+ /function\s+([A-Z][A-Za-z0-9_]*)\s*\(\s*\{([^{}]*)\}[^)]*\)\s*\{/g;
1900
+ let m;
1901
+ while ((m = fnRegex.exec(sourceCode)) !== null) {
1902
+ const compName = m[1];
1903
+ if (!new RegExp(`<${compName}\\b`).test(output)) continue;
1904
+
1905
+ const bodyOpenIdx = fnRegex.lastIndex - 1;
1906
+ const bodyCloseIdx = findMatchingCurlyClose(sourceCode, bodyOpenIdx);
1907
+ if (bodyCloseIdx === -1) continue;
1908
+ const body = sourceCode.slice(bodyOpenIdx + 1, bodyCloseIdx);
1909
+
1910
+ const wpIconMatch = body.match(/<WpIcon\s+([^>]*?)\/?>/);
1911
+ if (!wpIconMatch) continue;
1912
+ const wpAttrs = wpIconMatch[1];
1913
+ const nameAttr = wpAttrs.match(/\bname\s*=\s*\{\s*([A-Za-z0-9_$]+)\s*\}/);
1914
+ const classAttr = wpAttrs.match(
1915
+ /\bclassName\s*=\s*\{\s*([A-Za-z0-9_$]+)\s*\}/,
1916
+ );
1917
+ const providerAttr = wpAttrs.match(
1918
+ /\bprovider\s*=\s*(?:"([^"]*)"|'([^']*)')/,
1919
+ );
1920
+ if (!nameAttr) continue;
1921
+ const provider =
1922
+ (providerAttr && (providerAttr[1] || providerAttr[2])) || 'lucide';
1923
+
1924
+ const paramNames = m[2]
1925
+ .split(',')
1926
+ .map((p) => p.trim().split(':')[0].trim())
1927
+ .filter(Boolean);
1928
+
1929
+ // What the wrapper actually feeds WpIcon's `name` — either a param
1930
+ // directly, or (the one real-world shape seen so far) a local const of
1931
+ // the form `const X = (PARAM || 'default').toLowerCase();`. Only that
1932
+ // specific shape is resolved; anything else bails (tag left untouched,
1933
+ // same as today) rather than risk mistranslating unknown logic.
1934
+ let namePropParam = null;
1935
+ let nameDefault = null;
1936
+ if (paramNames.includes(nameAttr[1])) {
1937
+ namePropParam = nameAttr[1];
1938
+ } else {
1939
+ const declRx = new RegExp(
1940
+ `const\\s+${nameAttr[1]}\\s*=\\s*\\(\\s*([A-Za-z0-9_$]+)\\s*\\|\\|\\s*('(?:[^'\\\\]|\\\\.)*'|"(?:[^"\\\\]|\\\\.)*")\\s*\\)\\.toLowerCase\\(\\)`,
1941
+ );
1942
+ const declMatch = body.match(declRx);
1943
+ if (declMatch && paramNames.includes(declMatch[1])) {
1944
+ namePropParam = declMatch[1];
1945
+ nameDefault = declMatch[2];
1946
+ }
1947
+ }
1948
+ if (!namePropParam) continue;
1949
+
1950
+ const classPropParam =
1951
+ classAttr && paramNames.includes(classAttr[1]) ? classAttr[1] : null;
1952
+
1953
+ const tagRx = new RegExp(`<${compName}\\b([^>]*?)/>`, 'g');
1954
+ output = output.replace(tagRx, (fullTag, attrsStr) => {
1955
+ const getAttrValue = (attrName) => {
1956
+ const litM = attrsStr.match(
1957
+ new RegExp(`\\b${attrName}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`),
1958
+ );
1959
+ if (litM) return `'${(litM[1] ?? litM[2] ?? '').replace(/'/g, "\\'")}'`;
1960
+ const exprM = attrsStr.match(
1961
+ new RegExp(`\\b${attrName}\\s*=\\s*\\{\\s*([\\s\\S]*?)\\s*\\}`),
1962
+ );
1963
+ if (exprM) return exprM[1].trim();
1964
+ return null;
1965
+ };
1966
+
1967
+ const nameCallSiteValue = getAttrValue(namePropParam);
1968
+ if (nameCallSiteValue === null) return fullTag;
1969
+ const nameExpr = nameDefault
1970
+ ? `${nameCallSiteValue} || ${nameDefault}`
1971
+ : nameCallSiteValue;
1972
+
1973
+ let classAttrOut = '';
1974
+ if (classPropParam) {
1975
+ const classVal = getAttrValue(classPropParam);
1976
+ if (classVal !== null) classAttrOut = ` className={${classVal}}`;
1977
+ }
1978
+
1979
+ return `<WpIcon name={${nameExpr}} provider="${provider}"${classAttrOut} />`;
1980
+ });
1981
+ }
1982
+ return output;
1983
+ }
1984
+
1985
+ export function convertJsObjectToPhp(jsObjStr) {
1986
+ let clean = jsObjStr.trim();
1987
+ if (clean.startsWith('{') && clean.endsWith('}')) {
1988
+ clean = clean.substring(1, clean.length - 1).trim();
1989
+ }
1990
+ const props = [];
1991
+ const propRegex =
1992
+ /([a-zA-Z0-9_-]+)\s*:\s*('[^']*'|"[^"]*"|__\('[^']*'\)|__\("[^"]*"\)|[a-zA-Z0-9_-]+)/g;
1993
+ let match;
1994
+ while ((match = propRegex.exec(clean)) !== null) {
1995
+ const key = match[1];
1996
+ const val = match[2];
1997
+ props.push(`'${key}' => ${val}`);
1998
+ }
1999
+ return `array(${props.join(', ')})`;
2000
+ }
2001
+
2002
+ export function convertJsArrayToPhp(jsArrStr) {
2003
+ let clean = jsArrStr.trim();
2004
+ if (clean.startsWith('[') && clean.endsWith(']')) {
2005
+ clean = clean.substring(1, clean.length - 1).trim();
2006
+ }
2007
+ const objects = [];
2008
+ const objRegex = /\{[^\}]+\}/g;
2009
+ let match;
2010
+ while ((match = objRegex.exec(clean)) !== null) {
2011
+ objects.push(convertJsObjectToPhp(match[0]));
2012
+ }
2013
+ if (objects.length > 0) {
2014
+ return `array(${objects.join(', ')})`;
2015
+ }
2016
+ return `array(${clean})`;
2017
+ }
2018
+
2019
+ // A className expression's operands are always strings, so unlike the
2020
+ // generic case, JS `+` concatenation can be safely rewritten to PHP's `.`
2021
+ // without risking a numeric-addition misread elsewhere.
2022
+ export function translateClassNameExpr(
2023
+ jsExpr,
2024
+ blockAttrKeys = [],
2025
+ localVars = new Set(),
2026
+ freeFunctions = new Set(),
2027
+ ) {
2028
+ const phpExpr = translateJsExpressionToPhp(
2029
+ jsExpr,
2030
+ blockAttrKeys,
2031
+ localVars,
2032
+ freeFunctions,
2033
+ );
2034
+ return phpExpr.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|\+/g, (m) =>
2035
+ m === '+' ? '.' : m,
2036
+ );
2037
+ }
2038
+
2039
+ // Handles a loop-body `class(Name)?={...}` attribute whose expression is more
2040
+ // than a bare `{varName.field}`/`{varName}` (e.g. `row.color?.replace(/x/, '')
2041
+ // .trim() || 'fallback'`) — the simpler passes in substituteLoopVarInJsx only
2042
+ // match those two exact shapes and otherwise leave the whole expression as
2043
+ // raw, unrendered JS text. Runs last, so it only ever sees whatever the
2044
+ // simpler passes didn't already convert away.
2045
+ function substituteLoopVarInClassAttr(jsx, varName) {
2046
+ let output = jsx;
2047
+ const attrRx = /\b(?:class|className)\s*=\s*\{/g;
2048
+ let match;
2049
+ while ((match = attrRx.exec(output)) !== null) {
2050
+ const openBraceIdx = match.index + match[0].length - 1;
2051
+ const closeBraceIdx = findMatchingCurlyClose(output, openBraceIdx);
2052
+ if (closeBraceIdx === -1) continue;
2053
+ const exprText = output.slice(openBraceIdx + 1, closeBraceIdx).trim();
2054
+ const phpExpr = translateClassNameExpr(exprText, [], new Set([varName]));
2055
+ const replacement = `class="<?php echo esc_attr( ${phpExpr} ); ?>"`;
2056
+ output =
2057
+ output.slice(0, match.index) +
2058
+ replacement +
2059
+ output.slice(closeBraceIdx + 1);
2060
+ attrRx.lastIndex = match.index + replacement.length;
2061
+ }
2062
+ return output;
2063
+ }
2064
+
2065
+ // Replaces `{varName.field}` / bare `{varName}` occurrences inside a .map() loop body,
2066
+ // distinguishing attribute position (`attr={varName.field}` — needs quotes + esc_url/esc_attr)
2067
+ // from text-content position (`{varName.field}` between tags — esc_html, no quotes). Loop-body
2068
+ // substitution used to always apply the text-content form regardless of position, which left
2069
+ // attribute values like `src={row.avatar}` as unquoted, incorrectly-escaped PHP.
2070
+ function substituteLoopVarInJsx(innerJsx, varName) {
2071
+ const fieldRx = new RegExp(
2072
+ `([a-zA-Z0-9_-]+=)?\\{\\s*${varName}\\.([a-zA-Z0-9_-]+)\\s*\\}`,
2073
+ 'g',
2074
+ );
2075
+ let processedJsx = innerJsx.replace(fieldRx, (m, attrPrefix, field) => {
2076
+ if (attrPrefix) {
2077
+ const attrName = attrPrefix.slice(0, -1);
2078
+ const escFunc =
2079
+ attrName === 'href' || attrName === 'src' ? 'esc_url' : 'esc_attr';
2080
+ return `${attrName}="<?php echo ${escFunc}( $${varName}['${field}'] ?? '' ); ?>"`;
2081
+ }
2082
+ return `<?php echo esc_html( $${varName}['${field}'] ?? '' ); ?>`;
2083
+ });
2084
+ const primitiveRx = new RegExp(
2085
+ `([a-zA-Z0-9_-]+=)?\\{\\s*${varName}\\s*\\}`,
2086
+ 'g',
2087
+ );
2088
+ processedJsx = processedJsx.replace(primitiveRx, (m, attrPrefix) => {
2089
+ if (attrPrefix) {
2090
+ const attrName = attrPrefix.slice(0, -1);
2091
+ const escFunc =
2092
+ attrName === 'href' || attrName === 'src' ? 'esc_url' : 'esc_attr';
2093
+ return `${attrName}="<?php echo ${escFunc}( $${varName} ?? '' ); ?>"`;
2094
+ }
2095
+ return `<?php echo esc_html( $${varName} ); ?>`;
2096
+ });
2097
+ // Remaining uses inside expressions/helpers: avatarUrl(row.avatar) → avatarUrl($row['avatar'])
2098
+ // Skip already-PHP `$row`, string/array keys like ['row'], and quoted text.
2099
+ processedJsx = processedJsx.replace(
2100
+ new RegExp(`(?<![.$\\w'\\"])${varName}\\.([a-zA-Z0-9_-]+)\\b`, 'g'),
2101
+ `$${varName}['$1']`,
2102
+ );
2103
+ processedJsx = processedJsx.replace(
2104
+ new RegExp(`(?<![.$\\w'\\"])${varName}\\b(?!\\s*['\\"])`, 'g'),
2105
+ `$${varName}`,
2106
+ );
2107
+ processedJsx = substituteLoopVarInClassAttr(processedJsx, varName);
2108
+ return processedJsx;
2109
+ }
2110
+
2111
+ export function transpileLoops(phpMarkup) {
2112
+ // 1. Literal Array Maps: {[ ... ].map((item) => ( ... ))}
2113
+ const literalMapRegex =
2114
+ /\{\s*(\[[^\]]*\])\s*\.map\(\s*\(\s*([a-zA-Z0-9_-]+)\s*(?:,\s*[a-zA-Z0-9_-]+)?\s*\)\s*=>\s*\(\s*(<[\s\S]*?>)\s*\)\s*\)\s*\}/g;
2115
+ phpMarkup = phpMarkup.replace(
2116
+ literalMapRegex,
2117
+ (match, arrayExpr, varName, innerJsx) => {
2118
+ try {
2119
+ const phpArray = convertJsArrayToPhp(arrayExpr);
2120
+ let processedJsx = substituteLoopVarInJsx(innerJsx, varName);
2121
+ processedJsx = processedJsx.replace(/className=/g, 'class=');
2122
+ return `<?php foreach (${phpArray} as $${varName}): ?>\n${processedJsx}\n<?php endforeach; ?>`;
2123
+ } catch (e) {
2124
+ return match;
2125
+ }
2126
+ },
2127
+ );
2128
+
2129
+ // 2. Identifier Maps: {items.map((item) => ( ... ))}
2130
+ const idMapRegex =
2131
+ /\{\s*([a-zA-Z0-9_-]+)\s*\.map\(\s*\(\s*([a-zA-Z0-9_-]+)\s*(?:,\s*[a-zA-Z0-9_-]+)?\s*\)\s*=>\s*\(\s*(<[\s\S]*?>)\s*\)\s*\)\s*\}/g;
2132
+ phpMarkup = phpMarkup.replace(
2133
+ idMapRegex,
2134
+ (match, arrayVar, varName, innerJsx) => {
2135
+ try {
2136
+ let processedJsx = substituteLoopVarInJsx(innerJsx, varName);
2137
+ processedJsx = processedJsx.replace(/className=/g, 'class=');
2138
+ return `<?php foreach (($attributes['${arrayVar}'] ?? $${arrayVar} ?? array()) as $${varName}): ?>\n${processedJsx}\n<?php endforeach; ?>`;
2139
+ } catch (e) {
2140
+ return match;
2141
+ }
2142
+ },
2143
+ );
2144
+
2145
+ // 3. String Split and Map: {(tags || '').split(',').map(...).filter(...).map((tag) => ( ... ))}
2146
+ const splitMapRegex =
2147
+ /\{\s*\((?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\|\|\s*(['"])\2\)\s*\.split\(\s*(['"])([^'"]+)\3\s*\)(?:\.map\(\s*[a-zA-Z0-9_-]+\s*=>\s*[a-zA-Z0-9_-]+\.trim\(\)\s*\))?(?:\.filter\(\s*[a-zA-Z0-9_-]+\s*\))?\.map\(\s*\(\s*([a-zA-Z0-9_-]+)\s*\)\s*=>\s*\(\s*(<[\s\S]*?>)\s*\)\s*\)\s*\}/g;
2148
+ phpMarkup = phpMarkup.replace(
2149
+ splitMapRegex,
2150
+ (match, arrayVar, q1, q2, separator, varName, innerJsx) => {
2151
+ try {
2152
+ let processedJsx = substituteLoopVarInJsx(innerJsx, varName);
2153
+ processedJsx = processedJsx.replace(/className=/g, 'class=');
2154
+ const phpExpr = `$attributes['${arrayVar}'] ?? ''`;
2155
+ return `<?php foreach (array_filter(array_map('trim', explode('${separator}', ${phpExpr}))) as $${varName}): ?>\n${processedJsx}\n<?php endforeach; ?>`;
2156
+ } catch (e) {
2157
+ return match;
2158
+ }
2159
+ },
2160
+ );
2161
+
2162
+ return phpMarkup;
2163
+ }
2164
+
2165
+ export function transpileConditionals(phpMarkup, attrKeys = []) {
2166
+ let index = phpMarkup.length;
2167
+ while (true) {
2168
+ const matchIndex = phpMarkup.lastIndexOf('&&', index);
2169
+ if (matchIndex === -1) break;
2170
+
2171
+ // Ignore if inside an active <?php ... ?> block
2172
+ const lastPhpStart = phpMarkup.lastIndexOf('<?php', matchIndex);
2173
+ const lastPhpEnd = phpMarkup.lastIndexOf('?>', matchIndex);
2174
+ if (lastPhpStart !== -1 && lastPhpStart > lastPhpEnd) {
2175
+ index = matchIndex - 1;
2176
+ continue;
2177
+ }
2178
+
2179
+ const openBrace = phpMarkup.lastIndexOf('{', matchIndex);
2180
+ if (openBrace !== -1 && openBrace > matchIndex - 100) {
2181
+ const condVar = phpMarkup.substring(openBrace + 1, matchIndex).trim();
2182
+ if (/^[a-zA-Z0-9_.\-\s&|!=<>'"]+$/.test(condVar)) {
2183
+ const openParen = phpMarkup.indexOf('(', matchIndex);
2184
+ if (openParen !== -1 && openParen < matchIndex + 10) {
2185
+ const innerJsx = extractJsxByTagBalancing(
2186
+ phpMarkup.substring(openParen + 1),
2187
+ );
2188
+ if (innerJsx) {
2189
+ const trueJsxIndex = phpMarkup.indexOf(innerJsx, openParen);
2190
+ const closeParenIndexActual = trueJsxIndex + innerJsx.length;
2191
+ const endBrace = phpMarkup.indexOf('}', closeParenIndexActual);
2192
+ if (endBrace !== -1) {
2193
+ const gap = phpMarkup
2194
+ .substring(closeParenIndexActual, endBrace)
2195
+ .trim();
2196
+ if (gap === ')' || gap === '') {
2197
+ const phpCond = translateJsExpressionToPhp(condVar, attrKeys);
2198
+ const replacement = `<?php if (${phpCond}): ?>\n${innerJsx}\n<?php endif; ?>`;
2199
+ phpMarkup =
2200
+ phpMarkup.substring(0, openBrace) +
2201
+ replacement +
2202
+ phpMarkup.substring(endBrace + 1);
2203
+ index = openBrace - 1;
2204
+ continue;
2205
+ }
2206
+ }
2207
+ }
2208
+ }
2209
+ }
2210
+ }
2211
+ index = matchIndex - 1;
2212
+ }
2213
+ return phpMarkup;
2214
+ }
2215
+
2216
+ export function findMatchingParenClose(str, openIdx) {
2217
+ let depth = 0;
2218
+ let inStr = null;
2219
+ let esc = false;
2220
+ for (let i = openIdx; i < str.length; i++) {
2221
+ const c = str[i];
2222
+ if (inStr) {
2223
+ if (esc) {
2224
+ esc = false;
2225
+ } else if (c === '\\') {
2226
+ esc = true;
2227
+ } else if (c === inStr) {
2228
+ inStr = null;
2229
+ }
2230
+ continue;
2231
+ }
2232
+ if (c === "'" || c === '"' || c === '`') {
2233
+ inStr = c;
2234
+ continue;
2235
+ }
2236
+ if (c === '(') depth++;
2237
+ else if (c === ')') {
2238
+ depth--;
2239
+ if (depth === 0) return i;
2240
+ }
2241
+ }
2242
+ return -1;
2243
+ }
2244
+
2245
+ /**
2246
+ * Extract one ternary branch starting right after its opening paren. If the
2247
+ * branch is JSX (starts with a tag), tag-balance it as before. Otherwise it's a
2248
+ * plain expression (bare identifier, string literal, etc.) — dual-host
2249
+ * components commonly write `{cond ? (<Editable/>) : (plainValue)}`, where the
2250
+ * non-editable branch is just the raw underlying value, not JSX. Previously
2251
+ * extractJsxByTagBalancing's unbounded `<letter` search would run off into
2252
+ * unrelated markup much further down the file and fail, silently leaving the
2253
+ * entire ternary — including the literal `{cond ? (` text — untranspiled and
2254
+ * visible on the live page.
2255
+ */
2256
+ function extractTernaryBranch(phpMarkup, openParenIdx, attrKeys) {
2257
+ const after = phpMarkup.substring(openParenIdx + 1);
2258
+ if (/^\s*</.test(after)) {
2259
+ const jsx = extractJsxByTagBalancing(after);
2260
+ if (!jsx) return null;
2261
+ const jsxIndex = phpMarkup.indexOf(jsx, openParenIdx);
2262
+ return { content: jsx, endIndex: jsxIndex + jsx.length };
2263
+ }
2264
+ const closeIdx = findMatchingParenClose(phpMarkup, openParenIdx);
2265
+ if (closeIdx === -1) return null;
2266
+ const rawExpr = phpMarkup.substring(openParenIdx + 1, closeIdx).trim();
2267
+ if (!rawExpr) return null;
2268
+
2269
+ // Only attempt real translation for genuinely simple expressions — bare
2270
+ // identifiers, property chains, logical-OR fallbacks, or a single plain
2271
+ // function call. translateJsExpressionToPhp is a regex-based translator, not
2272
+ // a real parser — IIFEs, arrow functions, and multi-statement bodies (e.g. a
2273
+ // `.find()` lookup wrapped in `(() => { const x = ...; return ...; })()`)
2274
+ // are far beyond what it can safely rewrite, and previously came out as
2275
+ // mangled, syntactically-broken PHP. Degrade to a blank string instead.
2276
+ const looksComplex = /=>|\bfunction\b|;|\bconst\b|\blet\b|\bvar\b/.test(
2277
+ rawExpr,
2278
+ );
2279
+ const content = looksComplex
2280
+ ? `<?php echo ''; ?>`
2281
+ : `<?php echo esc_html( ${translateJsExpressionToPhp(rawExpr, attrKeys)} ); ?>`;
2282
+ return { content, endIndex: closeIdx + 1 };
2283
+ }
2284
+
2285
+ export function parseTernaryBounds(str) {
2286
+ let parenDepth = 0;
2287
+ let braceDepth = 0;
2288
+ let bracketDepth = 0;
2289
+ let inQuote = null;
2290
+ let esc = false;
2291
+
2292
+ let qIdx = -1;
2293
+ let colonIdx = -1;
2294
+ let ternaryCount = 0;
2295
+
2296
+ for (let i = 0; i < str.length; i++) {
2297
+ const c = str[i];
2298
+
2299
+ if (inQuote) {
2300
+ if (esc) {
2301
+ esc = false;
2302
+ } else if (c === '\\') {
2303
+ esc = true;
2304
+ } else if (c === inQuote) {
2305
+ inQuote = null;
2306
+ }
2307
+ continue;
2308
+ }
2309
+
2310
+ if (c === "'" || c === '"' || c === '`') {
2311
+ inQuote = c;
2312
+ continue;
2313
+ }
2314
+
2315
+ if (c === '(') {
2316
+ parenDepth++;
2317
+ continue;
2318
+ }
2319
+ if (c === ')') {
2320
+ parenDepth--;
2321
+ continue;
2322
+ }
2323
+ if (c === '{') {
2324
+ braceDepth++;
2325
+ continue;
2326
+ }
2327
+ if (c === '}') {
2328
+ braceDepth--;
2329
+ continue;
2330
+ }
2331
+ if (c === '[') {
2332
+ bracketDepth++;
2333
+ continue;
2334
+ }
2335
+ if (c === ']') {
2336
+ bracketDepth--;
2337
+ continue;
2338
+ }
2339
+
2340
+ if (parenDepth === 0 && braceDepth === 0 && bracketDepth === 0) {
2341
+ if (c === '?') {
2342
+ if (str[i + 1] === '?') {
2343
+ i++;
2344
+ continue;
2345
+ }
2346
+ if (str[i - 1] === '<' || str[i + 1] === '>') {
2347
+ continue;
2348
+ }
2349
+ if (qIdx === -1) {
2350
+ qIdx = i;
2351
+ }
2352
+ ternaryCount++;
2353
+ } else if (c === ':') {
2354
+ if (qIdx !== -1) {
2355
+ ternaryCount--;
2356
+ if (ternaryCount === 0) {
2357
+ colonIdx = i;
2358
+ break;
2359
+ }
2360
+ }
2361
+ }
2362
+ }
2363
+ }
2364
+
2365
+ if (qIdx !== -1 && colonIdx !== -1) {
2366
+ return { qIdx, colonIdx };
2367
+ }
2368
+ return null;
2369
+ }
2370
+
2371
+ export function stripParenWrap(s) {
2372
+ const trimmed = s.trim();
2373
+ if (trimmed[0] !== '(' || trimmed[trimmed.length - 1] !== ')') return trimmed;
2374
+ const close = findMatchingParenClose(trimmed, 0);
2375
+ if (close !== trimmed.length - 1) return trimmed;
2376
+ return stripParenWrap(trimmed.slice(1, -1));
2377
+ }
2378
+
2379
+ export function transpileTernaryString(expr, attrKeys = []) {
2380
+ const bounds = parseTernaryBounds(expr);
2381
+ if (!bounds) {
2382
+ const trimmed = expr.trim();
2383
+ if (/^\s*</.test(trimmed) || /^\s*<>\s*/.test(trimmed)) {
2384
+ return transpileTernaries(trimmed, attrKeys);
2385
+ }
2386
+ const parenStripped = stripParenWrap(trimmed);
2387
+ if (parenStripped !== trimmed) {
2388
+ return transpileTernaryString(parenStripped, attrKeys);
2389
+ }
2390
+ const looksComplex = /=>|\bfunction\b|;|\bconst\b|\blet\b|\bvar\b/.test(
2391
+ trimmed,
2392
+ );
2393
+ if (looksComplex) return `<?php echo ''; ?>`;
2394
+ return `<?php echo esc_html( ${translateJsExpressionToPhp(trimmed, attrKeys)} ); ?>`;
2395
+ }
2396
+
2397
+ const { qIdx, colonIdx } = bounds;
2398
+ const condVar = expr.substring(0, qIdx).trim();
2399
+ const trueBranchRaw = expr.substring(qIdx + 1, colonIdx).trim();
2400
+ const falseBranchRaw = expr.substring(colonIdx + 1).trim();
2401
+
2402
+ let trueBranch = stripParenWrap(trueBranchRaw);
2403
+ let falseBranch = stripParenWrap(falseBranchRaw);
2404
+
2405
+ const isJsx = (s) => /^\s*</.test(s.trim()) || /^\s*<>\s*/.test(s.trim());
2406
+
2407
+ let trueContent = '';
2408
+ if (isJsx(trueBranch)) {
2409
+ trueContent = transpileTernaries(trueBranch, attrKeys);
2410
+ } else {
2411
+ trueContent = transpileTernaryString(trueBranch, attrKeys);
2412
+ }
2413
+
2414
+ let falseContent = '';
2415
+ if (isJsx(falseBranch)) {
2416
+ falseContent = transpileTernaries(falseBranch, attrKeys);
2417
+ } else {
2418
+ falseContent = transpileTernaryString(falseBranch, attrKeys);
2419
+ }
2420
+
2421
+ const phpCond = translateJsExpressionToPhp(condVar, attrKeys);
2422
+ return `<?php if (${phpCond}): ?>\n${trueContent}\n<?php else: ?>\n${falseContent}\n<?php endif; ?>`;
2423
+ }
2424
+
2425
+ export function transpileTernaries(phpMarkup, attrKeys = []) {
2426
+ let index = phpMarkup.length;
2427
+ while (true) {
2428
+ const openBrace = phpMarkup.lastIndexOf('{', index);
2429
+ if (openBrace === -1) break;
2430
+
2431
+ // Ignore if inside an active <?php ... ?> block
2432
+ const lastPhpStart = phpMarkup.lastIndexOf('<?php', openBrace);
2433
+ const lastPhpEnd = phpMarkup.lastIndexOf('?>', openBrace);
2434
+ if (lastPhpStart !== -1 && lastPhpStart > lastPhpEnd) {
2435
+ index = openBrace - 1;
2436
+ continue;
2437
+ }
2438
+
2439
+ let depth = 1;
2440
+ let closeBrace = -1;
2441
+ let inQuote = null;
2442
+ let esc = false;
2443
+ for (let j = openBrace + 1; j < phpMarkup.length; j++) {
2444
+ const c = phpMarkup[j];
2445
+ if (inQuote) {
2446
+ if (esc) {
2447
+ esc = false;
2448
+ } else if (c === '\\') {
2449
+ esc = true;
2450
+ } else if (c === inQuote) {
2451
+ inQuote = null;
2452
+ }
2453
+ continue;
2454
+ }
2455
+ if (c === "'" || c === '"' || c === '`') {
2456
+ inQuote = c;
2457
+ continue;
2458
+ }
2459
+ if (c === '{') depth++;
2460
+ else if (c === '}') {
2461
+ depth--;
2462
+ if (depth === 0) {
2463
+ closeBrace = j;
2464
+ break;
2465
+ }
2466
+ }
2467
+ }
2468
+
2469
+ if (closeBrace !== -1) {
2470
+ const braceContent = phpMarkup
2471
+ .substring(openBrace + 1, closeBrace)
2472
+ .trim();
2473
+ const bounds = parseTernaryBounds(braceContent);
2474
+ if (bounds) {
2475
+ const transpiled = transpileTernaryString(braceContent, attrKeys);
2476
+ phpMarkup =
2477
+ phpMarkup.substring(0, openBrace) +
2478
+ transpiled +
2479
+ phpMarkup.substring(closeBrace + 1);
2480
+ index = openBrace - 1;
2481
+ continue;
2482
+ }
2483
+ }
2484
+ index = openBrace - 1;
2485
+ }
2486
+ return phpMarkup;
2487
+ }
2488
+
2489
+ /**
2490
+ * Inline local JSX-returning render-helper calls (`{cell(a, b)}`) directly
2491
+ * into the markup, substituting each parameter with its call-site argument
2492
+ * text. jsHelperToPhpFunction can't turn these into real PHP functions (JSX
2493
+ * has no PHP-function-body equivalent), so without this the call site would
2494
+ * otherwise pass straight through every other transform untouched and leak
2495
+ * literal JS text into render.php. Running this first lets the substituted
2496
+ * JSX flow through the normal transpileConditionals/transpileTernaries/etc.
2497
+ * pipeline exactly like markup the dev wrote directly inline.
2498
+ */
2499
+ export function inlineJsxRenderHelperCalls(text, templates) {
2500
+ if (!templates || templates.size === 0) return text;
2501
+ let result = text;
2502
+ let guard = 0;
2503
+ let changed = true;
2504
+ while (changed && guard < 50) {
2505
+ changed = false;
2506
+ guard++;
2507
+ for (const [name, tmpl] of templates) {
2508
+ const callRegex = new RegExp(`\\{\\s*${name}\\s*\\(`, 'g');
2509
+ const match = callRegex.exec(result);
2510
+ if (!match) continue;
2511
+
2512
+ const parenStart = match.index + match[0].length - 1;
2513
+ const parenEnd = findMatchingParenClose(result, parenStart);
2514
+ if (parenEnd === -1) continue;
2515
+
2516
+ let closeBraceIdx = parenEnd + 1;
2517
+ while (closeBraceIdx < result.length && /\s/.test(result[closeBraceIdx]))
2518
+ closeBraceIdx++;
2519
+ if (result[closeBraceIdx] !== '}') continue;
2520
+
2521
+ const argsText = result.slice(parenStart + 1, parenEnd);
2522
+ const args = splitTopLevelArgs(argsText);
2523
+
2524
+ let jsxBody = tmpl.jsxBody;
2525
+ tmpl.params.forEach((p, idx) => {
2526
+ const argExpr = args[idx] !== undefined ? args[idx].trim() : 'null';
2527
+ const isStringLiteral =
2528
+ /^'(?:[^'\\]|\\.)*'$/.test(argExpr) ||
2529
+ /^"(?:[^"\\]|\\.)*"$/.test(argExpr);
2530
+
2531
+ // A JSX attribute assigned via braces (`className={className}`) needs
2532
+ // the whole `={param}` replaced, not just the identifier inside —
2533
+ // substituting only the identifier would leave `={'literal string'}`,
2534
+ // which the downstream attr-to-PHP pass doesn't recognize (it only
2535
+ // handles `attr="..."` / `attr='...'` or `attr={identifier}`),
2536
+ // producing literal, broken `class={'...'}` text in the rendered page.
2537
+ jsxBody = jsxBody.replace(
2538
+ new RegExp(`=\\{\\s*${p}\\s*\\}`, 'g'),
2539
+ isStringLiteral ? `=${argExpr}` : `={${argExpr}}`,
2540
+ );
2541
+
2542
+ // Remaining occurrences (children `{value}`, computed keys `[key]`,
2543
+ // etc). A bare `IDENT=` (single `=`, not `==`/`===`) is a JSX
2544
+ // attribute name (`value={value}` — the LHS `value=` is markup, not
2545
+ // the parameter), so it must be excluded or the attribute name
2546
+ // itself gets corrupted.
2547
+ jsxBody = jsxBody.replace(
2548
+ new RegExp(`(?<![\\w$])${p}(?![\\w$])(?!\\s*=(?!=))`, 'g'),
2549
+ argExpr,
2550
+ );
2551
+ });
2552
+
2553
+ let isBareJsx = /^<[A-Za-z/]|^<>/.test(jsxBody.trim());
2554
+
2555
+ // Chained dispatch ternaries (`tagName === 'p' ? (<p/>) : tagName === 'h2'
2556
+ // ? (<h2/>) : (<span/>)`) are a shape transpileTernaries doesn't support
2557
+ // (it only handles a single cond ? A : B, not further ternaries inside
2558
+ // the false branch). Since every param has already been substituted
2559
+ // with its real call-site argument text above, each condition in the
2560
+ // chain is now fully resolved data (`setAttributes` — always undefined
2561
+ // in render.php — or a literal-vs-literal comparison like `'h2' ===
2562
+ // 'div'`), so it can be evaluated at compile time instead of requiring
2563
+ // runtime PHP branching. Falls back to leaving the chain untouched
2564
+ // (for transpileTernaries to attempt) if anything isn't staticly
2565
+ // resolvable, e.g. a call site that passes a real variable.
2566
+ if (!isBareJsx) {
2567
+ const resolved = resolveStaticTernaryChain(jsxBody);
2568
+ if (resolved !== null) {
2569
+ jsxBody = resolved;
2570
+ isBareJsx = true;
2571
+ }
2572
+ }
2573
+
2574
+ // A bare JSX element/fragment (`<div>…</div>`) doesn't need the
2575
+ // surrounding `{}` — strip it, matching how a dev would write it
2576
+ // inline. A ternary/conditional expression (`cond ? (<A/>) : (<B/>)`)
2577
+ // is not valid JSX on its own — transpileTernaries/transpileConditionals
2578
+ // specifically look for the `{` immediately before the condition to
2579
+ // find its boundaries, so those braces must be kept.
2580
+ const replacement = isBareJsx ? jsxBody : `{${jsxBody}}`;
2581
+ result =
2582
+ result.slice(0, match.index) +
2583
+ replacement +
2584
+ result.slice(closeBraceIdx + 1);
2585
+ changed = true;
2586
+ }
2587
+ }
2588
+ return result;
2589
+ }
2590
+
2591
+ /**
2592
+ * Resolve a chain of `cond ? (branch) : cond2 ? (branch2) : … : (fallback)`
2593
+ * down to a single JSX branch by evaluating each condition at compile time.
2594
+ * `setAttributes` is treated as always-false (render.php never defines it —
2595
+ * see translateJsExpressionToPhp's `($x ?? null)` fallback for unknown
2596
+ * identifiers, which is the same effective behavior at runtime). Any other
2597
+ * condition must be a safely `Function`-evaluable literal expression (e.g.
2598
+ * `'h2' === 'div'`) with no identifiers left in it — anything else aborts
2599
+ * and returns null so the caller leaves the original text untouched.
2600
+ */
2601
+ function resolveStaticTernaryChain(expr, depth = 0) {
2602
+ if (depth > 20) return null;
2603
+ const trimmed = expr.trim();
2604
+
2605
+ const bareJsxMatch = /^<[A-Za-z/]|^<>/.test(trimmed);
2606
+ if (bareJsxMatch) return trimmed;
2607
+
2608
+ const parenWrapped = stripJsxParenWrap(trimmed);
2609
+ if (parenWrapped !== null) return parenWrapped;
2610
+
2611
+ const condMatch = trimmed.match(/^([^()?:]+?)\s*\?\s*\(/);
2612
+ if (!condMatch) return null;
2613
+
2614
+ const cond = condMatch[1].trim();
2615
+ const trueParenStart = trimmed.indexOf('(', condMatch[0].length - 1);
2616
+ const trueParenEnd = findMatchingParenClose(trimmed, trueParenStart);
2617
+ if (trueParenEnd === -1) return null;
2618
+
2619
+ let condValue;
2620
+ if (cond === 'setAttributes') {
2621
+ condValue = false;
2622
+ } else {
2623
+ try {
2624
+ const evaluated = new Function(`return (${cond});`)();
2625
+ if (typeof evaluated !== 'boolean') return null;
2626
+ condValue = evaluated;
2627
+ } catch {
2628
+ return null;
2629
+ }
2630
+ }
2631
+
2632
+ if (condValue) {
2633
+ return resolveStaticTernaryChain(
2634
+ trimmed.slice(trueParenStart + 1, trueParenEnd),
2635
+ depth + 1,
2636
+ );
2637
+ }
2638
+
2639
+ const colonIdx = trimmed.indexOf(':', trueParenEnd);
2640
+ if (colonIdx === -1) return null;
2641
+ return resolveStaticTernaryChain(trimmed.slice(colonIdx + 1), depth + 1);
2642
+ }
2643
+
2644
+ function stripJsxParenWrap(s) {
2645
+ if (s[0] !== '(' || s[s.length - 1] !== ')') return null;
2646
+ const close = findMatchingParenClose(s, 0);
2647
+ if (close !== s.length - 1) return null;
2648
+ const inner = s.slice(1, -1).trim();
2649
+ return /^<[A-Za-z/]|^<>/.test(inner) ? inner : null;
2650
+ }
2651
+
2652
+ function splitTopLevelArgs(argsText) {
2653
+ const args = [];
2654
+ let depth = 0;
2655
+ let current = '';
2656
+ let inStr = null;
2657
+ let esc = false;
2658
+ for (let i = 0; i < argsText.length; i++) {
2659
+ const c = argsText[i];
2660
+ if (inStr) {
2661
+ current += c;
2662
+ if (esc) {
2663
+ esc = false;
2664
+ } else if (c === '\\') {
2665
+ esc = true;
2666
+ } else if (c === inStr) {
2667
+ inStr = null;
2668
+ }
2669
+ continue;
2670
+ }
2671
+ if (c === "'" || c === '"' || c === '`') {
2672
+ inStr = c;
2673
+ current += c;
2674
+ continue;
2675
+ }
2676
+ if (c === '(' || c === '[' || c === '{') depth++;
2677
+ if (c === ')' || c === ']' || c === '}') depth--;
2678
+ if (c === ',' && depth === 0) {
2679
+ args.push(current);
2680
+ current = '';
2681
+ continue;
2682
+ }
2683
+ current += c;
2684
+ }
2685
+ if (current.trim()) args.push(current);
2686
+ return args;
2687
+ }
2688
+
2689
+ function findMatchingBracketClose(str, openIdx) {
2690
+ let depth = 0;
2691
+ let inStr = null;
2692
+ let esc = false;
2693
+ for (let i = openIdx; i < str.length; i++) {
2694
+ const c = str[i];
2695
+ if (inStr) {
2696
+ if (esc) esc = false;
2697
+ else if (c === '\\') esc = true;
2698
+ else if (c === inStr) inStr = null;
2699
+ continue;
2700
+ }
2701
+ if (c === "'" || c === '"' || c === '`') {
2702
+ inStr = c;
2703
+ continue;
2704
+ }
2705
+ if (c === '[') depth++;
2706
+ else if (c === ']') {
2707
+ depth--;
2708
+ if (depth === 0) return i;
2709
+ }
2710
+ }
2711
+ return -1;
2712
+ }
2713
+
2714
+ function findMatchingCurlyClose(str, openIdx) {
2715
+ let depth = 0;
2716
+ let inStr = null;
2717
+ let esc = false;
2718
+ for (let i = openIdx; i < str.length; i++) {
2719
+ const c = str[i];
2720
+ if (inStr) {
2721
+ if (esc) esc = false;
2722
+ else if (c === '\\') esc = true;
2723
+ else if (c === inStr) inStr = null;
2724
+ continue;
2725
+ }
2726
+ if (c === "'" || c === '"' || c === '`') {
2727
+ inStr = c;
2728
+ continue;
2729
+ }
2730
+ if (c === '{') depth++;
2731
+ else if (c === '}') {
2732
+ depth--;
2733
+ if (depth === 0) return i;
2734
+ }
2735
+ }
2736
+ return -1;
2737
+ }
2738
+
2739
+ function findTopLevelColon(str) {
2740
+ let depth = 0;
2741
+ let inStr = null;
2742
+ let esc = false;
2743
+ for (let i = 0; i < str.length; i++) {
2744
+ const c = str[i];
2745
+ if (inStr) {
2746
+ if (esc) esc = false;
2747
+ else if (c === '\\') esc = true;
2748
+ else if (c === inStr) inStr = null;
2749
+ continue;
2750
+ }
2751
+ if (c === "'" || c === '"' || c === '`') {
2752
+ inStr = c;
2753
+ continue;
2754
+ }
2755
+ if (c === '(' || c === '[' || c === '{') depth++;
2756
+ else if (c === ')' || c === ']' || c === '}') depth--;
2757
+ if (c === ':' && depth === 0) return i;
2758
+ }
2759
+ return -1;
2760
+ }
2761
+
2762
+ // Resolves a locally-defined, trivial SVG wrapper component (e.g. a hand-
2763
+ // rolled brand icon not in any icon package: `const TiktokIcon = (props) =>
2764
+ // (<svg viewBox="..." className={props.className}>...</svg>)`) by extracting
2765
+ // its literal JSX and swapping its own className passthrough for a
2766
+ // placeholder — substituteStaticMapRow fills that in with the real call
2767
+ // site's className once resolved, the same way a package icon's className
2768
+ // gets merged into its real <svg>. Only this single "just forwards its own
2769
+ // className" shape is supported; anything else returns null so the caller
2770
+ // can fall back to today's behavior instead of risking a bad inline.
2771
+ function resolveLocalSvgComponent(sourceCode, compName) {
2772
+ if (!sourceCode) return null;
2773
+ const declRx = new RegExp(
2774
+ `const\\s+${compName}\\s*=\\s*\\([^)]*\\)(?:\\s*:[^=]+)?\\s*=>\\s*\\(`,
2775
+ );
2776
+ const declMatch = sourceCode.match(declRx);
2777
+ if (!declMatch) return null;
2778
+ const parenOpenIdx = declMatch.index + declMatch[0].length - 1;
2779
+ const parenCloseIdx = findMatchingParenClose(sourceCode, parenOpenIdx);
2780
+ if (parenCloseIdx === -1) return null;
2781
+ const jsx = sourceCode.slice(parenOpenIdx + 1, parenCloseIdx).trim();
2782
+ if (!/^<svg\b/i.test(jsx)) return null;
2783
+ if (!/\bclassName\s*=\s*\{[^}]*\}/.test(jsx)) return null;
2784
+ return jsx.replace(
2785
+ /\bclassName\s*=\s*\{[^}]*\}/,
2786
+ 'class="__FORGEWP_ICON_CLASS__"',
2787
+ );
2788
+ }
2789
+
2790
+ // Resolves one object-literal field value (raw JS text) to either a PHP
2791
+ // expression (literal string, or code referencing an already-defined local
2792
+ // var like $phone) or, for a value that's a bare component reference
2793
+ // matching settings.importMap (e.g. `icon: Phone`), a deferred icon
2794
+ // reference — actual SVG resolution happens at substitution time, once the
2795
+ // JSX call site's own className is known (so e.g. `<Icon className="w-4 h-4" />`
2796
+ // gets that class merged into the real <svg>, matching how a directly-named
2797
+ // `<Phone className="…" />` tag is already resolved elsewhere in this file).
2798
+ function resolveStaticMapValue(
2799
+ rawValue,
2800
+ settings,
2801
+ localVarNames,
2802
+ sourceCode = '',
2803
+ freeFunctions = new Set(),
2804
+ ) {
2805
+ // Strip a trailing TS type assertion (`undefined as string | undefined`,
2806
+ // `x as const`, …) — the fields in this object-literal idiom commonly carry
2807
+ // one to satisfy a shared row type across items with different value shapes.
2808
+ let v = rawValue
2809
+ .trim()
2810
+ .replace(/\s+as\s+[^,}]+$/, '')
2811
+ .trim();
2812
+
2813
+ if (v === 'undefined' || v === 'null') {
2814
+ return { kind: 'text', phpText: 'null' };
2815
+ }
2816
+
2817
+ const strMatch = v.match(/^'((?:[^'\\]|\\.)*)'$|^"((?:[^"\\]|\\.)*)"$/);
2818
+ if (strMatch) {
2819
+ const text = (strMatch[1] ?? strMatch[2] ?? '').replace(/\\(['"])/g, '$1');
2820
+ return {
2821
+ kind: 'text',
2822
+ phpText: `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`,
2823
+ };
2824
+ }
2825
+
2826
+ if (v.startsWith('`') && v.endsWith('`')) {
2827
+ const templateContent = v.slice(1, -1);
2828
+ const parts = [];
2829
+ let lastIdx = 0;
2830
+ const rx = /\$\{\s*([\s\S]*?)\s*\}/g;
2831
+ let m;
2832
+ while ((m = rx.exec(templateContent)) !== null) {
2833
+ const textBefore = templateContent.substring(lastIdx, m.index);
2834
+ if (textBefore)
2835
+ parts.push(
2836
+ `'${textBefore.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`,
2837
+ );
2838
+ const exprName = m[1].trim();
2839
+ parts.push(
2840
+ localVarNames.has(exprName)
2841
+ ? `$${exprName}`
2842
+ : `(${translateJsExpressionToPhp(exprName, Object.keys(settings.attributes || {}), localVarNames, freeFunctions)})`,
2843
+ );
2844
+ lastIdx = rx.lastIndex;
2845
+ }
2846
+ const textAfter = templateContent.substring(lastIdx);
2847
+ if (textAfter)
2848
+ parts.push(`'${textAfter.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`);
2849
+ return { kind: 'text', phpText: parts.join(' . ') || "''" };
2850
+ }
2851
+
2852
+ // `cond ? trueBranch : falseBranch` — e.g. `url ? getHandle(url) : ''`.
2853
+ // Recurse into each branch (handles a template literal or helper call in
2854
+ // the true branch, a plain string in the false branch) rather than falling
2855
+ // straight to the generic fallback below, which has no ternary-aware
2856
+ // per-branch handling and would otherwise mistranslate the whole thing.
2857
+ const ternaryBounds = parseTernaryBounds(v);
2858
+ if (ternaryBounds) {
2859
+ const condText = v.slice(0, ternaryBounds.qIdx).trim();
2860
+ const trueText = v
2861
+ .slice(ternaryBounds.qIdx + 1, ternaryBounds.colonIdx)
2862
+ .trim();
2863
+ const falseText = v.slice(ternaryBounds.colonIdx + 1).trim();
2864
+ const trueResolved = resolveStaticMapValue(
2865
+ trueText,
2866
+ settings,
2867
+ localVarNames,
2868
+ sourceCode,
2869
+ freeFunctions,
2870
+ );
2871
+ const falseResolved = resolveStaticMapValue(
2872
+ falseText,
2873
+ settings,
2874
+ localVarNames,
2875
+ sourceCode,
2876
+ freeFunctions,
2877
+ );
2878
+ // Icons never appear in a ternary branch for this idiom, only text does —
2879
+ // only combine when both branches actually resolved to plain text.
2880
+ if (trueResolved.kind === 'text' && falseResolved.kind === 'text') {
2881
+ const condPhp = translateJsExpressionToPhp(
2882
+ condText,
2883
+ Object.keys(settings.attributes || {}),
2884
+ localVarNames,
2885
+ freeFunctions,
2886
+ );
2887
+ return {
2888
+ kind: 'text',
2889
+ phpText: `(${condPhp} ? ${trueResolved.phpText} : ${falseResolved.phpText})`,
2890
+ };
2891
+ }
2892
+ }
2893
+
2894
+ const identMatch = v.match(/^[A-Za-z_$][\w$]*$/);
2895
+ if (identMatch) {
2896
+ if (settings.importMap && settings.importMap[v]) {
2897
+ return {
2898
+ kind: 'icon',
2899
+ componentName: v,
2900
+ packageName: settings.importMap[v],
2901
+ };
2902
+ }
2903
+ if (localVarNames.has(v)) {
2904
+ return { kind: 'text', phpText: `$${v}` };
2905
+ }
2906
+ const svgTemplate = resolveLocalSvgComponent(sourceCode, v);
2907
+ if (svgTemplate) {
2908
+ return {
2909
+ kind: 'icon',
2910
+ componentName: v,
2911
+ packageName: '__local__',
2912
+ svgTemplate,
2913
+ };
2914
+ }
2915
+ // An unresolvable capitalized (component-like) reference — e.g. a locally
2916
+ // defined component this scope can't safely inline any other way —
2917
+ // degrades to nothing rather than leaking a broken `$CompName` PHP
2918
+ // variable reference into the output.
2919
+ if (/^[A-Z]/.test(v)) {
2920
+ return { kind: 'text', phpText: "''" };
2921
+ }
2922
+ }
2923
+
2924
+ // Best-effort fallback for anything else (e.g. a nested expression this
2925
+ // scope doesn't specifically model) — pass through translateJsExpressionToPhp,
2926
+ // which already handles the common shapes (attribute keys, ?? fallbacks, etc).
2927
+ return {
2928
+ kind: 'text',
2929
+ phpText: translateJsExpressionToPhp(
2930
+ v,
2931
+ Object.keys(settings.attributes || {}),
2932
+ localVarNames,
2933
+ freeFunctions,
2934
+ ),
2935
+ };
2936
+ }
2937
+
2938
+ // Substitutes one row's resolved alias values into the JSX template text.
2939
+ // Mirrors substituteLoopVarInJsx's attr-vs-text distinction, but per-alias
2940
+ // with that row's own already-resolved value rather than a generic $row[key].
2941
+ function substituteStaticMapRow(jsxTemplate, resolved, themeRoot) {
2942
+ let out = jsxTemplate;
2943
+ for (const [alias, value] of Object.entries(resolved)) {
2944
+ if (value.kind === 'icon') {
2945
+ const tagRx = new RegExp(`<${alias}\\b([^>]*?)/>`, 'g');
2946
+ out = out.replace(tagRx, (fullTag, attrsStr) => {
2947
+ const classMatch = attrsStr.match(
2948
+ /className\s*=\s*"([^"]*)"|className\s*=\s*'([^']*)'/,
2949
+ );
2950
+ const className = classMatch
2951
+ ? (classMatch[1] ?? classMatch[2] ?? '')
2952
+ : '';
2953
+ if (value.packageName === '__local__' && value.svgTemplate) {
2954
+ return value.svgTemplate.replace('__FORGEWP_ICON_CLASS__', className);
2955
+ }
2956
+ const svg = resolveIconToSvgHtml(
2957
+ value.componentName,
2958
+ value.packageName,
2959
+ themeRoot,
2960
+ className,
2961
+ );
2962
+ return svg || fullTag;
2963
+ });
2964
+ continue;
2965
+ }
2966
+ const phpExpr = value.phpText;
2967
+ const attrRx = new RegExp(`([a-zA-Z0-9_-]+)=\\{\\s*${alias}\\s*\\}`, 'g');
2968
+ out = out.replace(attrRx, (m, attrName) => {
2969
+ const escFunc =
2970
+ attrName === 'href' || attrName === 'src' ? 'esc_url' : 'esc_attr';
2971
+ return `${attrName}="<?php echo ${escFunc}(${phpExpr}); ?>"`;
2972
+ });
2973
+ // Bare `{alias}` (child-text position) — but NOT `${alias}` (a template-
2974
+ // literal interpolation, e.g. inside className={`… ${color}`}), which
2975
+ // the generic substitution below handles by embedding the raw value —
2976
+ // wrapping it in <?php echo …?> here too would double-process it.
2977
+ const bareRx = new RegExp(`(?<!\\$)\\{\\s*${alias}\\s*\\}`, 'g');
2978
+ out = out.replace(bareRx, `<?php echo esc_html(${phpExpr}); ?>`);
2979
+ // Remaining bare occurrences — inside __(alias), `${alias}` template
2980
+ // interpolation, or a ternary condition like `alias ? (A) : (B)` — get
2981
+ // the raw resolved PHP expression substituted directly; whichever later
2982
+ // pipeline stage processes that construct picks it up from there. Must
2983
+ // NOT match the attribute *name* left behind by attrRx above (e.g. the
2984
+ // literal `href="` in `href="<?php echo esc_url(...); ?>"` — same text
2985
+ // as the alias itself), so an immediately-following `="` is excluded.
2986
+ out = out.replace(
2987
+ new RegExp(`(?<![\\w$'"])${alias}(?![\\w$])(?!=")`, 'g'),
2988
+ phpExpr,
2989
+ );
2990
+ }
2991
+ out = out.replace(/className=/g, 'class=');
2992
+ return out;
2993
+ }
2994
+
2995
+ function unrollStaticArrayMap(
2996
+ arrayLiteralText,
2997
+ destructureText,
2998
+ jsxTemplate,
2999
+ settings,
3000
+ themeRoot,
3001
+ localVarNames,
3002
+ filterInfo = null,
3003
+ sourceCode = '',
3004
+ freeFunctions = new Set(),
3005
+ ) {
3006
+ const inner = arrayLiteralText.trim().replace(/^\[/, '').replace(/\]$/, '');
3007
+ const itemTexts = splitTopLevelArgs(inner)
3008
+ .map((s) => s.trim())
3009
+ .filter(Boolean);
3010
+ if (itemTexts.length === 0) return null;
3011
+
3012
+ const destructureEntries = splitTopLevelArgs(destructureText)
3013
+ .map((s) => s.trim())
3014
+ .filter(Boolean);
3015
+ const aliasToKey = new Map(); // alias -> original object key
3016
+ for (const entry of destructureEntries) {
3017
+ const renameMatch = entry.match(
3018
+ /^([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)$/,
3019
+ );
3020
+ if (renameMatch) {
3021
+ aliasToKey.set(renameMatch[2], renameMatch[1]);
3022
+ continue;
3023
+ }
3024
+ const shorthandMatch = entry.match(/^([A-Za-z_$][\w$]*)/);
3025
+ if (shorthandMatch) aliasToKey.set(shorthandMatch[1], shorthandMatch[1]);
3026
+ }
3027
+ if (aliasToKey.size === 0) return null;
3028
+
3029
+ const items = itemTexts.map((itemText) => {
3030
+ const t = itemText.trim();
3031
+ if (!t.startsWith('{') || !t.endsWith('}')) return null;
3032
+ const objInner = t.slice(1, -1);
3033
+ const pairs = splitTopLevelArgs(objInner)
3034
+ .map((s) => s.trim())
3035
+ .filter(Boolean);
3036
+ const obj = {};
3037
+ for (const pair of pairs) {
3038
+ const colonIdx = findTopLevelColon(pair);
3039
+ if (colonIdx === -1) continue;
3040
+ obj[pair.slice(0, colonIdx).trim()] = pair.slice(colonIdx + 1).trim();
3041
+ }
3042
+ return obj;
3043
+ });
3044
+ if (items.some((it) => it === null)) return null;
3045
+
3046
+ const copies = items.map((obj) => {
3047
+ const resolved = {};
3048
+ for (const [alias, key] of aliasToKey) {
3049
+ const rawValue = obj[key];
3050
+ resolved[alias] =
3051
+ rawValue === undefined
3052
+ ? { kind: 'text', phpText: "''" }
3053
+ : resolveStaticMapValue(
3054
+ rawValue,
3055
+ settings,
3056
+ localVarNames,
3057
+ sourceCode,
3058
+ freeFunctions,
3059
+ );
3060
+ }
3061
+ let rowJsx = substituteStaticMapRow(jsxTemplate, resolved, themeRoot);
3062
+
3063
+ // A trailing `.filter((s) => s.href && …)` on the source array (e.g. hiding
3064
+ // social-platform rows with no configured URL) can't be evaluated at
3065
+ // compile time — the values it checks are only known at request time
3066
+ // (a WordPress option). Re-express it as a per-row runtime PHP guard
3067
+ // instead of dropping the row outright or ignoring the filter.
3068
+ if (filterInfo) {
3069
+ const fieldRx = new RegExp(
3070
+ `\\b${filterInfo.paramName}\\.([A-Za-z_$][\\w$]*)`,
3071
+ 'g',
3072
+ );
3073
+ const substitutedCond = filterInfo.conditionText.replace(
3074
+ fieldRx,
3075
+ (m, field) => {
3076
+ const raw = obj[field];
3077
+ if (raw === undefined) return 'null';
3078
+ const trimmed = raw.trim();
3079
+ return /^[A-Za-z_$][\w$]*$/.test(trimmed) ? trimmed : `(${trimmed})`;
3080
+ },
3081
+ );
3082
+ const phpCond = translateJsExpressionToPhp(
3083
+ substitutedCond,
3084
+ Object.keys(settings.attributes || {}),
3085
+ localVarNames,
3086
+ freeFunctions,
3087
+ );
3088
+ rowJsx = `<?php if (${phpCond}): ?>\n${rowJsx}\n<?php endif; ?>`;
3089
+ }
3090
+
3091
+ return rowJsx;
3092
+ });
3093
+ return copies.join('\n');
3094
+ }
3095
+
3096
+ // Looks up `const IDENTIFIER = [ {...}, {...} ]` (optionally followed by a
3097
+ // `.filter((param) => condition)` chain) directly in the component's own
3098
+ // source — used for a `{socialList.map(({ destructured }) => (<jsx>))}` JSX
3099
+ // call site, where the array literal isn't inline at the .map() call (unlike
3100
+ // the phone/email/address/hours case) but a separate, previously-declared
3101
+ // header const. Returns null if IDENTIFIER isn't declared this way (i.e. it's
3102
+ // a genuine runtime array better left to transpileLoops).
3103
+ export function findHeaderConstArrayWithFilter(sourceCode, identifier) {
3104
+ const declRx = new RegExp(`const\\s+${identifier}\\s*=\\s*\\[`);
3105
+ const declMatch = sourceCode.match(declRx);
3106
+ if (!declMatch) return null;
3107
+ const bracketOpenIdx = declMatch.index + declMatch[0].length - 1;
3108
+ const bracketCloseIdx = findMatchingBracketClose(sourceCode, bracketOpenIdx);
3109
+ if (bracketCloseIdx === -1) return null;
3110
+ const arrayLiteralText = sourceCode.slice(
3111
+ bracketOpenIdx,
3112
+ bracketCloseIdx + 1,
3113
+ );
3114
+
3115
+ let filterInfo = null;
3116
+ const afterArray = sourceCode.slice(bracketCloseIdx + 1);
3117
+ const filterCallMatch = afterArray.match(/^\s*(?:as\s+const\s*)?\.filter\(/);
3118
+ if (filterCallMatch) {
3119
+ const filterParenOpenIdx =
3120
+ bracketCloseIdx + 1 + filterCallMatch[0].length - 1;
3121
+ const filterParenCloseIdx = findMatchingParenClose(
3122
+ sourceCode,
3123
+ filterParenOpenIdx,
3124
+ );
3125
+ if (filterParenCloseIdx !== -1) {
3126
+ const filterArgText = sourceCode
3127
+ .slice(filterParenOpenIdx + 1, filterParenCloseIdx)
3128
+ .trim();
3129
+ const arrowMatch = filterArgText.match(
3130
+ /^(?:\(\s*([a-zA-Z_$][\w$]*)\s*\)|([a-zA-Z_$][\w$]*))\s*=>\s*([\s\S]+)$/,
3131
+ );
3132
+ if (arrowMatch) {
3133
+ const paramName = arrowMatch[1] || arrowMatch[2];
3134
+ let conditionText = arrowMatch[3].trim();
3135
+ if (
3136
+ conditionText.startsWith('(') &&
3137
+ conditionText.endsWith(')') &&
3138
+ findMatchingParenClose(conditionText, 0) === conditionText.length - 1
3139
+ ) {
3140
+ conditionText = conditionText.slice(1, -1).trim();
3141
+ }
3142
+ filterInfo = { paramName, conditionText };
3143
+ }
3144
+ }
3145
+ }
3146
+ return { arrayLiteralText, filterInfo };
3147
+ }
3148
+
3149
+ // `{NAME.length > 0 && (...)}` guarding a static-array-with-filter header
3150
+ // const (e.g. `{socialList.length > 0 && (<div>…</div>)}`) can't be resolved
3151
+ // at compile time either, for the same reason the .filter() itself can't —
3152
+ // re-expressed as "is at least one row's own filter condition true at
3153
+ // request time", i.e. each row's condition OR'd together.
3154
+ //
3155
+ // That OR'd condition is long (one clause per row), and transpileConditionals
3156
+ // only recognizes `{COND && (...)}` when COND's own opening `{` sits within
3157
+ // ~100 characters of the `&&` — inlining the full expression here pushes the
3158
+ // two too far apart for it to ever match, silently leaving the whole `{...}`
3159
+ // block unconverted. So instead of inlining, this assigns the condition to a
3160
+ // short-named PHP var in a "prelude" the caller must prepend ahead of the
3161
+ // rest of the markup, and substitutes just that short bare name inline.
3162
+ export function translateStaticArrayLengthCheck(
3163
+ jsx,
3164
+ sourceCode,
3165
+ settings,
3166
+ localVarNames,
3167
+ freeFunctions = new Set(),
3168
+ ) {
3169
+ if (!sourceCode) return { jsx, prelude: '' };
3170
+ let prelude = '';
3171
+ const rx = /\b([a-zA-Z_$][\w$]*)\.length\s*>\s*0\b/g;
3172
+ const outJsx = jsx.replace(rx, (m, identifier) => {
3173
+ const found = findHeaderConstArrayWithFilter(sourceCode, identifier);
3174
+ if (!found || !found.filterInfo) return m;
3175
+ try {
3176
+ const inner = found.arrayLiteralText
3177
+ .trim()
3178
+ .replace(/^\[/, '')
3179
+ .replace(/\]$/, '');
3180
+ const itemTexts = splitTopLevelArgs(inner)
3181
+ .map((s) => s.trim())
3182
+ .filter(Boolean);
3183
+ const conds = itemTexts.map((itemText) => {
3184
+ const t = itemText.trim();
3185
+ if (!t.startsWith('{') || !t.endsWith('}')) return null;
3186
+ const objInner = t.slice(1, -1);
3187
+ const pairs = splitTopLevelArgs(objInner)
3188
+ .map((s) => s.trim())
3189
+ .filter(Boolean);
3190
+ const obj = {};
3191
+ for (const pair of pairs) {
3192
+ const colonIdx = findTopLevelColon(pair);
3193
+ if (colonIdx === -1) continue;
3194
+ obj[pair.slice(0, colonIdx).trim()] = pair.slice(colonIdx + 1).trim();
3195
+ }
3196
+ const fieldRx = new RegExp(
3197
+ `\\b${found.filterInfo.paramName}\\.([A-Za-z_$][\\w$]*)`,
3198
+ 'g',
3199
+ );
3200
+ const substituted = found.filterInfo.conditionText.replace(
3201
+ fieldRx,
3202
+ (mm, field) => {
3203
+ const raw = obj[field];
3204
+ if (raw === undefined) return 'null';
3205
+ const trimmed = raw.trim();
3206
+ return /^[A-Za-z_$][\w$]*$/.test(trimmed)
3207
+ ? trimmed
3208
+ : `(${trimmed})`;
3209
+ },
3210
+ );
3211
+ return translateJsExpressionToPhp(
3212
+ substituted,
3213
+ Object.keys(settings.attributes || {}),
3214
+ localVarNames,
3215
+ freeFunctions,
3216
+ );
3217
+ });
3218
+ if (conds.some((c) => c === null)) return m;
3219
+ const varName = `__forgewp_haslen_${identifier}`;
3220
+ prelude += `$${varName} = (${conds.join(' || ')});\n`;
3221
+ return varName;
3222
+ } catch (e) {
3223
+ return m;
3224
+ }
3225
+ });
3226
+ return { jsx: outJsx, prelude };
3227
+ }
3228
+
3229
+ // Handles `{IDENTIFIER.map(({ destructured }) => (<jsx>))}` where IDENTIFIER
3230
+ // is a bare reference to a header const declared as `const IDENTIFIER = [
3231
+ // {...}, ... ].filter(...)` (e.g. a social-links array built from a fixed set
3232
+ // of platforms, filtered down to whichever ones have a URL configured) —
3233
+ // distinct from transpileLoops' "Identifier Maps" case, which only handles a
3234
+ // non-destructured loop param (`items.map((item) => …)`), and from the inline-
3235
+ // array-literal case below, whose array is written directly at the .map()
3236
+ // call site rather than referenced by name.
3237
+ function transpileNamedStaticArrayObjectMap(
3238
+ phpMarkup,
3239
+ settings,
3240
+ themeRoot,
3241
+ localVarNames,
3242
+ sourceCode,
3243
+ freeFunctions = new Set(),
3244
+ ) {
3245
+ if (!sourceCode) return phpMarkup;
3246
+ const openRegex = /\{\s*([a-zA-Z_$][\w$]*)\s*\.map\(\s*\(\s*\{/g;
3247
+ let result = '';
3248
+ let cursor = 0;
3249
+ let match;
3250
+ while ((match = openRegex.exec(phpMarkup)) !== null) {
3251
+ if (match.index < cursor) continue;
3252
+ const identifier = match[1];
3253
+ const destructureBraceOpenIdx = match.index + match[0].length - 1;
3254
+ const destructureBraceCloseIdx = findMatchingCurlyClose(
3255
+ phpMarkup,
3256
+ destructureBraceOpenIdx,
3257
+ );
3258
+ if (destructureBraceCloseIdx === -1) continue;
3259
+
3260
+ const afterDestructure = phpMarkup.slice(destructureBraceCloseIdx + 1);
3261
+ const arrowMatch = afterDestructure.match(/^[^)]*\)\s*=>\s*\(/);
3262
+ if (!arrowMatch) continue;
3263
+
3264
+ const jsxOpenParenIdx =
3265
+ destructureBraceCloseIdx + 1 + arrowMatch[0].length - 1;
3266
+ const jsxCloseParenIdx = findMatchingParenClose(phpMarkup, jsxOpenParenIdx);
3267
+ if (jsxCloseParenIdx === -1) continue;
3268
+
3269
+ const afterJsx = phpMarkup.slice(jsxCloseParenIdx + 1);
3270
+ const closeMatch = afterJsx.match(/^\s*\)\s*\}/);
3271
+ if (!closeMatch) continue;
3272
+
3273
+ const wholeMatchEnd = jsxCloseParenIdx + 1 + closeMatch[0].length;
3274
+
3275
+ const found = findHeaderConstArrayWithFilter(sourceCode, identifier);
3276
+ let unrolled = null;
3277
+ if (found) {
3278
+ const destructureText = phpMarkup.slice(
3279
+ destructureBraceOpenIdx + 1,
3280
+ destructureBraceCloseIdx,
3281
+ );
3282
+ const jsxTemplate = phpMarkup.slice(
3283
+ jsxOpenParenIdx + 1,
3284
+ jsxCloseParenIdx,
3285
+ );
3286
+ try {
3287
+ unrolled = unrollStaticArrayMap(
3288
+ found.arrayLiteralText,
3289
+ destructureText,
3290
+ jsxTemplate,
3291
+ settings,
3292
+ themeRoot,
3293
+ localVarNames,
3294
+ found.filterInfo,
3295
+ sourceCode,
3296
+ freeFunctions,
3297
+ );
3298
+ } catch (e) {
3299
+ unrolled = null;
3300
+ }
3301
+ }
3302
+
3303
+ result += phpMarkup.slice(cursor, match.index);
3304
+ // Not a recognized static-array-with-filter header const — leave
3305
+ // untouched for transpileLoops (or whatever else already handles it)
3306
+ // rather than risk mistranslating a genuine runtime array.
3307
+ result +=
3308
+ unrolled !== null
3309
+ ? unrolled
3310
+ : phpMarkup.slice(match.index, wholeMatchEnd);
3311
+ cursor = wholeMatchEnd;
3312
+ openRegex.lastIndex = cursor;
3313
+ }
3314
+ result += phpMarkup.slice(cursor);
3315
+ return result;
3316
+ }
3317
+
3318
+ /**
3319
+ * Handles `(ARRAY_LITERAL as const).map(({ destructured }) => (<jsx>))` — a
3320
+ * common "small, fixed set of static rows with dynamic values" pattern (e.g.
3321
+ * a phone/email/address/hours details list, or a social-links array),
3322
+ * distinct from transpileLoops' simpler cases (which all require a bare
3323
+ * identifier before `.map()`, not an inline array-of-objects literal, and
3324
+ * don't support a destructured/renamed param). Since the array's shape is
3325
+ * fully known at compile time, this unrolls the loop into N literal copies
3326
+ * rather than emitting a PHP foreach — letting each row's own icon (a JSX
3327
+ * component reference, e.g. `icon: Phone`) be resolved to real SVG markup
3328
+ * once, per row, at compile time.
3329
+ */
3330
+ export function transpileStaticArrayObjectMap(
3331
+ phpMarkup,
3332
+ settings,
3333
+ themeRoot,
3334
+ localVarNames,
3335
+ sourceCode = '',
3336
+ freeFunctions = new Set(),
3337
+ ) {
3338
+ phpMarkup = transpileNamedStaticArrayObjectMap(
3339
+ phpMarkup,
3340
+ settings,
3341
+ themeRoot,
3342
+ localVarNames,
3343
+ sourceCode,
3344
+ freeFunctions,
3345
+ );
3346
+
3347
+ const openRegex = /\{\s*\(\s*\[/g;
3348
+ let result = '';
3349
+ let cursor = 0;
3350
+ let match;
3351
+ while ((match = openRegex.exec(phpMarkup)) !== null) {
3352
+ if (match.index < cursor) continue;
3353
+ const bracketOpenIdx = match.index + match[0].length - 1;
3354
+ const bracketCloseIdx = findMatchingBracketClose(phpMarkup, bracketOpenIdx);
3355
+ if (bracketCloseIdx === -1) continue;
3356
+
3357
+ const afterArray = phpMarkup.slice(bracketCloseIdx + 1);
3358
+ const mapHeadMatch = afterArray.match(
3359
+ /^\s*(?:as\s+const\s*)?\)\s*\.map\(\s*\(\s*\{/,
3360
+ );
3361
+ if (!mapHeadMatch) continue;
3362
+
3363
+ const destructureBraceOpenAbs =
3364
+ bracketCloseIdx + 1 + mapHeadMatch[0].length - 1;
3365
+ const destructureBraceCloseAbs = findMatchingCurlyClose(
3366
+ phpMarkup,
3367
+ destructureBraceOpenAbs,
3368
+ );
3369
+ if (destructureBraceCloseAbs === -1) continue;
3370
+
3371
+ const afterDestructure = phpMarkup.slice(destructureBraceCloseAbs + 1);
3372
+ // Must end exactly ON the opening `(` (no trailing `\s*`) — arrowMatch[0].length
3373
+ // is used below to index straight to that paren for the balance scan; consuming
3374
+ // trailing whitespace after it would point the scan at a space instead.
3375
+ const arrowMatch = afterDestructure.match(/^[^)]*\)\s*=>\s*\(/);
3376
+ if (!arrowMatch) continue;
3377
+
3378
+ const jsxOpenParenIdx =
3379
+ destructureBraceCloseAbs + 1 + arrowMatch[0].length - 1;
3380
+ const jsxCloseParenIdx = findMatchingParenClose(phpMarkup, jsxOpenParenIdx);
3381
+ if (jsxCloseParenIdx === -1) continue;
3382
+
3383
+ const afterJsx = phpMarkup.slice(jsxCloseParenIdx + 1);
3384
+ const closeMatch = afterJsx.match(/^\s*\)\s*\}/);
3385
+ if (!closeMatch) continue;
3386
+
3387
+ const wholeMatchEnd = jsxCloseParenIdx + 1 + closeMatch[0].length;
3388
+
3389
+ const arrayLiteralText = phpMarkup.slice(
3390
+ bracketOpenIdx,
3391
+ bracketCloseIdx + 1,
3392
+ );
3393
+ const destructureText = phpMarkup.slice(
3394
+ destructureBraceOpenAbs + 1,
3395
+ destructureBraceCloseAbs,
3396
+ );
3397
+ const jsxTemplate = phpMarkup.slice(jsxOpenParenIdx + 1, jsxCloseParenIdx);
3398
+
3399
+ let unrolled = null;
3400
+ try {
3401
+ unrolled = unrollStaticArrayMap(
3402
+ arrayLiteralText,
3403
+ destructureText,
3404
+ jsxTemplate,
3405
+ settings,
3406
+ themeRoot,
3407
+ localVarNames,
3408
+ null,
3409
+ sourceCode,
3410
+ freeFunctions,
3411
+ );
3412
+ } catch (e) {
3413
+ unrolled = null;
3414
+ }
3415
+
3416
+ result += phpMarkup.slice(cursor, match.index);
3417
+ // Safe fallback on any parse failure: leave the original text untouched
3418
+ // rather than emit anything broken — same bail philosophy used
3419
+ // throughout this pipeline.
3420
+ result +=
3421
+ unrolled !== null
3422
+ ? unrolled
3423
+ : phpMarkup.slice(match.index, wholeMatchEnd);
3424
+ cursor = wholeMatchEnd;
3425
+ openRegex.lastIndex = cursor;
3426
+ }
3427
+ result += phpMarkup.slice(cursor);
3428
+ return result;
3429
+ }
3430
+
3431
+ /**
3432
+ * ===========================================================================
3433
+ * AST-based PHP markup emitter — Phase 2 Step 4 (PHP half).
3434
+ * ===========================================================================
3435
+ *
3436
+ * generatePhpMarkupFromJsx parses the raw extracted JSX once and walks the
3437
+ * real AST to emit render.php markup directly, replacing the bulk of what
3438
+ * used to be ~20 independently-evolved regex/text passes in index.js
3439
+ * (JSX-tag balancing, brace-depth scanning for ternaries/conditionals,
3440
+ * attribute-shape regexes layered by increasing generality, …) with
3441
+ * recursive emitters keyed on node.type: ConditionalExpression,
3442
+ * LogicalExpression (&&), CallExpression (.map()), generic JSXElement/
3443
+ * JSXFragment/JSXText/JSXExpressionContainer.
3444
+ *
3445
+ * Deliberately NOT reimplemented here (left to the existing text-based
3446
+ * passes, unchanged, running on this function's output as a safety net):
3447
+ * - transpileStaticArrayObjectMap / translateStaticArrayLengthCheck: these
3448
+ * resolve a `const X = [...] as const` array declared elsewhere in the
3449
+ * *same source file* and statically unroll `.map()` over it into N literal
3450
+ * copies of the row template. That's a cross-reference into sibling source
3451
+ * text, not a property of the JSX subtree being emitted here — a
3452
+ * genuinely different concern from "turn this parsed expression into PHP".
3453
+ * tryEmitPhpMapLoop below emits supported dynamic array loop shapes
3454
+ * with confidence (a bare attribute/local-var array, or the `(x || '').
3455
+ * split(...)` string-split shape); anything else — an array literal
3456
+ * target, an `as const` cast, chained `.filter()` in an unrecognized
3457
+ * shape — is left as the original verbatim JSX text `{...}` so these
3458
+ * existing passes can still catch and unroll it downstream exactly as
3459
+ * before.
3460
+ *
3461
+ * Every leaf expression still goes through the existing, unchanged
3462
+ * translateJsExpressionToPhp — this migration is about correctly *finding*
3463
+ * expression/condition/loop boundaries via a real parser, not about
3464
+ * reimplementing PHP code generation for expressions that already works.
3465
+ *
3466
+ * Returns the emitted PHP markup string, or null if `jsxCode` doesn't parse
3467
+ * as a single clean JSX expression (falls back to the legacy text pipeline
3468
+ * — see index.js's call site) or if emission hits an unexpected shape it
3469
+ * has no safe fallback for.
3470
+ */
3471
+ export function generatePhpMarkupFromJsx(jsxCode, blockSettings, context) {
3472
+ const ast = tryParseSource(jsxCode);
3473
+ const body = ast && ast.program.body;
3474
+ if (!(body && body.length === 1 && body[0].type === 'ExpressionStatement'))
3475
+ return null;
3476
+ const rootExpr = body[0].expression;
3477
+ if (rootExpr.type !== 'JSXElement' && rootExpr.type !== 'JSXFragment')
3478
+ return null;
3479
+
3480
+ const fullContext = {
3481
+ attrKeys: Object.keys((blockSettings && blockSettings.attributes) || {}),
3482
+ localVars: (context && context.localVars) || new Set(),
3483
+ freeFunctions: (context && context.freeFunctions) || new Set(),
3484
+ themeRoot: context && context.themeRoot,
3485
+ importMap: (blockSettings && blockSettings.importMap) || {},
3486
+ textDomain: (context && context.textDomain) || 'hotelchecker24',
3487
+ queryState: { nextId: 0 },
3488
+ };
3489
+
3490
+ try {
3491
+ return emitPhpNode(rootExpr, jsxCode, blockSettings, fullContext);
3492
+ } catch {
3493
+ return null;
3494
+ }
3495
+ }
3496
+
3497
+ const VOID_HTML_TAGS = new Set([
3498
+ 'area',
3499
+ 'base',
3500
+ 'br',
3501
+ 'col',
3502
+ 'embed',
3503
+ 'hr',
3504
+ 'img',
3505
+ 'input',
3506
+ 'link',
3507
+ 'meta',
3508
+ 'param',
3509
+ 'source',
3510
+ 'track',
3511
+ 'wbr',
3512
+ 'path',
3513
+ 'circle',
3514
+ 'rect',
3515
+ 'line',
3516
+ 'polygon',
3517
+ 'polyline',
3518
+ 'ellipse',
3519
+ 'stop',
3520
+ 'use',
3521
+ ]);
3522
+
3523
+ function isJsxNodePhp(node) {
3524
+ return !!node && (node.type === 'JSXElement' || node.type === 'JSXFragment');
3525
+ }
3526
+
3527
+ function getPhpJsxTagName(nameNode) {
3528
+ if (nameNode.type === 'JSXIdentifier') return nameNode.name;
3529
+ if (nameNode.type === 'JSXMemberExpression') {
3530
+ return `${getPhpJsxTagName(nameNode.object)}.${nameNode.property.name}`;
3531
+ }
3532
+ if (nameNode.type === 'JSXNamespacedName')
3533
+ return `${nameNode.namespace.name}:${nameNode.name.name}`;
3534
+ return '';
3535
+ }
3536
+
3537
+ /** `[{ name, valueNode, hasValue }]` — valueNode is a StringLiteral or the
3538
+ * inner expression of a JSXExpressionContainer; null when boolean-shorthand. */
3539
+ function readPhpJsxAttrs(openingElement) {
3540
+ const attrs = [];
3541
+ for (const attr of openingElement.attributes) {
3542
+ if (attr.type !== 'JSXAttribute') continue; // spreads: never modeled by the legacy regex pipeline either
3543
+ const name =
3544
+ getPhpJsxTagName(attr.name) ||
3545
+ (attr.name.type === 'JSXIdentifier' ? attr.name.name : '');
3546
+ if (!attr.value) {
3547
+ attrs.push({ name, valueNode: null, hasValue: false });
3548
+ } else if (attr.value.type === 'JSXExpressionContainer') {
3549
+ attrs.push({ name, valueNode: attr.value.expression, hasValue: true });
3550
+ } else {
3551
+ attrs.push({ name, valueNode: attr.value, hasValue: true }); // StringLiteral
3552
+ }
3553
+ }
3554
+ return attrs;
3555
+ }
3556
+
3557
+ function findPhpAttr(attrs, name) {
3558
+ return attrs.find((a) => a.name === name) || null;
3559
+ }
3560
+
3561
+ function isStrippedPhpAttrName(name) {
3562
+ return (
3563
+ name === 'ref' ||
3564
+ name === 'disabled' ||
3565
+ name === 'checked' ||
3566
+ /^on[A-Z]/.test(name)
3567
+ );
3568
+ }
3569
+
3570
+ /**
3571
+ * Emit one JSX child/branch/condition expression that is NOT itself JSX.
3572
+ * Mirrors extractTernaryBranch's "only translate genuinely simple
3573
+ * expressions" bail: an IIFE, arrow function, or multi-statement body is far
3574
+ * beyond what translateJsExpressionToPhp can safely rewrite, so it degrades
3575
+ * to a blank echo instead of emitting mangled PHP.
3576
+ */
3577
+ function emitPhpLeafExpression(exprNode, code, context) {
3578
+ const exprText = code.slice(exprNode.start, exprNode.end);
3579
+ const looksComplex = /=>|\bfunction\b|;|\bconst\b|\blet\b|\bvar\b/.test(
3580
+ exprText,
3581
+ );
3582
+ if (looksComplex) return `<?php echo ''; ?>`;
3583
+ const phpExpr = translateJsExpressionToPhp(
3584
+ exprText,
3585
+ context.attrKeys,
3586
+ context.localVars,
3587
+ context.freeFunctions,
3588
+ );
3589
+ return `<?php echo esc_html( ${phpExpr} ); ?>`;
3590
+ }
3591
+
3592
+ /** A ternary/`&&` branch: JSX recurses into the element emitter; a further
3593
+ * nested ternary/`&&` recurses into emitPhpExpression; anything else is a
3594
+ * leaf expression. */
3595
+ function emitPhpBranch(node, code, blockSettings, context) {
3596
+ if (isJsxNodePhp(node))
3597
+ return emitPhpNode(node, code, blockSettings, context);
3598
+ if (
3599
+ node.type === 'ConditionalExpression' ||
3600
+ (node.type === 'LogicalExpression' && node.operator === '&&')
3601
+ ) {
3602
+ return emitPhpExpression(node, code, blockSettings, context);
3603
+ }
3604
+ return emitPhpLeafExpression(node, code, context);
3605
+ }
3606
+
3607
+ /**
3608
+ * `<arrayTarget>.map((param[, index]) => ( <JSX/> ))` → PHP foreach.
3609
+ * Only resolves the loop shapes transpileLoops' bare-identifier/split-map
3610
+ * regexes already covered — a bare attribute/local-var array, or `(x || '').
3611
+ * split(sep)[...].map(...)`. Anything else (array literal, `as const` cast,
3612
+ * unrecognized chain) returns null so the caller falls back to verbatim JSX
3613
+ * text for transpileStaticArrayObjectMap/transpileLoops to catch downstream.
3614
+ */
3615
+ function tryEmitPhpMapLoop(callExpr, code, blockSettings, context) {
3616
+ if (
3617
+ callExpr.arguments.length !== 1 ||
3618
+ callExpr.arguments[0].type !== 'ArrowFunctionExpression'
3619
+ )
3620
+ return null;
3621
+ const arrow = callExpr.arguments[0];
3622
+ if (!isJsxNodePhp(arrow.body)) return null; // only concise `=> ( <JSX/> )` bodies, matching legacy's scope
3623
+ if (arrow.params.length < 1 || arrow.params.length > 2) return null;
3624
+ const valueParam = arrow.params[0];
3625
+ const indexParam = arrow.params[1];
3626
+ if (indexParam && indexParam.type !== 'Identifier') return null;
3627
+
3628
+ const arrayTarget = callExpr.callee.object;
3629
+ let phpArrayExpr = null;
3630
+
3631
+ if (arrayTarget.type === 'Identifier') {
3632
+ // Matches legacy's idMapRegex exactly: always try the attribute override
3633
+ // first, then the bare identifier (a computed local var in the common
3634
+ // case; PHP just treats an undefined one as null via `??`, harmless),
3635
+ // then an empty array — never branch on whether it's "really" a known
3636
+ // local var, since legacy's transpileLoops never had that information
3637
+ // available either (it takes no localVars argument at all).
3638
+ const name = arrayTarget.name;
3639
+ phpArrayExpr = `($attributes['${name}'] ?? $${name} ?? array())`;
3640
+ } else if (arrayTarget.type === 'ArrayExpression') {
3641
+ phpArrayExpr = translateJsExpressionToPhp(
3642
+ code.slice(arrayTarget.start, arrayTarget.end),
3643
+ context.attrKeys,
3644
+ context.localVars,
3645
+ context.freeFunctions,
3646
+ );
3647
+ } else if (arrayTarget.type === 'MemberExpression') {
3648
+ const attrKey = getPhpMapAttributeKey(arrayTarget);
3649
+ if (attrKey !== null) {
3650
+ phpArrayExpr = `($attributes['${attrKey}'] ?? array())`;
3651
+ }
3652
+ } else if (
3653
+ arrayTarget.type === 'LogicalExpression' &&
3654
+ (arrayTarget.operator === '||' || arrayTarget.operator === '??')
3655
+ ) {
3656
+ const attrKey = getPhpMapAttributeKey(arrayTarget.left);
3657
+ if (attrKey !== null) {
3658
+ const fallback = emitPhpMapArrayFallback(
3659
+ arrayTarget.right,
3660
+ code,
3661
+ context,
3662
+ );
3663
+ if (fallback !== null) {
3664
+ phpArrayExpr = `($attributes['${attrKey}'] ?? ${fallback})`;
3665
+ }
3666
+ }
3667
+ } else {
3668
+ const split = matchPhpSplitMapTarget(arrayTarget, code);
3669
+ if (split) {
3670
+ phpArrayExpr = `array_filter(array_map('trim', explode('${split.separator}', ($attributes['${split.varName}'] ?? ''))))`;
3671
+ }
3672
+ }
3673
+ if (!phpArrayExpr) return null; // complex target (array literal, `as const`, …) — bail
3674
+
3675
+ const varName =
3676
+ valueParam.type === 'Identifier'
3677
+ ? valueParam.name
3678
+ : `__forgewp_row_${context.queryState.nextId++}`;
3679
+ const bindings = getPhpMapParamBindings(valueParam, varName);
3680
+ if (bindings === null) return null;
3681
+ const indexName = indexParam ? indexParam.name : null;
3682
+ const innerContext = {
3683
+ ...context,
3684
+ localVars: new Set([
3685
+ ...context.localVars,
3686
+ varName,
3687
+ ...(indexName ? [indexName] : []),
3688
+ ...bindings.map(({ name }) => name),
3689
+ ]),
3690
+ };
3691
+ let innerContent = emitPhpNode(arrow.body, code, blockSettings, innerContext);
3692
+ innerContent = innerContent.replace(/className=/g, 'class=');
3693
+
3694
+ const foreachValue =
3695
+ indexName && innerContent.includes(`$${indexName}`)
3696
+ ? `$${indexName} => $${varName}`
3697
+ : `$${varName}`;
3698
+ const bindingStatements = bindings
3699
+ .map(({ name, expression }) => `<?php $${name} = ${expression}; ?>`)
3700
+ .join('\n');
3701
+ return `<?php foreach (${phpArrayExpr} as ${foreachValue}): ?>\n${bindingStatements}${bindingStatements ? '\n' : ''}${innerContent}\n<?php endforeach; ?>`;
3702
+ }
3703
+
3704
+ function getPhpMapAttributeKey(node) {
3705
+ if (
3706
+ node.type !== 'MemberExpression' ||
3707
+ node.object.type !== 'Identifier' ||
3708
+ node.object.name !== 'attributes'
3709
+ ) {
3710
+ return null;
3711
+ }
3712
+
3713
+ if (!node.computed && node.property.type === 'Identifier') {
3714
+ return node.property.name;
3715
+ }
3716
+ if (
3717
+ node.computed &&
3718
+ (node.property.type === 'StringLiteral' ||
3719
+ node.property.type === 'NumericLiteral')
3720
+ ) {
3721
+ return String(node.property.value);
3722
+ }
3723
+ return null;
3724
+ }
3725
+
3726
+ function emitPhpMapArrayFallback(node, code, context) {
3727
+ if (node.type !== 'ArrayExpression') return null;
3728
+ const expression = code.slice(node.start, node.end);
3729
+ if (node.elements.some((item) => item?.type === 'ObjectExpression')) {
3730
+ return convertJsArrayToPhp(expression);
3731
+ }
3732
+ return translateJsExpressionToPhp(
3733
+ expression,
3734
+ context.attrKeys,
3735
+ context.localVars,
3736
+ context.freeFunctions,
3737
+ );
3738
+ }
3739
+
3740
+ function getPhpMapParamBindings(pattern, valueName) {
3741
+ if (pattern.type === 'Identifier') return [];
3742
+
3743
+ if (pattern.type === 'ArrayPattern') {
3744
+ const bindings = [];
3745
+ for (const [index, element] of pattern.elements.entries()) {
3746
+ if (element === null) continue;
3747
+ if (element.type !== 'Identifier') return null;
3748
+ bindings.push({
3749
+ name: element.name,
3750
+ expression: `($${valueName}[${index}] ?? null)`,
3751
+ });
3752
+ }
3753
+ return bindings;
3754
+ }
3755
+
3756
+ if (pattern.type === 'ObjectPattern') {
3757
+ const bindings = [];
3758
+ for (const property of pattern.properties) {
3759
+ if (
3760
+ property.type !== 'ObjectProperty' ||
3761
+ property.computed ||
3762
+ property.value.type !== 'Identifier'
3763
+ ) {
3764
+ return null;
3765
+ }
3766
+ const key =
3767
+ property.key.type === 'Identifier'
3768
+ ? property.key.name
3769
+ : property.key.type === 'StringLiteral'
3770
+ ? property.key.value
3771
+ : null;
3772
+ if (key === null) return null;
3773
+ const escapedKey = key.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
3774
+ bindings.push({
3775
+ name: property.value.name,
3776
+ expression: `($${valueName}['${escapedKey}'] ?? null)`,
3777
+ });
3778
+ }
3779
+ return bindings;
3780
+ }
3781
+
3782
+ return null;
3783
+ }
3784
+
3785
+ /** `(x || '').split(',')[.map(trim)][.filter(Boolean)]` → { varName, separator } | null */
3786
+ function matchPhpSplitMapTarget(node, code) {
3787
+ let current = node;
3788
+ // Peel optional trailing .filter(...) / .map(trim-like) calls.
3789
+ while (
3790
+ current.type === 'CallExpression' &&
3791
+ current.callee.type === 'MemberExpression' &&
3792
+ (current.callee.property.name === 'filter' ||
3793
+ current.callee.property.name === 'map')
3794
+ ) {
3795
+ current = current.callee.object;
3796
+ }
3797
+ if (
3798
+ current.type !== 'CallExpression' ||
3799
+ current.callee.type !== 'MemberExpression' ||
3800
+ current.callee.property.name !== 'split'
3801
+ ) {
3802
+ return null;
3803
+ }
3804
+ const sepArg = current.arguments[0];
3805
+ if (!sepArg || sepArg.type !== 'StringLiteral') return null;
3806
+ const base = current.callee.object;
3807
+ if (base.type !== 'LogicalExpression' || base.operator !== '||') return null;
3808
+ if (base.left.type !== 'Identifier') return null;
3809
+ const fallback = base.right;
3810
+ const isEmptyStringFallback =
3811
+ fallback.type === 'StringLiteral' && fallback.value === '';
3812
+ if (!isEmptyStringFallback) return null;
3813
+ return { varName: base.left.name, separator: sepArg.value };
3814
+ }
3815
+
3816
+ /** True when `node` (a ternary/&& condition) reads `.length` off a bare
3817
+ * identifier that is neither a block attribute nor a computed local —
3818
+ * i.e. a static array const only resolvable by reading the source file. */
3819
+ function hasUnresolvableLengthGuard(node, context) {
3820
+ if (!node || typeof node !== 'object' || typeof node.type !== 'string')
3821
+ return false;
3822
+ if (
3823
+ node.type === 'MemberExpression' &&
3824
+ !node.computed &&
3825
+ node.property.type === 'Identifier' &&
3826
+ node.property.name === 'length' &&
3827
+ node.object.type === 'Identifier' &&
3828
+ !context.localVars.has(node.object.name) &&
3829
+ !context.attrKeys.includes(node.object.name)
3830
+ ) {
3831
+ return true;
3832
+ }
3833
+ for (const key of Object.keys(node)) {
3834
+ if (AST_PHP_METADATA_KEYS.has(key)) continue;
3835
+ const val = node[key];
3836
+ if (Array.isArray(val)) {
3837
+ for (const item of val) {
3838
+ if (
3839
+ item &&
3840
+ typeof item.type === 'string' &&
3841
+ hasUnresolvableLengthGuard(item, context)
3842
+ )
3843
+ return true;
3844
+ }
3845
+ } else if (
3846
+ val &&
3847
+ typeof val.type === 'string' &&
3848
+ hasUnresolvableLengthGuard(val, context)
3849
+ ) {
3850
+ return true;
3851
+ }
3852
+ }
3853
+ return false;
3854
+ }
3855
+
3856
+ const AST_PHP_METADATA_KEYS = new Set([
3857
+ 'loc',
3858
+ 'start',
3859
+ 'end',
3860
+ 'range',
3861
+ 'extra',
3862
+ 'leadingComments',
3863
+ 'trailingComments',
3864
+ 'innerComments',
3865
+ 'comments',
3866
+ ]);
3867
+
3868
+ function emitPhpExpression(exprNode, code, blockSettings, context) {
3869
+ if (isJsxNodePhp(exprNode))
3870
+ return emitPhpNode(exprNode, code, blockSettings, context);
3871
+
3872
+ if (exprNode.type === 'ConditionalExpression') {
3873
+ const condText = code.slice(exprNode.test.start, exprNode.test.end);
3874
+ const phpCond = translateJsExpressionToPhp(
3875
+ condText,
3876
+ context.attrKeys,
3877
+ context.localVars,
3878
+ context.freeFunctions,
3879
+ );
3880
+ const trueContent = emitPhpBranch(
3881
+ exprNode.consequent,
3882
+ code,
3883
+ blockSettings,
3884
+ context,
3885
+ );
3886
+ const falseContent = emitPhpBranch(
3887
+ exprNode.alternate,
3888
+ code,
3889
+ blockSettings,
3890
+ context,
3891
+ );
3892
+ return `<?php if (${phpCond}): ?>\n${trueContent}\n<?php else: ?>\n${falseContent}\n<?php endif; ?>`;
3893
+ }
3894
+
3895
+ if (exprNode.type === 'LogicalExpression' && exprNode.operator === '&&') {
3896
+ // A `X.length > 0` guard where X is neither a block attribute nor a
3897
+ // computed local is a compile-time-static array const (e.g. a socialList
3898
+ // whose rows each carry their own URL-filter condition). Its length
3899
+ // cannot be known here — translateStaticArrayLengthCheck resolves it by
3900
+ // reading the array's declaration out of the component source, and that
3901
+ // pass matches on the literal `{X.length > 0 && (` text. Leave the whole
3902
+ // expression as verbatim JSX so it still finds its pattern downstream;
3903
+ // emitting the generic count($X ?? null) form instead would make the
3904
+ // guard always-false at render time (no $X PHP variable ever exists).
3905
+ if (hasUnresolvableLengthGuard(exprNode.left, context)) {
3906
+ return `{${code.slice(exprNode.start, exprNode.end)}}`;
3907
+ }
3908
+ const condText = code.slice(exprNode.left.start, exprNode.left.end);
3909
+ const phpCond = translateJsExpressionToPhp(
3910
+ condText,
3911
+ context.attrKeys,
3912
+ context.localVars,
3913
+ context.freeFunctions,
3914
+ );
3915
+ const content = emitPhpBranch(exprNode.right, code, blockSettings, context);
3916
+ return `<?php if (${phpCond}): ?>\n${content}\n<?php endif; ?>`;
3917
+ }
3918
+
3919
+ if (
3920
+ exprNode.type === 'CallExpression' &&
3921
+ exprNode.callee.type === 'MemberExpression' &&
3922
+ exprNode.callee.property.type === 'Identifier' &&
3923
+ exprNode.callee.property.name === 'map'
3924
+ ) {
3925
+ const loop = tryEmitPhpMapLoop(exprNode, code, blockSettings, context);
3926
+ if (loop !== null) return loop;
3927
+ // Bail to verbatim JSX text — see generatePhpMarkupFromJsx's doc comment.
3928
+ return `{${code.slice(exprNode.start, exprNode.end)}}`;
3929
+ }
3930
+
3931
+ // i18n: {__('Text', 'domain')}
3932
+ if (
3933
+ exprNode.type === 'CallExpression' &&
3934
+ exprNode.callee.type === 'Identifier' &&
3935
+ exprNode.callee.name === '__'
3936
+ ) {
3937
+ const arg0 = exprNode.arguments[0];
3938
+ if (arg0 && arg0.type === 'StringLiteral') {
3939
+ const escaped = arg0.value
3940
+ .replace(/'/g, "\\'")
3941
+ .trim()
3942
+ .replace(/\s+/g, ' ');
3943
+ return `<?php echo esc_html( __('${escaped}', '${context.textDomain}') ); ?>`;
3944
+ }
3945
+ }
3946
+
3947
+ if (exprNode.type === 'Identifier') {
3948
+ const varName = exprNode.name;
3949
+ const attrConfig =
3950
+ blockSettings &&
3951
+ blockSettings.attributes &&
3952
+ blockSettings.attributes[varName];
3953
+ const escFunc =
3954
+ attrConfig && attrConfig.control === 'richText'
3955
+ ? 'wp_kses_post'
3956
+ : 'esc_html';
3957
+ const prefix = context.localVars.has(varName)
3958
+ ? `$${varName}`
3959
+ : `$attributes['${varName}']`;
3960
+ return `<?php echo ${escFunc}( ${prefix} ?? '' ); ?>`;
3961
+ }
3962
+
3963
+ if (
3964
+ exprNode.type === 'MemberExpression' &&
3965
+ !exprNode.computed &&
3966
+ exprNode.object.type === 'Identifier' &&
3967
+ exprNode.property.type === 'Identifier'
3968
+ ) {
3969
+ const objName = exprNode.object.name;
3970
+ if (objName === 'attributes' || objName === 'props') {
3971
+ // Legacy's final `{attributes.X}` pass STRIPS the attributes./props.
3972
+ // prefix and then prefers the computed local var when one exists
3973
+ // (`const description = descriptionProp ?? descriptionMeta` must win
3974
+ // over the raw block attribute — the local carries the dual-host
3975
+ // meta-fallback resolution). Match that exactly.
3976
+ const varName = exprNode.property.name;
3977
+ const attrConfig =
3978
+ blockSettings &&
3979
+ blockSettings.attributes &&
3980
+ blockSettings.attributes[varName];
3981
+ const escFunc =
3982
+ attrConfig && attrConfig.control === 'richText'
3983
+ ? 'wp_kses_post'
3984
+ : 'esc_html';
3985
+ const prefix = context.localVars.has(varName)
3986
+ ? `$${varName}`
3987
+ : `$attributes['${varName}']`;
3988
+ return `<?php echo ${escFunc}( ${prefix} ?? '' ); ?>`;
3989
+ }
3990
+ const prefix = context.localVars.has(objName)
3991
+ ? `$${objName}`
3992
+ : `$attributes['${objName}']`;
3993
+ return `<?php echo esc_html( ${prefix}['${exprNode.property.name}'] ?? '' ); ?>`;
3994
+ }
3995
+
3996
+ return emitPhpLeafExpression(exprNode, code, context);
3997
+ }
3998
+
3999
+ function emitPhpChildren(children, code, blockSettings, context) {
4000
+ let out = '';
4001
+ for (const child of children) {
4002
+ if (child.type === 'JSXText') {
4003
+ out += child.value;
4004
+ } else if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
4005
+ out += emitPhpNode(child, code, blockSettings, context);
4006
+ } else if (child.type === 'JSXExpressionContainer') {
4007
+ if (child.expression.type === 'JSXEmptyExpression') continue; // {/* comment */}
4008
+ out += emitPhpExpression(child.expression, code, blockSettings, context);
4009
+ }
4010
+ }
4011
+ return out;
4012
+ }
4013
+
4014
+ /** style={{ prop: expr, ... }} → a single interpolated `style="..."` HTML attribute. */
4015
+ function emitPhpStyleAttr(objExpr, code, context) {
4016
+ const parts = [];
4017
+ for (const prop of objExpr.properties) {
4018
+ if (prop.type !== 'ObjectProperty') continue;
4019
+ const propName =
4020
+ prop.key.type === 'Identifier' ? prop.key.name : prop.key.value;
4021
+ const kebabProp = propName
4022
+ .replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2')
4023
+ .toLowerCase();
4024
+ const valText = code.slice(prop.value.start, prop.value.end);
4025
+ const phpExpr = translateJsExpressionToPhp(
4026
+ valText,
4027
+ context.attrKeys,
4028
+ context.localVars,
4029
+ context.freeFunctions,
4030
+ );
4031
+ parts.push(`${kebabProp}: <?php echo esc_attr( ${phpExpr} ); ?>;`);
4032
+ }
4033
+ return `style="${parts.join(' ')}"`;
4034
+ }
4035
+
4036
+ /** Generic `attr="literal"` / `attr={expr}` HTML attribute rendering (the
4037
+ * cascade of increasingly-generic regexes in index.js, unified). */
4038
+ function emitPhpSingleAttr(name, valueNode, hasValue, code, context) {
4039
+ if (!hasValue) return name; // boolean shorthand
4040
+ if (valueNode.type === 'StringLiteral') {
4041
+ return `${name}="${valueNode.value}"`;
4042
+ }
4043
+ // {'literal'} written with braces instead of the natural JSX shorthand.
4044
+ if (
4045
+ valueNode.type === 'StringLiteral' ||
4046
+ (valueNode.type === 'TemplateLiteral' && valueNode.expressions.length === 0)
4047
+ ) {
4048
+ const text =
4049
+ valueNode.type === 'StringLiteral'
4050
+ ? valueNode.value
4051
+ : valueNode.quasis[0].value.cooked;
4052
+ return `${name}="${text}"`;
4053
+ }
4054
+ const escFunc = name === 'href' || name === 'src' ? 'esc_url' : 'esc_attr';
4055
+ // Bare `attr={x}` / dotted `attr={x.y}` — legacy's specific attribute-value
4056
+ // cascade (distinct from the generic translateJsExpressionToPhp fallback
4057
+ // below) always uses `?? ''`, not `?? null`, and never double-wraps in
4058
+ // parens; match it exactly rather than going through the generic path,
4059
+ // which is semantically equivalent PHP but a needless divergence.
4060
+ if (valueNode.type === 'Identifier') {
4061
+ const varName = valueNode.name;
4062
+ const prefix = context.localVars.has(varName)
4063
+ ? `$${varName}`
4064
+ : `$attributes['${varName}']`;
4065
+ return `${name}="<?php echo ${escFunc}( ${prefix} ?? '' ); ?>"`;
4066
+ }
4067
+ if (
4068
+ valueNode.type === 'MemberExpression' &&
4069
+ !valueNode.computed &&
4070
+ valueNode.object.type === 'Identifier' &&
4071
+ valueNode.property.type === 'Identifier'
4072
+ ) {
4073
+ const objName = valueNode.object.name;
4074
+ if (objName === 'attributes' || objName === 'props') {
4075
+ // Same prefix-strip-then-prefer-local resolution as the child-position
4076
+ // `{attributes.X}` case — see emitPhpExpression's comment.
4077
+ const varName = valueNode.property.name;
4078
+ const prefix = context.localVars.has(varName)
4079
+ ? `$${varName}`
4080
+ : `$attributes['${varName}']`;
4081
+ return `${name}="<?php echo ${escFunc}( ${prefix} ?? '' ); ?>"`;
4082
+ }
4083
+ const prefix = context.localVars.has(objName)
4084
+ ? `$${objName}`
4085
+ : `$attributes['${objName}']`;
4086
+ return `${name}="<?php echo ${escFunc}( ${prefix}['${valueNode.property.name}'] ?? '' ); ?>"`;
4087
+ }
4088
+ // i18n: attr={__('Text')} — matches legacy's attr-position `__()` regex.
4089
+ // Must come before the generic fallback: `__` is not a known PHP-callable
4090
+ // to translateJsExpressionToPhp, whose neutralizeUnknownJsCalls pass would
4091
+ // blank the whole call (losing e.g. an image's alt text).
4092
+ if (
4093
+ valueNode.type === 'CallExpression' &&
4094
+ valueNode.callee.type === 'Identifier' &&
4095
+ valueNode.callee.name === '__' &&
4096
+ valueNode.arguments[0] &&
4097
+ valueNode.arguments[0].type === 'StringLiteral'
4098
+ ) {
4099
+ const escaped = valueNode.arguments[0].value
4100
+ .replace(/'/g, "\\'")
4101
+ .trim()
4102
+ .replace(/\s+/g, ' ');
4103
+ return `${name}="<?php echo esc_attr( __('${escaped}', '${context.textDomain}') ); ?>"`;
4104
+ }
4105
+ // class/className operands are always strings — safe to rewrite JS `+`
4106
+ // concatenation to PHP's `.` there (translateClassNameExpr), unlike the
4107
+ // generic case where `+` might be real numeric addition.
4108
+ const isClassAttr = name === 'class';
4109
+ const translate = (text) =>
4110
+ isClassAttr
4111
+ ? translateClassNameExpr(
4112
+ text,
4113
+ context.attrKeys,
4114
+ context.localVars,
4115
+ context.freeFunctions,
4116
+ )
4117
+ : translateJsExpressionToPhp(
4118
+ text,
4119
+ context.attrKeys,
4120
+ context.localVars,
4121
+ context.freeFunctions,
4122
+ );
4123
+ if (valueNode.type === 'TemplateLiteral') {
4124
+ // Interpolated FRAGMENTS always use esc_attr, even for href/src — the
4125
+ // scheme/static part of the URL lives in the literal quasis (e.g.
4126
+ // href={`mailto:${email}`}), and esc_url on a schemeless fragment would
4127
+ // "normalize" it by prepending http://, corrupting the assembled URL.
4128
+ let out = '';
4129
+ for (let i = 0; i < valueNode.quasis.length; i++) {
4130
+ out += valueNode.quasis[i].value.cooked;
4131
+ if (i < valueNode.expressions.length) {
4132
+ const exprText = code.slice(
4133
+ valueNode.expressions[i].start,
4134
+ valueNode.expressions[i].end,
4135
+ );
4136
+ out += `<?php echo esc_attr( ${translate(exprText)} ); ?>`;
4137
+ }
4138
+ }
4139
+ return `${name}="${out}"`;
4140
+ }
4141
+ const exprText = code.slice(valueNode.start, valueNode.end);
4142
+ return `${name}="<?php echo ${escFunc}( ${translate(exprText)} ); ?>"`;
4143
+ }
4144
+
4145
+ function emitPhpAttrsExcluding(attrs, code, context, extraExclude) {
4146
+ const parts = [];
4147
+ for (const { name, valueNode, hasValue } of attrs) {
4148
+ if (extraExclude.has(name)) continue;
4149
+ if (name === 'className') continue; // handled by caller (renamed to class=)
4150
+ if (name === 'key') continue;
4151
+ if (isStrippedPhpAttrName(name) && hasValue) continue;
4152
+ parts.push(
4153
+ emitPhpSingleAttr(
4154
+ name === 'className' ? 'class' : name,
4155
+ valueNode,
4156
+ hasValue,
4157
+ code,
4158
+ context,
4159
+ ),
4160
+ );
4161
+ }
4162
+ return parts.length ? ' ' + parts.join(' ') : '';
4163
+ }
4164
+
4165
+ /** Resolves a WpIcon `name={...}` expression the same way index.js's inline
4166
+ * <WpIcon> handling did — a bare loop-row property, a PHP-already var, a
4167
+ * plain attr key, or a translated fallback for anything else. */
4168
+ function resolvePhpIconNameExpr(expr, context) {
4169
+ if (/\$[a-zA-Z_]/.test(expr)) return expr;
4170
+ if (/^(?:attributes|props)\./.test(expr)) {
4171
+ return translateJsExpressionToPhp(
4172
+ expr,
4173
+ context.attrKeys,
4174
+ context.localVars,
4175
+ context.freeFunctions,
4176
+ );
4177
+ }
4178
+ const dotted = expr.match(/^([a-zA-Z_][\w$]*)\.([a-zA-Z_][\w$]*)$/);
4179
+ if (dotted) return `($${dotted[1]}['${dotted[2]}'] ?? '')`;
4180
+ const dottedFallback = expr.match(
4181
+ /^([a-zA-Z_][\w$]*)\.([a-zA-Z_][\w$]*)\s*\|\|\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")$/,
4182
+ );
4183
+ if (dottedFallback)
4184
+ return `($${dottedFallback[1]}['${dottedFallback[2]}'] ?: ${dottedFallback[3]})`;
4185
+ if (/^[a-zA-Z_][\w$]*$/.test(expr)) {
4186
+ return context.localVars.has(expr)
4187
+ ? `($${expr} ?? '')`
4188
+ : `($attributes['${expr}'] ?? '')`;
4189
+ }
4190
+ return translateJsExpressionToPhp(
4191
+ expr,
4192
+ context.attrKeys,
4193
+ context.localVars,
4194
+ context.freeFunctions,
4195
+ );
4196
+ }
4197
+
4198
+ function emitPhpWpIcon(attrs, code, context) {
4199
+ const nameAttr = findPhpAttr(attrs, 'name');
4200
+ const classAttr =
4201
+ findPhpAttr(attrs, 'className') || findPhpAttr(attrs, 'class');
4202
+ const providerAttr = findPhpAttr(attrs, 'provider');
4203
+
4204
+ let namePhp = "''";
4205
+ if (nameAttr && nameAttr.valueNode) {
4206
+ namePhp =
4207
+ nameAttr.valueNode.type === 'StringLiteral'
4208
+ ? JSON.stringify(nameAttr.valueNode.value)
4209
+ : resolvePhpIconNameExpr(
4210
+ code.slice(nameAttr.valueNode.start, nameAttr.valueNode.end),
4211
+ context,
4212
+ );
4213
+ }
4214
+ let classPhp = "''";
4215
+ if (classAttr && classAttr.valueNode) {
4216
+ classPhp =
4217
+ classAttr.valueNode.type === 'StringLiteral'
4218
+ ? JSON.stringify(classAttr.valueNode.value)
4219
+ : translateJsExpressionToPhp(
4220
+ code.slice(classAttr.valueNode.start, classAttr.valueNode.end),
4221
+ context.attrKeys,
4222
+ context.localVars,
4223
+ context.freeFunctions,
4224
+ );
4225
+ }
4226
+ const provider =
4227
+ providerAttr &&
4228
+ providerAttr.valueNode &&
4229
+ providerAttr.valueNode.type === 'StringLiteral'
4230
+ ? providerAttr.valueNode.value
4231
+ : 'lucide';
4232
+ return `<?php forgewp_render_theme_icon( ${namePhp}, ${classPhp}, ${JSON.stringify(provider)} ); ?>`;
4233
+ }
4234
+
4235
+ function emitPhpWpShortcode(attrs, code, context) {
4236
+ const codeAttr = findPhpAttr(attrs, 'code');
4237
+ let codePhp = "''";
4238
+ if (codeAttr && codeAttr.valueNode) {
4239
+ codePhp =
4240
+ codeAttr.valueNode.type === 'StringLiteral'
4241
+ ? `'${codeAttr.valueNode.value.replace(/'/g, "\\'")}'`
4242
+ : translateJsExpressionToPhp(
4243
+ code.slice(codeAttr.valueNode.start, codeAttr.valueNode.end),
4244
+ context.attrKeys,
4245
+ context.localVars,
4246
+ context.freeFunctions,
4247
+ );
4248
+ }
4249
+ return `<?php echo do_shortcode( ${codePhp} ); ?>`;
4250
+ }
4251
+
4252
+ function emitPhpWpEditable(attrs, children, code, blockSettings, context) {
4253
+ const tagAttr = findPhpAttr(attrs, 'tagName');
4254
+ const tag =
4255
+ tagAttr && tagAttr.valueNode && tagAttr.valueNode.type === 'StringLiteral'
4256
+ ? tagAttr.valueNode.value
4257
+ : 'div';
4258
+
4259
+ const valueAttr = findPhpAttr(attrs, 'value');
4260
+ let content;
4261
+ if (!valueAttr || !valueAttr.valueNode) {
4262
+ content = emitPhpChildren(children, code, blockSettings, context);
4263
+ } else {
4264
+ const vn = valueAttr.valueNode;
4265
+ let bareVarName = null;
4266
+ if (vn.type === 'Identifier') {
4267
+ bareVarName = vn.name;
4268
+ } else if (
4269
+ vn.type === 'MemberExpression' &&
4270
+ !vn.computed &&
4271
+ vn.object.type === 'Identifier' &&
4272
+ (vn.object.name === 'attributes' || vn.object.name === 'props') &&
4273
+ vn.property.type === 'Identifier'
4274
+ ) {
4275
+ bareVarName = vn.property.name;
4276
+ }
4277
+
4278
+ if (bareVarName) {
4279
+ // This is the (dead server-side) `setAttributes ? <WpEditable/> : …`
4280
+ // branch — `setAttributes` is never defined in render.php, so this
4281
+ // never actually executes, but still needs to be valid PHP. Prefer the
4282
+ // dual-host local var when one shadows this name (e.g. `const badge =
4283
+ // badgeProp ?? badgeMeta`) for consistency with how a plain `{badge}`
4284
+ // child expression resolves elsewhere in this same emitter.
4285
+ const attrConfig =
4286
+ blockSettings &&
4287
+ blockSettings.attributes &&
4288
+ blockSettings.attributes[bareVarName];
4289
+ const escFunc =
4290
+ attrConfig && attrConfig.control === 'richText'
4291
+ ? 'wp_kses_post'
4292
+ : 'esc_html';
4293
+ const prefix = context.localVars.has(bareVarName)
4294
+ ? `$${bareVarName}`
4295
+ : `$attributes['${bareVarName}']`;
4296
+ content = `<?php echo ${escFunc}( ${prefix} ?? '' ); ?>`;
4297
+ } else if (
4298
+ vn.type === 'MemberExpression' &&
4299
+ !vn.computed &&
4300
+ vn.object.type === 'Identifier' &&
4301
+ vn.property.type === 'Identifier'
4302
+ ) {
4303
+ content = `<?php echo esc_html( $${vn.object.name}['${vn.property.name}'] ?? '' ); ?>`;
4304
+ } else {
4305
+ content = emitPhpBranch(vn, code, blockSettings, context);
4306
+ }
4307
+ }
4308
+
4309
+ // emitPhpAttrsExcluding always skips className (the generic-element caller
4310
+ // is expected to prepend it as class= — WpEditable is a caller too).
4311
+ let attrsPhp = emitPhpAttrsExcluding(
4312
+ attrs,
4313
+ code,
4314
+ context,
4315
+ new Set(['tagName', 'value', 'onChange']),
4316
+ );
4317
+ const classAttr = findPhpAttr(attrs, 'className');
4318
+ if (classAttr) {
4319
+ attrsPhp =
4320
+ ` ${emitPhpSingleAttr('class', classAttr.valueNode, classAttr.hasValue, code, context)}` +
4321
+ attrsPhp;
4322
+ }
4323
+ return `<${tag}${attrsPhp}>${content}</${tag}>`;
4324
+ }
4325
+
4326
+ function phpAttributeExpression(attrs, name, code, context, fallback) {
4327
+ const attr = findPhpAttr(attrs, name);
4328
+ if (!attr || !attr.hasValue || !attr.valueNode) return fallback;
4329
+ const node = attr.valueNode;
4330
+ if (node.type === 'StringLiteral') return phpStringLiteral(node.value);
4331
+ if (node.type === 'NumericLiteral') return String(node.value);
4332
+ if (node.type === 'BooleanLiteral') return node.value ? 'true' : 'false';
4333
+ return translateJsExpressionToPhp(
4334
+ code.slice(node.start, node.end),
4335
+ context.attrKeys,
4336
+ context.localVars,
4337
+ context.freeFunctions,
4338
+ );
4339
+ }
4340
+
4341
+ function phpBooleanPropExpression(
4342
+ attrs,
4343
+ name,
4344
+ code,
4345
+ blockSettings,
4346
+ context,
4347
+ fallback,
4348
+ ) {
4349
+ const attr = findPhpAttr(attrs, name);
4350
+ if (!attr || !attr.hasValue || !attr.valueNode) {
4351
+ return fallback ? 'true' : 'false';
4352
+ }
4353
+
4354
+ const node = attr.valueNode;
4355
+ if (node.type === 'BooleanLiteral') return node.value ? 'true' : 'false';
4356
+
4357
+ let attributeName = null;
4358
+ if (node.type === 'Identifier') {
4359
+ attributeName = node.name;
4360
+ } else if (
4361
+ node.type === 'MemberExpression' &&
4362
+ !node.computed &&
4363
+ node.object.type === 'Identifier' &&
4364
+ (node.object.name === 'attributes' || node.object.name === 'props') &&
4365
+ node.property.type === 'Identifier'
4366
+ ) {
4367
+ attributeName = node.property.name;
4368
+ }
4369
+
4370
+ const attributeDefinition =
4371
+ attributeName &&
4372
+ blockSettings?.attributes &&
4373
+ blockSettings.attributes[attributeName];
4374
+ if (attributeDefinition?.type === 'boolean') {
4375
+ const defaultValue =
4376
+ typeof attributeDefinition.default === 'boolean'
4377
+ ? attributeDefinition.default
4378
+ : fallback;
4379
+ return `($attributes['${attributeName}'] ?? ${defaultValue ? 'true' : 'false'})`;
4380
+ }
4381
+
4382
+ if (node.type === 'Identifier') {
4383
+ return `($${node.name} ?? ${fallback ? 'true' : 'false'})`;
4384
+ }
4385
+
4386
+ return translateJsExpressionToPhp(
4387
+ code.slice(node.start, node.end),
4388
+ context.attrKeys,
4389
+ context.localVars,
4390
+ context.freeFunctions,
4391
+ );
4392
+ }
4393
+
4394
+ function emitPhpWpFormSubmitButton(attrs, children, code, blockSettings, context) {
4395
+ const iconAttr = findPhpAttr(attrs, 'icon');
4396
+ const showIconExpr = phpBooleanPropExpression(
4397
+ attrs,
4398
+ 'showIcon',
4399
+ code,
4400
+ blockSettings,
4401
+ context,
4402
+ true,
4403
+ );
4404
+ const pendingExpr = phpBooleanPropExpression(
4405
+ attrs,
4406
+ 'pending',
4407
+ code,
4408
+ blockSettings,
4409
+ context,
4410
+ false,
4411
+ );
4412
+ const disabledExpr = phpBooleanPropExpression(
4413
+ attrs,
4414
+ 'disabled',
4415
+ code,
4416
+ blockSettings,
4417
+ context,
4418
+ false,
4419
+ );
4420
+ const icon =
4421
+ iconAttr?.valueNode && isJsxNodePhp(iconAttr.valueNode)
4422
+ ? emitPhpNode(iconAttr.valueNode, code, blockSettings, context)
4423
+ : '';
4424
+ const iconMarkup = icon
4425
+ ? `<?php if ((${showIconExpr}) && !(${pendingExpr})): ?><span aria-hidden="true">${icon}</span><?php endif; ?>`
4426
+ : '';
4427
+ const disabledMarkup = `<?php if ((${disabledExpr}) || (${pendingExpr})): ?> disabled<?php endif; ?>`;
4428
+ const busyMarkup = `<?php if (${pendingExpr}): ?> aria-busy="true"<?php endif; ?>`;
4429
+ const excluded = new Set([
4430
+ 'type',
4431
+ 'icon',
4432
+ 'showIcon',
4433
+ 'pending',
4434
+ 'disabled',
4435
+ 'aria-busy',
4436
+ ]);
4437
+ let attrsPhp = emitPhpAttrsExcluding(attrs, code, context, excluded);
4438
+ const classAttr = findPhpAttr(attrs, 'className');
4439
+ if (classAttr) {
4440
+ attrsPhp =
4441
+ ` ${emitPhpSingleAttr('class', classAttr.valueNode, classAttr.hasValue, code, context)}` +
4442
+ attrsPhp;
4443
+ }
4444
+ const content = emitPhpChildren(children, code, blockSettings, context);
4445
+
4446
+ return `<button type="submit"${attrsPhp}${disabledMarkup}${busyMarkup}>${content}${iconMarkup}</button>`;
4447
+ }
4448
+
4449
+ function emitPhpWpQueryLoop(node, code, blockSettings, context) {
4450
+ const attrs = readPhpJsxAttrs(node.openingElement);
4451
+ const id = context.queryState.nextId++;
4452
+ const queryName = `$forgewp_query_${id}`;
4453
+ const argsName = `$forgewp_query_args_${id}`;
4454
+ const parentPostName = `$forgewp_parent_post_${id}`;
4455
+ const postsPerPageName = `$forgewp_posts_per_page_${id}`;
4456
+
4457
+ const postType = phpAttributeExpression(
4458
+ attrs,
4459
+ 'postType',
4460
+ code,
4461
+ context,
4462
+ "'post'",
4463
+ );
4464
+ const postsPerPage = phpAttributeExpression(
4465
+ attrs,
4466
+ 'postsPerPage',
4467
+ code,
4468
+ context,
4469
+ '3',
4470
+ );
4471
+ const order = phpAttributeExpression(attrs, 'order', code, context, "'DESC'");
4472
+ const categoryName = findPhpAttr(attrs, 'categoryName')
4473
+ ? phpAttributeExpression(attrs, 'categoryName', code, context, "''")
4474
+ : null;
4475
+ const orderby = findPhpAttr(attrs, 'orderby')
4476
+ ? phpAttributeExpression(attrs, 'orderby', code, context, "''")
4477
+ : null;
4478
+ const postId = findPhpAttr(attrs, 'postId')
4479
+ ? phpAttributeExpression(attrs, 'postId', code, context, '0')
4480
+ : null;
4481
+ const metaKey = findPhpAttr(attrs, 'metaKey')
4482
+ ? phpAttributeExpression(attrs, 'metaKey', code, context, "''")
4483
+ : null;
4484
+ const metaValue = phpAttributeExpression(
4485
+ attrs,
4486
+ 'metaValue',
4487
+ code,
4488
+ context,
4489
+ "''",
4490
+ );
4491
+ const metaCompare = phpAttributeExpression(
4492
+ attrs,
4493
+ 'metaCompare',
4494
+ code,
4495
+ context,
4496
+ "'='",
4497
+ );
4498
+ const taxTaxonomy = findPhpAttr(attrs, 'taxTaxonomy')
4499
+ ? phpAttributeExpression(attrs, 'taxTaxonomy', code, context, "''")
4500
+ : null;
4501
+ const taxTerms = findPhpAttr(attrs, 'taxTerms')
4502
+ ? phpAttributeExpression(attrs, 'taxTerms', code, context, "''")
4503
+ : null;
4504
+ const postIn = findPhpAttr(attrs, 'postIn')
4505
+ ? phpAttributeExpression(attrs, 'postIn', code, context, "''")
4506
+ : null;
4507
+
4508
+ const setup = [
4509
+ `global $post;`,
4510
+ `${parentPostName} = isset($post) ? $post : null;`,
4511
+ `${postsPerPageName} = intval(${postsPerPage});`,
4512
+ `${argsName} = array(`,
4513
+ ` 'post_type' => sanitize_key((string)(${postType})),`,
4514
+ ` 'post_status' => 'publish',`,
4515
+ ` 'posts_per_page' => (${postsPerPageName} === -1 ? -1 : max(1, ${postsPerPageName})),`,
4516
+ ` 'order' => (strtoupper((string)(${order})) === 'ASC' ? 'ASC' : 'DESC'),`,
4517
+ `);`,
4518
+ ];
4519
+
4520
+ if (orderby !== null) {
4521
+ setup.push(
4522
+ `if ((string)(${orderby}) !== '') { ${argsName}['orderby'] = sanitize_key((string)(${orderby})); }`,
4523
+ );
4524
+ }
4525
+ if (categoryName !== null) {
4526
+ setup.push(
4527
+ `if ((string)(${categoryName}) !== '') { ${argsName}['category_name'] = sanitize_title((string)(${categoryName})); }`,
4528
+ );
4529
+ }
4530
+ if (postId !== null) {
4531
+ setup.push(
4532
+ `if (absint(${postId}) > 0) { ${argsName}['p'] = absint(${postId}); }`,
4533
+ );
4534
+ }
4535
+ if (metaKey !== null) {
4536
+ const keyName = `$forgewp_meta_key_${id}`;
4537
+ const compareName = `$forgewp_meta_compare_${id}`;
4538
+ setup.push(
4539
+ `${keyName} = sanitize_key((string)(${metaKey}));`,
4540
+ `if (${keyName} !== '') {`,
4541
+ ` ${compareName} = strtoupper((string)(${metaCompare}));`,
4542
+ ` $forgewp_allowed_meta_compare_${id} = array('=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS', 'NOT EXISTS', 'REGEXP', 'NOT REGEXP', 'RLIKE');`,
4543
+ ` if (!in_array(${compareName}, $forgewp_allowed_meta_compare_${id}, true)) { ${compareName} = '='; }`,
4544
+ ` $forgewp_meta_query_${id} = array('key' => ${keyName}, 'compare' => ${compareName});`,
4545
+ );
4546
+ const valueAttr = findPhpAttr(attrs, 'metaValue');
4547
+ const specialValue =
4548
+ valueAttr?.valueNode?.type === 'StringLiteral'
4549
+ ? valueAttr.valueNode.value
4550
+ : null;
4551
+ let valueExpr = `sanitize_text_field((string)(${metaValue}))`;
4552
+ if (specialValue === 'CURRENT_POST_ID') {
4553
+ valueExpr = 'get_the_ID()';
4554
+ } else if (specialValue === ',CURRENT_POST_ID,') {
4555
+ valueExpr = "',' . get_the_ID() . ','";
4556
+ }
4557
+ setup.push(
4558
+ ` if (!in_array(${compareName}, array('EXISTS', 'NOT EXISTS'), true)) {`,
4559
+ ` $forgewp_meta_query_${id}['value'] = ${valueExpr};`,
4560
+ ` }`,
4561
+ ` ${argsName}['meta_query'] = array($forgewp_meta_query_${id});`,
4562
+ `}`,
4563
+ );
4564
+ }
4565
+ if (taxTaxonomy !== null) {
4566
+ setup.push(
4567
+ `$forgewp_taxonomy_${id} = sanitize_key((string)(${taxTaxonomy}));`,
4568
+ `$forgewp_terms_${id} = array_map('sanitize_title', wp_parse_list((string)(${taxTerms})));`,
4569
+ `if ($forgewp_taxonomy_${id} !== '' && !empty($forgewp_terms_${id})) {`,
4570
+ ` ${argsName}['tax_query'] = array(array('taxonomy' => $forgewp_taxonomy_${id}, 'field' => 'slug', 'terms' => $forgewp_terms_${id}));`,
4571
+ `}`,
4572
+ );
4573
+ }
4574
+ if (postIn !== null) {
4575
+ setup.push(
4576
+ `$forgewp_post_in_key_${id} = sanitize_key((string)(${postIn}));`,
4577
+ `$forgewp_post_in_value_${id} = $forgewp_post_in_key_${id} !== '' ? get_post_meta(get_the_ID(), $forgewp_post_in_key_${id}, true) : '';`,
4578
+ `$forgewp_post_in_ids_${id} = array_values(array_filter(array_map('absint', explode(',', (string)$forgewp_post_in_value_${id}))));`,
4579
+ `${argsName}['post__in'] = !empty($forgewp_post_in_ids_${id}) ? $forgewp_post_in_ids_${id} : array(-1);`,
4580
+ `${argsName}['orderby'] = 'post__in';`,
4581
+ );
4582
+ }
4583
+ setup.push(
4584
+ `if (function_exists('pll_current_language')) { ${argsName}['lang'] = pll_current_language(); }`,
4585
+ `${queryName} = new WP_Query(${argsName});`,
4586
+ `if (${queryName}->have_posts()) :`,
4587
+ `while (${queryName}->have_posts()) :`,
4588
+ `${queryName}->the_post();`,
4589
+ );
4590
+
4591
+ const content = emitPhpChildren(
4592
+ node.children,
4593
+ code,
4594
+ blockSettings,
4595
+ context,
4596
+ );
4597
+ return `<?php\n${setup.join('\n')}\n?>${content}<?php\nendwhile;\nwp_reset_postdata();\nif (${parentPostName} instanceof WP_Post) {\n $post = ${parentPostName};\n setup_postdata($post);\n}\nendif;\n?>`;
4598
+ }
4599
+
4600
+ function emitPhpWpImage(attrs, code, context) {
4601
+ const sizeExpr = phpAttributeExpression(attrs, 'size', code, context, "'full'");
4602
+ const srcAttr = findPhpAttr(attrs, 'src');
4603
+ const idAttr = findPhpAttr(attrs, 'id');
4604
+ const fieldAttr = findPhpAttr(attrs, 'field');
4605
+ let sourceExpr = "'assets/image-placeholder.png'";
4606
+ if (srcAttr) {
4607
+ sourceExpr = phpAttributeExpression(attrs, 'src', code, context, "''");
4608
+ } else if (idAttr) {
4609
+ sourceExpr = phpAttributeExpression(attrs, 'id', code, context, "''");
4610
+ } else if (fieldAttr) {
4611
+ const fieldExpr = phpAttributeExpression(attrs, 'field', code, context, "''");
4612
+ sourceExpr = `forgewp_get_meta_value(${fieldExpr}, '', false, null, false)`;
4613
+ }
4614
+
4615
+ const excluded = new Set([
4616
+ 'src',
4617
+ 'id',
4618
+ 'field',
4619
+ 'size',
4620
+ 'priority',
4621
+ 'loading',
4622
+ 'decoding',
4623
+ 'style',
4624
+ ]);
4625
+ let attrsPhp = emitPhpAttrsExcluding(attrs, code, context, excluded);
4626
+ const classAttr = findPhpAttr(attrs, 'className');
4627
+ if (classAttr) {
4628
+ attrsPhp =
4629
+ ` ${emitPhpSingleAttr('class', classAttr.valueNode, classAttr.hasValue, code, context)}` +
4630
+ attrsPhp;
4631
+ }
4632
+ if (!findPhpAttr(attrs, 'alt')) attrsPhp += ' alt=""';
4633
+
4634
+ const loadingAttr = findPhpAttr(attrs, 'loading');
4635
+ const decodingAttr = findPhpAttr(attrs, 'decoding');
4636
+ const priorityAttr = findPhpAttr(attrs, 'priority');
4637
+ const priorityExpr = priorityAttr
4638
+ ? priorityAttr.hasValue
4639
+ ? phpAttributeExpression(attrs, 'priority', code, context, 'false')
4640
+ : 'true'
4641
+ : 'false';
4642
+ if (loadingAttr) {
4643
+ attrsPhp += ` ${emitPhpSingleAttr('loading', loadingAttr.valueNode, loadingAttr.hasValue, code, context)}`;
4644
+ } else {
4645
+ attrsPhp += ` loading="<?php echo esc_attr( (${priorityExpr}) ? 'eager' : 'lazy' ); ?>"`;
4646
+ }
4647
+ if (decodingAttr) {
4648
+ attrsPhp += ` ${emitPhpSingleAttr('decoding', decodingAttr.valueNode, decodingAttr.hasValue, code, context)}`;
4649
+ } else {
4650
+ attrsPhp += ' decoding="async"';
4651
+ }
4652
+ if (priorityAttr) {
4653
+ attrsPhp += `<?php if (${priorityExpr}): ?> fetchpriority="high"<?php endif; ?>`;
4654
+ }
4655
+
4656
+ const styleAttr = findPhpAttr(attrs, 'style');
4657
+ if (styleAttr?.valueNode?.type === 'ObjectExpression') {
4658
+ attrsPhp += ' ' + emitPhpStyleAttr(styleAttr.valueNode, code, context);
4659
+ }
4660
+
4661
+ return `<img src="<?php echo esc_url(forgewp_resolve_image_source(${sourceExpr}, ${sizeExpr})); ?>"${attrsPhp} />`;
4662
+ }
4663
+
4664
+ function emitPhpGenericElement(
4665
+ tagName,
4666
+ attrs,
4667
+ children,
4668
+ node,
4669
+ code,
4670
+ blockSettings,
4671
+ context,
4672
+ ) {
4673
+ const dsetAttr = findPhpAttr(attrs, 'dangerouslySetInnerHTML');
4674
+ let contentOverride = null;
4675
+ if (
4676
+ dsetAttr &&
4677
+ dsetAttr.valueNode &&
4678
+ dsetAttr.valueNode.type === 'ObjectExpression'
4679
+ ) {
4680
+ const htmlProp = dsetAttr.valueNode.properties.find(
4681
+ (p) =>
4682
+ p.type === 'ObjectProperty' &&
4683
+ (p.key.name === '__html' || p.key.value === '__html'),
4684
+ );
4685
+ if (htmlProp) {
4686
+ if (htmlProp.value.type === 'Identifier') {
4687
+ const varName = htmlProp.value.name;
4688
+ const prefix = context.localVars.has(varName)
4689
+ ? `$${varName}`
4690
+ : `$attributes['${varName}']`;
4691
+ contentOverride = `<?php echo wp_kses_post( ${prefix} ?? '' ); ?>`;
4692
+ } else {
4693
+ const exprText = code.slice(htmlProp.value.start, htmlProp.value.end);
4694
+ const phpExpr = translateJsExpressionToPhp(
4695
+ exprText,
4696
+ context.attrKeys,
4697
+ context.localVars,
4698
+ context.freeFunctions,
4699
+ );
4700
+ contentOverride = `<?php echo wp_kses_post( ${phpExpr} ); ?>`;
4701
+ }
4702
+ }
4703
+ }
4704
+
4705
+ const styleAttr = findPhpAttr(attrs, 'style');
4706
+ let attrsPhp = emitPhpAttrsExcluding(
4707
+ attrs,
4708
+ code,
4709
+ context,
4710
+ new Set(['dangerouslySetInnerHTML', 'style']),
4711
+ );
4712
+ const classAttr = findPhpAttr(attrs, 'className');
4713
+ if (classAttr) {
4714
+ attrsPhp =
4715
+ ` ${emitPhpSingleAttr('class', classAttr.valueNode, classAttr.hasValue, code, context)}` +
4716
+ attrsPhp;
4717
+ }
4718
+ if (
4719
+ styleAttr &&
4720
+ styleAttr.valueNode &&
4721
+ styleAttr.valueNode.type === 'ObjectExpression'
4722
+ ) {
4723
+ attrsPhp += ' ' + emitPhpStyleAttr(styleAttr.valueNode, code, context);
4724
+ }
4725
+
4726
+ const content =
4727
+ contentOverride !== null
4728
+ ? contentOverride
4729
+ : emitPhpChildren(children, code, blockSettings, context);
4730
+ if (
4731
+ !content &&
4732
+ node.openingElement.selfClosing &&
4733
+ VOID_HTML_TAGS.has(tagName.toLowerCase())
4734
+ ) {
4735
+ return `<${tagName}${attrsPhp} />`;
4736
+ }
4737
+ return `<${tagName}${attrsPhp}>${content}</${tagName}>`;
4738
+ }
4739
+
4740
+ function emitPhpNode(node, code, blockSettings, context) {
4741
+ if (node.type === 'JSXFragment') {
4742
+ return emitPhpChildren(node.children, code, blockSettings, context);
4743
+ }
4744
+
4745
+ const sourceTagName = getPhpJsxTagName(node.openingElement.name);
4746
+ const isMotionTag = /^motion\.[a-z][\w-]*$/.test(sourceTagName);
4747
+ const tagName = isMotionTag
4748
+ ? sourceTagName.slice('motion.'.length)
4749
+ : sourceTagName;
4750
+ const motionOnlyProps = new Set([
4751
+ 'animate',
4752
+ 'drag',
4753
+ 'dragConstraints',
4754
+ 'exit',
4755
+ 'initial',
4756
+ 'layout',
4757
+ 'layoutId',
4758
+ 'onAnimationComplete',
4759
+ 'onUpdate',
4760
+ 'transition',
4761
+ 'variants',
4762
+ 'viewport',
4763
+ 'whileDrag',
4764
+ 'whileFocus',
4765
+ 'whileHover',
4766
+ 'whileInView',
4767
+ 'whileTap',
4768
+ ]);
4769
+ const attrs = readPhpJsxAttrs(node.openingElement).filter(
4770
+ (attr) => !isMotionTag || !motionOnlyProps.has(attr.name),
4771
+ );
4772
+
4773
+ if (tagName === 'WpQueryLoop')
4774
+ return emitPhpWpQueryLoop(node, code, blockSettings, context);
4775
+ if (tagName === 'WpImage') return emitPhpWpImage(attrs, code, context);
4776
+ if (tagName === 'WpIcon') return emitPhpWpIcon(attrs, code, context);
4777
+ if (tagName === 'WpShortcode')
4778
+ return emitPhpWpShortcode(attrs, code, context);
4779
+ if (tagName === 'WpFormSubmitButton')
4780
+ return emitPhpWpFormSubmitButton(
4781
+ attrs,
4782
+ node.children,
4783
+ code,
4784
+ blockSettings,
4785
+ context,
4786
+ );
4787
+ if (tagName === 'WpEditable')
4788
+ return emitPhpWpEditable(
4789
+ attrs,
4790
+ node.children,
4791
+ code,
4792
+ blockSettings,
4793
+ context,
4794
+ );
4795
+
4796
+ const isPascalCase = /^[A-Z]/.test(tagName);
4797
+ if (isPascalCase && context.importMap[tagName] && context.themeRoot) {
4798
+ const classAttr = findPhpAttr(attrs, 'className');
4799
+ let classNameStr = '';
4800
+ if (classAttr && classAttr.valueNode) {
4801
+ classNameStr =
4802
+ classAttr.valueNode.type === 'StringLiteral'
4803
+ ? classAttr.valueNode.value
4804
+ : `<?php echo esc_attr( ${translateJsExpressionToPhp(code.slice(classAttr.valueNode.start, classAttr.valueNode.end), context.attrKeys, context.localVars, context.freeFunctions)} ); ?>`;
4805
+ }
4806
+ let svgHtml = resolveIconToSvgHtml(
4807
+ tagName,
4808
+ context.importMap[tagName],
4809
+ context.themeRoot,
4810
+ '',
4811
+ );
4812
+ if (svgHtml) {
4813
+ const iconSize = getPhpStaticNumericAttr(attrs, 'size', code);
4814
+ const width =
4815
+ getPhpStaticNumericAttr(attrs, 'width', code) ?? iconSize;
4816
+ const height =
4817
+ getPhpStaticNumericAttr(attrs, 'height', code) ?? iconSize;
4818
+ if (width !== null) {
4819
+ svgHtml = svgHtml.replace(/(\swidth=")[^"]*(")/, `$1${width}$2`);
4820
+ }
4821
+ if (height !== null) {
4822
+ svgHtml = svgHtml.replace(/(\sheight=")[^"]*(")/, `$1${height}$2`);
4823
+ }
4824
+ const classAttrRegex = /class="([^"]*)"/;
4825
+ const hasClassAttr = svgHtml.match(classAttrRegex);
4826
+ if (hasClassAttr) {
4827
+ return svgHtml.replace(
4828
+ classAttrRegex,
4829
+ `class="${(hasClassAttr[1] + ' ' + classNameStr).trim()}"`,
4830
+ );
4831
+ }
4832
+ return svgHtml.replace('<svg', `<svg class="${classNameStr.trim()}"`);
4833
+ }
4834
+ }
4835
+
4836
+ if (tagName === 'WpLink') {
4837
+ const hrefAttr = findPhpAttr(attrs, 'href');
4838
+ const classAttr = findPhpAttr(attrs, 'className');
4839
+ const href =
4840
+ hrefAttr && hrefAttr.valueNode
4841
+ ? hrefAttr.valueNode.type === 'StringLiteral'
4842
+ ? hrefAttr.valueNode.value
4843
+ : emitPhpSingleAttr(
4844
+ 'href',
4845
+ hrefAttr.valueNode,
4846
+ true,
4847
+ code,
4848
+ context,
4849
+ ).match(/="([\s\S]*)"$/)[1]
4850
+ : '#';
4851
+ const cls = classAttr
4852
+ ? classAttr.valueNode?.type === 'StringLiteral'
4853
+ ? ` class='${classAttr.valueNode.value}'`
4854
+ : classAttr.valueNode
4855
+ ? ` ${emitPhpSingleAttr(
4856
+ 'class',
4857
+ classAttr.valueNode,
4858
+ true,
4859
+ code,
4860
+ context,
4861
+ )}`
4862
+ : ' class=""'
4863
+ : '';
4864
+ const content = emitPhpChildren(
4865
+ node.children,
4866
+ code,
4867
+ blockSettings,
4868
+ context,
4869
+ );
4870
+ return `<a href="${href}"${cls}>${content}</a>`;
4871
+ }
4872
+ if (tagName === 'Button') {
4873
+ const classAttr = findPhpAttr(attrs, 'className');
4874
+ const cls = classAttr
4875
+ ? classAttr.valueNode?.type === 'StringLiteral'
4876
+ ? ` class='${classAttr.valueNode.value}'`
4877
+ : classAttr.valueNode
4878
+ ? ` ${emitPhpSingleAttr(
4879
+ 'class',
4880
+ classAttr.valueNode,
4881
+ true,
4882
+ code,
4883
+ context,
4884
+ )}`
4885
+ : ' class=""'
4886
+ : '';
4887
+ const content = emitPhpChildren(
4888
+ node.children,
4889
+ code,
4890
+ blockSettings,
4891
+ context,
4892
+ );
4893
+ return `<button${cls}>${content}</button>`;
4894
+ }
4895
+
4896
+ // Unknown PascalCase component (no importMap icon match, not a known
4897
+ // special tag): legacy strips self-closing instances entirely and unwraps
4898
+ // paired instances to just their children — a component with no PHP/HTML
4899
+ // equivalent contributes nothing of its own to the rendered page.
4900
+ if (isPascalCase) {
4901
+ if (node.openingElement.selfClosing || node.children.length === 0)
4902
+ return '';
4903
+ return emitPhpChildren(node.children, code, blockSettings, context);
4904
+ }
4905
+
4906
+ return emitPhpGenericElement(
4907
+ tagName,
4908
+ attrs,
4909
+ node.children,
4910
+ node,
4911
+ code,
4912
+ blockSettings,
4913
+ context,
4914
+ );
4915
+ }
4916
+
4917
+ function getPhpStaticNumericAttr(attrs, name, code) {
4918
+ const attr = findPhpAttr(attrs, name);
4919
+ if (!attr || !attr.valueNode) return null;
4920
+
4921
+ const raw =
4922
+ attr.valueNode.type === 'StringLiteral'
4923
+ ? attr.valueNode.value
4924
+ : code.slice(attr.valueNode.start, attr.valueNode.end);
4925
+ const value = String(raw).trim();
4926
+ if (!/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(value)) return null;
4927
+ return value;
4928
+ }