@forgewp/compiler 0.4.2 → 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 (144) hide show
  1. package/README.md +70 -3
  2. package/bin/add.js +30 -15
  3. package/bin/analyze.js +66 -1
  4. package/bin/cli.js +149 -70
  5. package/bin/doctor.js +21 -12
  6. package/bin/export.js +69 -20
  7. package/bin/fresh.js +6 -1
  8. package/bin/i18n-extract.js +3 -10
  9. package/bin/i18n-translate.js +15 -24
  10. package/bin/make-block.js +24 -0
  11. package/bin/make-editable.js +166 -0
  12. package/bin/make-form.js +131 -0
  13. package/bin/make-island.js +11 -0
  14. package/bin/make-loop.js +147 -0
  15. package/bin/make-mail.js +27 -0
  16. package/bin/make-page.js +83 -0
  17. package/bin/make-post-type.js +68 -29
  18. package/bin/make-sandbox.js +609 -0
  19. package/bin/make-section.js +221 -0
  20. package/bin/make-shell.js +375 -0
  21. package/bin/repair.js +14 -26
  22. package/bin/seed.js +119 -0
  23. package/bin/sync-routes.js +107 -85
  24. package/lib/adapters/html-adapter.js +13 -3
  25. package/lib/adapters/stub-adapter.js +10 -2
  26. package/lib/add-component.js +153 -92
  27. package/lib/asset-loader.js +333 -1
  28. package/lib/assets/asset-graph.js +432 -0
  29. package/lib/assets/asset-pipeline.js +125 -0
  30. package/lib/assets/diagnostics-report.js +345 -0
  31. package/lib/assets/external-fetcher.js +173 -0
  32. package/lib/assets/font-orchestrator.js +348 -0
  33. package/lib/assets/font-usage-scanner.js +242 -0
  34. package/lib/assets/image-optimizer.js +229 -0
  35. package/lib/assets/index.js +51 -0
  36. package/lib/assets/preload-generator.js +70 -0
  37. package/lib/assets/public-url.js +153 -0
  38. package/lib/block-authoring-help.js +11 -0
  39. package/lib/blocks/ast-parser.js +67 -0
  40. package/lib/blocks/discover-blocks.js +146 -0
  41. package/lib/blocks/editor-scope.js +733 -0
  42. package/lib/blocks/editor-transpiler.js +1229 -0
  43. package/lib/blocks/index.js +2838 -0
  44. package/lib/blocks/php-transpiler.js +4928 -0
  45. package/lib/blocks/scanner.js +1487 -0
  46. package/lib/blocks/shared-utils.js +290 -0
  47. package/lib/blocks/source-sanitize.js +1449 -0
  48. package/lib/blueprints.js +77 -5
  49. package/lib/build-assets.js +38 -33
  50. package/lib/collect-page-template-routes.js +102 -0
  51. package/lib/collect-static-routes.js +175 -0
  52. package/lib/diagnostics.js +58 -33
  53. package/lib/export-theme.js +84 -5
  54. package/lib/extract-template-content.js +90 -0
  55. package/lib/forms-preview.js +42 -0
  56. package/lib/functions/cpt-routing.js +69 -0
  57. package/lib/functions/forms.js +2461 -0
  58. package/lib/functions/hydration-enqueuer.js +400 -0
  59. package/lib/functions/index.js +1623 -0
  60. package/lib/functions/load-menus.js +112 -0
  61. package/lib/functions/load-translations.js +148 -0
  62. package/lib/functions/rest-endpoints.js +2923 -0
  63. package/lib/functions/routing.js +765 -0
  64. package/lib/functions/seed-mock-data.js +392 -0
  65. package/lib/functions/seed-products.js +481 -0
  66. package/lib/functions/settings-page.js +273 -0
  67. package/lib/functions/theme-setup.js +494 -0
  68. package/lib/generate-theme.js +2076 -303
  69. package/lib/hydration/editable-schemas.js +332 -0
  70. package/lib/hydration/enter-hidden-initial.js +65 -0
  71. package/lib/hydration/form-schemas.js +227 -0
  72. package/lib/hydration/index.js +12 -0
  73. package/lib/hydration/is-interactive.js +951 -0
  74. package/lib/hydration/island-split.js +1231 -0
  75. package/lib/hydration/islands-scanner.js +599 -0
  76. package/lib/hydration/resolve-island-chunk.js +103 -0
  77. package/lib/hydration/resolve-island-component.js +52 -0
  78. package/lib/hydration/rollup-inputs.js +81 -0
  79. package/lib/hydration/root-class-extractor.js +220 -0
  80. package/lib/hydration/scan-app-providers.js +154 -0
  81. package/lib/hydration/static-lint.js +382 -0
  82. package/lib/hydration/transform.js +257 -0
  83. package/lib/hydration/uses-block-area.js +49 -0
  84. package/lib/hydration/utils.js +119 -0
  85. package/lib/i18n/translation-cache.js +141 -0
  86. package/lib/icon-registry.js +72 -0
  87. package/lib/index.d.ts +324 -8
  88. package/lib/index.js +3 -2
  89. package/lib/load-config.js +338 -144
  90. package/lib/mail-templates.js +37 -0
  91. package/lib/markup-processor.js +483 -92
  92. package/lib/node-runtime.js +7 -0
  93. package/lib/page-config-plugin.js +84 -0
  94. package/lib/php-builders.js +383 -42
  95. package/lib/react-adapter.js +1053 -246
  96. package/lib/registration-metadata.js +11 -0
  97. package/lib/render-theme.mts +1410 -543
  98. package/lib/route-layout.js +76 -0
  99. package/lib/template-discovery.js +58 -0
  100. package/lib/theme-compatibility.js +32 -0
  101. package/lib/validate-export.js +51 -2
  102. package/lib/validate.js +27 -5
  103. package/lib/virtual-plugin.js +319 -0
  104. package/lib/walkthrough.md +26 -0
  105. package/package.json +17 -5
  106. package/templates/PresetsStyle.tsx +1 -1
  107. package/templates/auth/cms/email-logs.json +9 -0
  108. package/templates/auth/cms/menus.json +11 -0
  109. package/templates/auth/cms/mock-data.json +123 -0
  110. package/templates/auth/cms/roles.json +7 -0
  111. package/templates/auth/cms/sessions.json +1 -0
  112. package/templates/auth/cms/site-settings.json +28 -0
  113. package/templates/auth/cms/translations.json +4 -0
  114. package/templates/auth/cms/users.json +46 -0
  115. package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
  116. package/templates/auth/components/forgot-password-form-wrapper.tsx +141 -0
  117. package/templates/auth/components/login-form-wrapper.tsx +300 -0
  118. package/templates/auth/components/reset-password-form-wrapper.tsx +190 -0
  119. package/templates/auth/components/signup-form-wrapper.tsx +257 -0
  120. package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
  121. package/templates/auth/pages/DashboardPage.tsx +12 -0
  122. package/templates/auth/pages/ForgotPasswordPage.tsx +11 -0
  123. package/templates/auth/pages/LoginPage.tsx +11 -0
  124. package/templates/auth/pages/ResetPasswordPage.tsx +11 -0
  125. package/templates/auth/pages/SignUpPage.tsx +11 -0
  126. package/templates/auth/pages/VerifyEmailPage.tsx +11 -0
  127. package/templates/auth/ui/button.tsx +57 -0
  128. package/templates/auth/ui/card.tsx +76 -0
  129. package/templates/auth/ui/field.tsx +242 -0
  130. package/templates/auth/ui/input.tsx +22 -0
  131. package/templates/auth/ui/label.tsx +24 -0
  132. package/templates/auth/ui/separator.tsx +31 -0
  133. package/templates/forgewp-config.ts +70 -3
  134. package/templates/menus.json +12 -10
  135. package/templates/mock-data.json +122 -433
  136. package/templates/products.json +5 -0
  137. package/templates/roles.json +7 -0
  138. package/templates/sessions.json +1 -0
  139. package/templates/users.json +38 -0
  140. package/templates/wordpress.tsx +1835 -1297
  141. package/bin/make-template.js +0 -145
  142. package/lib/block-compiler.js +0 -552
  143. package/lib/functions-builder.js +0 -2044
  144. package/lib/hydration-scanner.js +0 -821
@@ -1,145 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
4
- import path from "node:path";
5
- import pc from "picocolors";
6
- import { loadConfig } from "../lib/load-config.js";
7
- import { loadFrameworkAdapter } from "../lib/framework-adapter.js";
8
-
9
- const args = process.argv.slice(2);
10
- let rawTemplateName = args.find(a => !a.startsWith("-"));
11
-
12
- // Support --name PortfolioTemplate or --name=PortfolioTemplate
13
- const nameIndex = args.indexOf("--name");
14
- if (nameIndex !== -1 && args[nameIndex + 1]) {
15
- rawTemplateName = args[nameIndex + 1];
16
- } else {
17
- const nameEqual = args.find(a => a.startsWith("--name="));
18
- if (nameEqual) {
19
- rawTemplateName = nameEqual.split("=")[1];
20
- }
21
- }
22
-
23
- // Check for legacy alias warning
24
- if (process.env.FORGEWP_LEGACY_ALIAS === "1") {
25
- console.log(pc.yellow(`\n⚠️ Legacy Command Warning: "make:component" is deprecated.`));
26
- console.log(` Please use the new modern naming: ${pc.cyan("pnpm forgewp make:template <Name>")}\n`);
27
- }
28
-
29
- if (!rawTemplateName) {
30
- console.error(pc.red("\n❌ Error: Please specify a template name."));
31
- console.log(pc.cyan(" Example: pnpm forgewp make:template PortfolioTemplate --postType=portfolio"));
32
- console.log(pc.cyan(" Or: pnpm forgewp make:template --name PortfolioTemplate --postType=portfolio\n"));
33
- process.exit(1);
34
- }
35
-
36
- // PascalCase formatting
37
- const cleanName = rawTemplateName.replace(/[^a-zA-Z0-9_-]/g, "");
38
- const pascalCase = cleanName
39
- .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => word.toUpperCase())
40
- .replace(/[^a-zA-Z0-9]/g, "");
41
-
42
- if (!pascalCase) {
43
- console.error(pc.red("\n❌ Error: Invalid template name.\n"));
44
- process.exit(1);
45
- }
46
-
47
- // Parse postType
48
- let postType = "post";
49
- const postTypeArg = args.find(a => a.startsWith("--postType=") || a.startsWith("--post-type="));
50
- if (postTypeArg) {
51
- postType = postTypeArg.split("=")[1];
52
- } else {
53
- const postTypeIndex = args.findIndex(a => a === "--postType" || a === "--post-type");
54
- if (postTypeIndex !== -1 && args[postTypeIndex + 1]) {
55
- postType = args[postTypeIndex + 1];
56
- }
57
- }
58
-
59
- const projectRoot = process.cwd();
60
- const mockDataPath = path.join(projectRoot, "cms", "mock-data.json");
61
-
62
- if (!existsSync(path.join(projectRoot, "src"))) {
63
- console.error(pc.red(`\n❌ Error: "src" folder not found. Are you in your theme's root directory?\n`));
64
- process.exit(1);
65
- }
66
-
67
- // Try to load custom fields from mock-data.json for this post type
68
- let customFields = [];
69
- let automaticallySeeded = false;
70
-
71
- if (existsSync(mockDataPath)) {
72
- try {
73
- const mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
74
- if (!mockData[postType]) {
75
- // SMART ACTION: Automatically register and seed postType records in the JSON database
76
- mockData[postType] = [
77
- {
78
- id: 1,
79
- title: `Sample ${postType.charAt(0).toUpperCase() + postType.slice(1)} Item 1`,
80
- excerpt: `This is a custom ${postType} post seeded dynamically via ForgeWP CLI.`,
81
- content: `<p>Welcome to your new custom <strong>${postType}</strong> post template! Edit this in cms/mock-data.json.</p>`,
82
- date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
83
- author: "ForgeWP CLI",
84
- featuredImage: `https://picsum.photos/seed/${postType}1/1200/630`,
85
- customFields: {
86
- client_name: "Mock Enterprise",
87
- project_budget: "$30,000",
88
- }
89
- },
90
- {
91
- id: 2,
92
- title: `Sample ${postType.charAt(0).toUpperCase() + postType.slice(1)} Item 2`,
93
- excerpt: `This is another custom ${postType} post seeded dynamically via ForgeWP CLI.`,
94
- content: `<p>This is the second custom post for the ${postType} post type.</p>`,
95
- date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
96
- author: "ForgeWP CLI",
97
- featuredImage: `https://picsum.photos/seed/${postType}2/1200/630`,
98
- customFields: {
99
- client_name: "Mock Organization",
100
- project_budget: "$55,000",
101
- }
102
- }
103
- ];
104
- // Save updated JSON
105
- writeFileSync(mockDataPath, JSON.stringify(mockData, null, 2), "utf8");
106
- automaticallySeeded = true;
107
- }
108
-
109
- const records = mockData[postType] || [];
110
- if (records.length > 0 && records[0].customFields) {
111
- customFields = Object.keys(records[0].customFields);
112
- }
113
- } catch (err) {
114
- // Ignore and fallback
115
- }
116
- }
117
-
118
- // Load configuration and invoke adapter
119
- let frameworkAdapter = "react";
120
- try {
121
- const config = await loadConfig(projectRoot);
122
- frameworkAdapter = config.frameworkAdapter || "react";
123
- } catch (err) {
124
- // Use default
125
- }
126
-
127
- try {
128
- const adapterModule = await loadFrameworkAdapter(frameworkAdapter);
129
- const adapter = adapterModule.default || adapterModule;
130
- if (typeof adapter.onMakeTemplate === "function") {
131
- await adapter.onMakeTemplate(projectRoot, {
132
- pascalCase,
133
- postType,
134
- customFields,
135
- automaticallySeeded,
136
- pc
137
- });
138
- } else {
139
- console.error(pc.red(`\n❌ Error: Framework adapter "${frameworkAdapter}" does not support making custom templates.`));
140
- process.exit(1);
141
- }
142
- } catch (err) {
143
- console.error(pc.red(`\n❌ Failed to execute make:template: ${err.message}`));
144
- process.exit(1);
145
- }
@@ -1,552 +0,0 @@
1
- import {
2
- existsSync,
3
- mkdirSync,
4
- readFileSync,
5
- readdirSync,
6
- statSync,
7
- writeFileSync,
8
- } from 'node:fs';
9
- import path from 'node:path';
10
-
11
- function parseAttributes(attrStr) {
12
- const attrs = {};
13
- const regex = /([a-zA-Z0-9_-]+)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|(?:\{([\s\S]*?)\}))|(?=\s|$))/gi;
14
- let match;
15
- while ((match = regex.exec(attrStr)) !== null) {
16
- const key = match[1];
17
- const val = match[2] || match[3] || match[4] || true;
18
- attrs[key] = val;
19
- }
20
- return attrs;
21
- }
22
-
23
- function parseJsxToAst(jsx) {
24
- const tokens = [];
25
- let index = 0;
26
-
27
- while (index < jsx.length) {
28
- const char = jsx[index];
29
-
30
- if (char === '<') {
31
- let tagEnd = jsx.indexOf('>', index);
32
- if (tagEnd === -1) break;
33
-
34
- let tagStr = jsx.substring(index, tagEnd + 1);
35
- const isClosing = tagStr.startsWith('</');
36
- const isSelfClosing = tagStr.endsWith('/>');
37
-
38
- const tagNameMatch = tagStr.match(/<\/?([a-zA-Z0-9_-]+)/);
39
- const tagName = tagNameMatch ? tagNameMatch[1] : '';
40
-
41
- tokens.push({
42
- type: 'tag',
43
- name: tagName,
44
- raw: tagStr,
45
- isClosing,
46
- isSelfClosing
47
- });
48
-
49
- index = tagEnd + 1;
50
- } else {
51
- let nextTag = jsx.indexOf('<', index);
52
- let text = nextTag === -1 ? jsx.substring(index) : jsx.substring(index, nextTag);
53
-
54
- if (text.trim()) {
55
- tokens.push({
56
- type: 'text',
57
- value: text
58
- });
59
- }
60
-
61
- index = nextTag === -1 ? jsx.length : nextTag;
62
- }
63
- }
64
-
65
- const root = { type: 'root', children: [] };
66
- const stack = [root];
67
-
68
- for (const token of tokens) {
69
- if (token.type === 'tag') {
70
- if (token.isClosing) {
71
- if (stack.length > 1) {
72
- stack.pop();
73
- }
74
- } else {
75
- const node = {
76
- type: 'element',
77
- name: token.name,
78
- attributes: parseAttributes(token.raw.substring(token.name.length + 1, token.raw.length - (token.isSelfClosing ? 2 : 1))),
79
- children: []
80
- };
81
-
82
- stack[stack.length - 1].children.push(node);
83
-
84
- if (!token.isSelfClosing && token.name !== 'img' && token.name !== 'input' && token.name !== 'br' && token.name !== 'hr') {
85
- stack.push(node);
86
- }
87
- }
88
- } else {
89
- stack[stack.length - 1].children.push({
90
- type: 'text',
91
- value: token.value
92
- });
93
- }
94
- }
95
-
96
- return root;
97
- }
98
-
99
- function generateReactCreateElement(node) {
100
- if (!node) return 'null';
101
-
102
- if (node.type === 'root') {
103
- if (node.children.length === 1) {
104
- return generateReactCreateElement(node.children[0]);
105
- }
106
- return `[${node.children.map(generateReactCreateElement).join(', ')}]`;
107
- }
108
-
109
- if (node.type === 'text') {
110
- const val = node.value.trim();
111
- if (val.startsWith('{') && val.endsWith('}')) {
112
- return val.slice(1, -1).trim();
113
- }
114
- return JSON.stringify(val);
115
- }
116
-
117
- if (node.type === 'element') {
118
- if (node.name === 'WpEditable') {
119
- const tag = String(node.attributes.tagName || 'div').replace(/['"]/g, '').trim();
120
- const valStr = String(node.attributes.value || '').trim();
121
-
122
- let varName = 'value';
123
- const varMatch = valStr.match(/(?:attributes|props)?\.?([a-zA-Z0-9_-]+)$/);
124
- if (varMatch) {
125
- varName = varMatch[1];
126
- }
127
-
128
- const className = node.attributes.className
129
- ? (node.attributes.className.startsWith('{')
130
- ? node.attributes.className.slice(1, -1)
131
- : JSON.stringify(node.attributes.className))
132
- : '""';
133
-
134
- return `createElement(wp.blockEditor.RichText, {
135
- tagName: ${JSON.stringify(tag)},
136
- value: attributes.${varName} || '',
137
- onChange: function(val) { setAttributes({ ${varName}: val }); },
138
- className: ${className}
139
- })`;
140
- }
141
-
142
- const props = {};
143
- for (const [key, val] of Object.entries(node.attributes)) {
144
- const propKey = key === 'className' ? 'className' : key;
145
- if (typeof val === 'string' && val.startsWith('{') && val.endsWith('}')) {
146
- props[propKey] = val.slice(1, -1).trim();
147
- } else {
148
- props[propKey] = JSON.stringify(val);
149
- }
150
- }
151
-
152
- const propsStr = Object.keys(props).length > 0
153
- ? `{ ${Object.entries(props).map(([k, v]) => `${k}: ${v}`).join(', ')} }`
154
- : 'null';
155
-
156
- const childrenStr = node.children.map(generateReactCreateElement).filter(Boolean).join(', ');
157
-
158
- return `createElement(${JSON.stringify(node.name)}, ${propsStr}${childrenStr ? `, ${childrenStr}` : ''})`;
159
- }
160
- return 'null';
161
- }
162
-
163
- function parseDefineBlock(code, blockSlug) {
164
- const startIndex = code.indexOf('defineBlock(');
165
- if (startIndex === -1) return null;
166
-
167
- let depth = 1;
168
- let i = startIndex + 'defineBlock('.length;
169
- let blockContent = '';
170
-
171
- while (i < code.length && depth > 0) {
172
- const char = code[i];
173
- if (char === '(') depth++;
174
- else if (char === ')') depth--;
175
-
176
- if (depth > 0) {
177
- blockContent += char;
178
- }
179
- i++;
180
- }
181
-
182
- let cleanBlockContent = blockContent;
183
-
184
- cleanBlockContent = cleanBlockContent.replace(
185
- /edit\s*:\s*([\s\S]*?)(?=,\s*(?:save|name|title|category|icon|attributes)\s*:|\s*\}$)/,
186
- 'edit: null'
187
- );
188
- cleanBlockContent = cleanBlockContent.replace(
189
- /save\s*:\s*([\s\S]*?)(?=,\s*(?:edit|name|title|category|icon|attributes)\s*:|\s*\}$)/,
190
- 'save: null'
191
- );
192
-
193
- try {
194
- const evalFn = new Function(`return ${cleanBlockContent};`);
195
- return evalFn();
196
- } catch (e) {
197
- console.warn(`[Gutenberg Block Compiler] parseDefineBlock eval failed:`, e.message);
198
-
199
- const nameMatch = blockContent.match(/name\s*:\s*["']([^"']+)["']/);
200
- const titleMatch = blockContent.match(/title\s*:\s*["']([^"']+)["']/);
201
- const categoryMatch = blockContent.match(/category\s*:\s*["']([^"']+)["']/);
202
- const iconMatch = blockContent.match(/icon\s*:\s*["']([^"']+)["']/);
203
-
204
- let attributes = {};
205
- const attrMatch = blockContent.match(/attributes\s*:\s*(\{[\s\S]*?\})(?:\s*,\s*(?:edit|save)|\s*\})/);
206
- if (attrMatch) {
207
- try {
208
- const attrEval = new Function(`return ${attrMatch[1]};`);
209
- attributes = attrEval();
210
- } catch {}
211
- }
212
-
213
- return {
214
- name: nameMatch ? nameMatch[1] : blockSlug,
215
- title: titleMatch ? titleMatch[1] : blockSlug,
216
- category: categoryMatch ? categoryMatch[1] : 'design',
217
- icon: iconMatch ? iconMatch[1] : 'info',
218
- attributes
219
- };
220
- }
221
- }
222
-
223
- function extractJsx(code, propertyName) {
224
- const propIndex = code.indexOf(`${propertyName}:`);
225
- if (propIndex === -1) return null;
226
-
227
- const subCode = code.substring(propIndex);
228
- const returnIndex = subCode.indexOf('return (');
229
- if (returnIndex !== -1) {
230
- let depth = 1;
231
- let j = returnIndex + 'return ('.length;
232
- let jsxContent = '';
233
- while (j < subCode.length && depth > 0) {
234
- const c = subCode[j];
235
- if (c === '(') depth++;
236
- else if (c === ')') depth--;
237
-
238
- if (depth > 0) {
239
- jsxContent += c;
240
- }
241
- j++;
242
- }
243
- return jsxContent.trim();
244
- }
245
-
246
- const returnSingleIndex = subCode.indexOf('return ');
247
- if (returnSingleIndex !== -1) {
248
- const afterReturn = subCode.substring(returnSingleIndex + 'return '.length).trim();
249
- if (afterReturn.startsWith('<')) {
250
- const match = afterReturn.match(/^(<[\s\S]*?>)(?:\s*[,;\}]|\s*$)/);
251
- if (match) {
252
- return match[1].trim();
253
- }
254
- }
255
- }
256
-
257
- const arrowIndex = subCode.indexOf('=>');
258
- if (arrowIndex !== -1 && arrowIndex < 80) {
259
- const afterArrow = subCode.substring(arrowIndex + 2).trim();
260
- if (afterArrow.startsWith('(')) {
261
- let depth = 1;
262
- let j = 1;
263
- let jsxContent = '';
264
- while (j < afterArrow.length && depth > 0) {
265
- const c = afterArrow[j];
266
- if (c === '(') depth++;
267
- else if (c === ')') depth--;
268
- if (depth > 0) jsxContent += c;
269
- j++;
270
- }
271
- return jsxContent.trim();
272
- } else if (afterArrow.startsWith('<')) {
273
- const match = afterArrow.match(/^(<[\s\S]*?>)(?:\s*[,;\}]|\s*$)/);
274
- if (match) {
275
- return match[1].trim();
276
- }
277
- }
278
- }
279
-
280
- return null;
281
- }
282
-
283
- function parenthesizeTernaryExpression(expr) {
284
- const questionCount = (expr.match(/\?/g) || []).length;
285
- if (questionCount <= 1) return expr;
286
-
287
- let depth = 0;
288
- let firstQuestionIdx = -1;
289
- let firstColonIdx = -1;
290
-
291
- for (let i = 0; i < expr.length; i++) {
292
- const char = expr[i];
293
- if (char === '(' || char === '{' || char === '[') depth++;
294
- else if (char === ')' || char === '}' || char === ']') depth--;
295
- else if (depth === 0) {
296
- if (char === '?' && firstQuestionIdx === -1) {
297
- firstQuestionIdx = i;
298
- } else if (char === ':' && firstQuestionIdx !== -1 && firstColonIdx === -1) {
299
- firstColonIdx = i;
300
- break;
301
- }
302
- }
303
- }
304
-
305
- if (firstQuestionIdx === -1 || firstColonIdx === -1) {
306
- return expr;
307
- }
308
-
309
- const cond = expr.substring(0, firstQuestionIdx).trim();
310
- const truthy = expr.substring(firstQuestionIdx + 1, firstColonIdx).trim();
311
- const falsy = expr.substring(firstColonIdx + 1).trim();
312
-
313
- const newTruthy = parenthesizeTernaryExpression(truthy);
314
- const newFalsy = parenthesizeTernaryExpression(falsy);
315
-
316
- const wrapTruthy = (truthy.includes('?') && !truthy.startsWith('(')) ? `(${newTruthy})` : newTruthy;
317
- const wrapFalsy = (falsy.includes('?') && !falsy.startsWith('(')) ? `(${newFalsy})` : newFalsy;
318
-
319
- return `${cond} ? ${wrapTruthy} : ${wrapFalsy}`;
320
- }
321
-
322
- function translateJsExpressionToPhp(jsExpr) {
323
- const phpExpr = jsExpr
324
- .replace(/(?:attributes|props)\.([a-zA-Z0-9_-]+)/g, "$attributes['$1']")
325
- .replace(/\b([a-zA-Z0-9_-]+)\b/g, (name) => {
326
- return name;
327
- });
328
- return parenthesizeTernaryExpression(phpExpr);
329
- }
330
-
331
- /**
332
- * Scans the `src/blocks/` folder, parses block settings and JSX content,
333
- * and compiles them into official, dynamic WordPress blocks.
334
- *
335
- * @param {string} themeRoot
336
- * @param {string} outDir
337
- * @returns {string[]} Compiled block slugs
338
- */
339
- export function compileBlocks(themeRoot, outDir) {
340
- const blocksDir = path.join(themeRoot, 'src', 'blocks');
341
- const blockSlugs = [];
342
-
343
- if (!existsSync(blocksDir)) {
344
- return blockSlugs;
345
- }
346
-
347
- const entries = readdirSync(blocksDir);
348
- for (const entry of entries) {
349
- const entryPath = path.join(blocksDir, entry);
350
- let blockFile = '';
351
- let blockSlug = '';
352
-
353
- if (statSync(entryPath).isDirectory()) {
354
- const indexPath = path.join(entryPath, 'index.tsx');
355
- if (existsSync(indexPath)) {
356
- blockFile = indexPath;
357
- blockSlug = entry
358
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
359
- .toLowerCase()
360
- .replace(/[^a-z0-9]+/g, '-');
361
- }
362
- } else if (entry.endsWith('.tsx') || entry.endsWith('.jsx')) {
363
- blockFile = entryPath;
364
- blockSlug = entry
365
- .replace(/\.(tsx|jsx)$/, '')
366
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
367
- .toLowerCase()
368
- .replace(/[^a-z0-9]+/g, '-');
369
- }
370
-
371
- if (blockFile) {
372
- try {
373
- const code = readFileSync(blockFile, 'utf8');
374
-
375
- const settingsMatch = code.match(
376
- /export\s+const\s+settings\s*=\s*(\{[\s\S]*?\});/,
377
- );
378
- let settings = {
379
- apiVersion: 3,
380
- name: `forgewp/${blockSlug}`,
381
- title: blockSlug
382
- .split('-')
383
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
384
- .join(' '),
385
- category: 'design',
386
- icon: 'admin-generic',
387
- attributes: {},
388
- render: 'file:./render.php',
389
- };
390
-
391
- let parsedSettings = null;
392
- if (code.includes('defineBlock(')) {
393
- parsedSettings = parseDefineBlock(code, blockSlug);
394
- } else if (settingsMatch) {
395
- try {
396
- const evalFn = new Function(`return ${settingsMatch[1]};`);
397
- parsedSettings = evalFn();
398
- } catch (e) {
399
- console.warn(
400
- `[Gutenberg Block Compiler] Error parsing legacy settings for ${blockSlug}:`,
401
- e.message,
402
- );
403
- }
404
- }
405
-
406
- if (parsedSettings) {
407
- settings = { ...settings, ...parsedSettings };
408
- settings.name = settings.name ? (settings.name.includes('/') ? settings.name : `forgewp/${settings.name}`) : `forgewp/${blockSlug}`;
409
- settings.apiVersion = 3;
410
- settings.render = 'file:./render.php';
411
- }
412
-
413
- // Extract JSX from save first, then edit as fallback
414
- let jsx = '';
415
- if (code.includes('save:')) {
416
- jsx = extractJsx(code, 'save');
417
- }
418
- if (!jsx && code.includes('edit:')) {
419
- jsx = extractJsx(code, 'edit');
420
- }
421
-
422
- if (!jsx) {
423
- const returnMatch = code.match(/return\s*\(\s*(<[\s\S]*?>)\s*\)/);
424
- if (returnMatch) {
425
- jsx = returnMatch[1];
426
- } else {
427
- const returnMatchSingle = code.match(/return\s+(<[\s\S]*?>);/);
428
- if (returnMatchSingle) {
429
- jsx = returnMatchSingle[1];
430
- }
431
- }
432
- }
433
-
434
- if (!jsx) {
435
- console.warn(
436
- `[Gutenberg Block Compiler] Skipping block ${blockSlug}: No returning JSX element found.`,
437
- );
438
- continue;
439
- }
440
-
441
- // Extract custom edit JSX for block-canvas high-fidelity controls using AST parser
442
- let editJsx = '';
443
- if (code.includes('edit:')) {
444
- editJsx = extractJsx(code, 'edit');
445
- }
446
- if (editJsx) {
447
- try {
448
- const ast = parseJsxToAst(editJsx);
449
- const customEditJsx = generateReactCreateElement(ast);
450
- settings.customEditJsx = customEditJsx;
451
- } catch (e) {
452
- console.warn(`[Gutenberg Block Compiler] Failed to parse custom edit JSX for ${blockSlug}:`, e.message);
453
- }
454
- }
455
-
456
- let phpMarkup = jsx;
457
-
458
- // Transpile <WpEditable> into standard JSX element so subsequent regexes can process it
459
- phpMarkup = phpMarkup.replace(
460
- /<WpEditable\s+([^>]*?)(?:\/>|>([\s\S]*?)<\/WpEditable>)/g,
461
- (match, attrsStr, children) => {
462
- const getAttr = (name) => {
463
- const regex = new RegExp(
464
- `${name}=(?:"([^"]*)"|'([^']*)'|\\{\\s*(?:attributes\\.|props\\.)?([a-zA-Z0-9_-]+)\\s*\\})`
465
- );
466
- const m = attrsStr.match(regex);
467
- return m ? m[1] || m[2] || m[3] || '' : '';
468
- };
469
-
470
- const tag = getAttr('tagName') || 'div';
471
- const valueVar = getAttr('value');
472
-
473
- let cleanAttrs = attrsStr
474
- .replace(/tagName=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
475
- .replace(/value=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
476
- .replace(/onChange=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
477
- .trim();
478
-
479
- if (cleanAttrs) cleanAttrs = ' ' + cleanAttrs;
480
-
481
- const content = valueVar ? `{attributes.${valueVar}}` : (children || '');
482
-
483
- return `<${tag}${cleanAttrs}>${content}</${tag}>`;
484
- }
485
- );
486
-
487
- // className="..." -> class="..."
488
- phpMarkup = phpMarkup.replace(/className=/g, 'class=');
489
-
490
- // Transpile ES6 template literal conditional classes class={`...`}
491
- phpMarkup = phpMarkup.replace(/class=\{\`([\s\S]*?)\`\}/g, (match, templateLiteralContent) => {
492
- const processed = templateLiteralContent.replace(/\$\{\s*([\s\S]*?)\s*\}/g, (m, jsExpr) => {
493
- const phpExpr = translateJsExpressionToPhp(jsExpr);
494
- return `<?php echo esc_attr( ${phpExpr} ); ?>`;
495
- });
496
- return `class="${processed}"`;
497
- });
498
-
499
- // src={image} or src={attributes.image}
500
- phpMarkup = phpMarkup.replace(
501
- /(src|href|alt|title)=\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/gi,
502
- (match, attr, varName) => {
503
- const escFunc =
504
- attr === 'href' || attr === 'src' ? 'esc_url' : 'esc_attr';
505
- return `${attr}="<?php echo ${escFunc}( $attributes['${varName}'] ?? '' ); ?>"`;
506
- },
507
- );
508
-
509
- // {title} or {props.title}
510
- phpMarkup = phpMarkup.replace(
511
- /\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/g,
512
- (match, varName) => {
513
- return `<?php echo esc_html( $attributes['${varName}'] ?? '' ); ?>`;
514
- },
515
- );
516
-
517
- const renderPhpContent = `<?php
518
- /**
519
- * Gutenberg dynamic block template — ${settings.title}
520
- * Autogenerated by ForgeWP Theme Compiler. Do not modify manually.
521
- */
522
- ?>
523
- ${phpMarkup}
524
- `;
525
-
526
- const blockOutDir = path.join(outDir, 'blocks', blockSlug);
527
- mkdirSync(blockOutDir, { recursive: true });
528
-
529
- // Write block.json and render.php
530
- writeFileSync(
531
- path.join(blockOutDir, 'block.json'),
532
- JSON.stringify(settings, null, 2),
533
- 'utf8',
534
- );
535
- writeFileSync(
536
- path.join(blockOutDir, 'render.php'),
537
- renderPhpContent,
538
- 'utf8',
539
- );
540
-
541
- blockSlugs.push(settings);
542
- } catch (e) {
543
- console.error(
544
- `[Gutenberg Block Compiler] Failed to compile block ${blockSlug}:`,
545
- e.message,
546
- );
547
- }
548
- }
549
- }
550
-
551
- return blockSlugs;
552
- }