@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
@@ -1,616 +1,1410 @@
1
- import { existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";
2
- import path from "node:path";
3
- import { pathToFileURL, fileURLToPath } from "node:url";
4
- import { createRequire, register } from "node:module";
5
-
6
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
- register(pathToFileURL(path.join(__dirname, "asset-loader.js")).href);
8
-
9
- const themeRoot = process.argv[2];
10
-
11
- if (!themeRoot) {
12
- console.error("Usage: render-theme.mts <theme-root>");
13
- process.exit(1);
14
- }
15
-
16
- // Use the theme's own node_modules for ALL packages (React 19)
17
- const require = createRequire(path.join(themeRoot, "package.json"));
18
- const React = require("react");
19
- globalThis.React = React; // Polyfill for classic JSX transform in Node.js
20
-
21
- // Resilient browser globals polyfills for Node SSR/compile-time rendering
22
- if (typeof globalThis.window === "undefined") {
23
- const mockLocation = {
24
- pathname: "/",
25
- search: "",
26
- hash: "",
27
- href: "http://localhost/",
28
- origin: "http://localhost",
29
- assign: () => {},
30
- replace: () => {},
31
- reload: () => {}
32
- };
33
- globalThis.window = {
34
- location: mockLocation,
35
- navigator: { userAgent: "Node" },
36
- addEventListener: () => {},
37
- removeEventListener: () => {},
38
- dispatchEvent: () => false,
39
- _forgeWpCompileTime: true,
40
- } as any;
41
- globalThis.location = mockLocation as any;
42
- globalThis.document = {
43
- addEventListener: () => {},
44
- removeEventListener: () => {},
45
- querySelector: () => null,
46
- querySelectorAll: () => [],
47
- } as any;
48
- globalThis.SVGElement = class SVGElement {} as any;
49
- }
50
-
51
- const { renderToStaticMarkup } = require("react-dom/server");
52
-
53
- const appUrl = pathToFileURL(path.join(themeRoot, "src", "app", "page.tsx")).href;
54
- const layoutUrl = pathToFileURL(path.join(themeRoot, "src", "app", "layout.tsx")).href;
55
- const layoutPath = path.join(themeRoot, "src", "app", "layout.tsx");
56
-
57
- // ── Load pages ────────────────────────────────────────────────────────────────
58
- let App: any;
59
- try {
60
- const module = await import(appUrl);
61
- App = module.default;
62
- if (!App) {
63
- throw new Error("Page component lacks a default export.");
64
- }
65
- } catch (err: any) {
66
- console.error(`\n[ForgeWP Compiler Error] Failed to load the main Page component (src/app/page.tsx).`);
67
- console.error(`Check for syntax errors, incorrect imports, or invalid references inside your page component.`);
68
- console.error(`Error details: ${err.stack || err.message || err}\n`);
69
- process.exit(1);
70
- }
71
-
72
- let RootLayout: (props: any) => any = ({ children }: any) =>
73
- React.createElement(React.Fragment, null, children);
74
- if (existsSync(layoutPath)) {
75
- try {
76
- const module = await import(layoutUrl);
77
- RootLayout = module.default;
78
- if (!RootLayout) {
79
- throw new Error("Root layout component lacks a default export.");
80
- }
81
- } catch (err: any) {
82
- console.error(`\n[ForgeWP Compiler Error] Failed to load the Root Layout component (src/app/layout.tsx).`);
83
- console.error(`Check for syntax errors, incorrect imports, or invalid references inside your layout component.`);
84
- console.error(`Error details: ${err.stack || err.message || err}\n`);
85
- process.exit(1);
86
- }
87
- } else {
88
- console.warn("RootLayout (src/app/layout.tsx) not found, using Fragment fallback");
89
- }
90
-
91
- // ── Render a page inside RootLayout ──────────────────────────────────────────
92
- function renderPage(PageComponent: any): string {
93
- try {
94
- return renderToStaticMarkup(
95
- React.createElement(RootLayout, null, React.createElement(PageComponent))
96
- );
97
- } catch (err: any) {
98
- console.error(`\n[ForgeWP Compiler Error] Server-Side Rendering (SSR) failed for Page Component.`);
99
- console.error(`This typically happens if you use browser-only globals (like 'window', 'document', 'localStorage') at render-time, or if a component throws during execution.`);
100
- console.error(`Ensure browser-specific logic is placed inside useEffect() or is executed only in the client.`);
101
- console.error(`Error details: ${err.stack || err.message || err}\n`);
102
- process.exit(1);
103
- }
104
- }
105
-
106
- let textDomain = "forgewp";
107
- let themeConfig: any = {};
108
- try {
109
- const wpConfigPath = path.join(themeRoot, "wp.config.ts");
110
- if (existsSync(wpConfigPath)) {
111
- const wpConfigUrl = pathToFileURL(wpConfigPath).href;
112
- const configModule = await import(wpConfigUrl);
113
- themeConfig = configModule.default || configModule;
114
- if (themeConfig.textDomain) {
115
- textDomain = themeConfig.textDomain;
116
- }
117
- }
118
- } catch (e) {
119
- // fallback if import fails
120
- try {
121
- const wpConfigPath = path.join(themeRoot, "wp.config.ts");
122
- if (existsSync(wpConfigPath)) {
123
- const configContent = readFileSync(wpConfigPath, "utf8");
124
- const domainMatch = configContent.match(/textDomain\s*:\s*['"]([^'"]+)['"]/);
125
- if (domainMatch) {
126
- textDomain = domainMatch[1];
127
- }
128
- }
129
- } catch (e2) {}
130
- }
131
-
132
- function translateExpressionToPhp(expression: string, propName: string): string {
133
- expression = expression.trim();
134
-
135
- // 1. Check for useWpTitle()
136
- if (expression.includes("useWpTitle(")) {
137
- return `<?php echo esc_attr(get_the_title()); ?>`;
138
- }
139
- // 2. Check for useWpExcerpt()
140
- if (expression.includes("useWpExcerpt(")) {
141
- return `<?php echo esc_attr(get_the_excerpt()); ?>`;
142
- }
143
- // 3. Check for useWpFeaturedImage()
144
- if (expression.includes("useWpFeaturedImage(")) {
145
- return `<?php echo esc_url(get_the_post_thumbnail_url(get_the_ID(), 'full')); ?>`;
146
- }
147
- // 4. Check for useWpPermalink()
148
- if (expression.includes("useWpPermalink(")) {
149
- return `<?php echo esc_url(get_permalink()); ?>`;
150
- }
151
- // 5. Check for useWpCustomField / useWpField / useWpMeta
152
- const metaMatch = expression.match(/useWp(?:CustomField|Field|Meta)\s*\(\s*['"]([^'"]+)['"]/);
153
- if (metaMatch) {
154
- const key = metaMatch[1];
155
- const isUrl = propName === "canonical" || propName === "ogImage" || key.includes("url") || key.includes("image") || key.includes("website");
156
- const escFn = isUrl ? "esc_url" : "esc_attr";
157
- return `<?php echo ${escFn}(get_post_meta(get_the_ID(), '${key}', true)); ?>`;
158
- }
159
- // 6. Check for useWpAuthor()
160
- if (expression.includes("useWpAuthor(")) {
161
- return `<?php echo esc_attr(get_the_author()); ?>`;
162
- }
163
- // 7. Check for useWpDate()
164
- if (expression.includes("useWpDate(")) {
165
- return `<?php echo esc_attr(get_the_date()); ?>`;
166
- }
167
- // 8. Check for useWpOption()
168
- const optionMatch = expression.match(/useWpOption\s*\(\s*['"]([^'"]+)['"]/);
169
- if (optionMatch) {
170
- const key = optionMatch[1];
171
- return `<?php echo esc_attr(get_option('${key}', '')); ?>`;
172
- }
173
- // 9. Check for useWpThemeMod()
174
- const themeModMatch = expression.match(/useWpThemeMod\s*\(\s*['"]([^'"]+)['"]/);
175
- if (themeModMatch) {
176
- const key = themeModMatch[1];
177
- return `<?php echo esc_attr(get_theme_mod('${key}', '')); ?>`;
178
- }
179
- // 10. Check for useWpPageLink
180
- const pageLinkMatch = expression.match(/useWpPageLink\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/);
181
- if (pageLinkMatch) {
182
- const templateName = pageLinkMatch[1];
183
- const fallbackUrl = pageLinkMatch[2];
184
- return `<?php $matched = get_pages(array('meta_key' => '_wp_page_template', 'meta_value' => 'page-${templateName.replace(/-page$/, "")}.php', 'number' => 1)); echo esc_url(!empty($matched) ? get_permalink($matched[0]->ID) : home_url('${fallbackUrl}')); ?>`;
185
- }
186
- // 11. Check for internationalization __()
187
- const i18nMatch = expression.match(/__\s*\(\s*['"]([^'"]+)['"]/);
188
- if (i18nMatch) {
189
- const str = i18nMatch[1];
190
- return `<?php echo esc_attr(__('${str}', '${textDomain}')); ?>`;
191
- }
192
- // 12. Check for literal string in quotes
193
- const literalMatch = expression.match(/^\s*['"]([^'"]+)['"]\s*$/);
194
- if (literalMatch) {
195
- return literalMatch[1];
196
- }
197
- return "";
198
- }
199
-
200
- function extractBalancedJsxExpression(src: string, propName: string): string {
201
- const marker = `${propName}={`;
202
- const index = src.indexOf(marker);
203
- if (index === -1) return "";
204
- let braces = 1;
205
- let start = index + marker.length;
206
- let i = start;
207
- while (braces > 0 && i < src.length) {
208
- if (src[i] === "{") braces++;
209
- else if (src[i] === "}") braces--;
210
- i++;
211
- }
212
- return src.slice(start, i - 1).trim();
213
- }
214
-
215
- function compileSchemaObject(schemaExpr: string, fileSrc: string): string {
216
- return schemaExpr.replace(/("[\w@]+"|[\w@]+)\s*:\s*([^,\n}]+)/g, (match, key, valStr) => {
217
- let val = valStr.trim();
218
- if (/^["']([^"']*)["']$/.test(val)) {
219
- return `${key}: ${val}`;
220
- }
221
- if (/^(true|false|[0-9.]+)$/i.test(val)) {
222
- return `${key}: ${val}`;
223
- }
224
- let resolved = val;
225
- if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(val)) {
226
- const declRegex = new RegExp(`(?:const|let|var)\\s+${val}\\s*=\\s*([^;\\n]+)`);
227
- const declMatch = fileSrc.match(declRegex);
228
- if (declMatch) {
229
- resolved = declMatch[1].trim();
230
- }
231
- }
232
- const phpVal = translateExpressionToPhp(resolved, "");
233
- if (phpVal) {
234
- return `${key}: "${phpVal}"`;
235
- }
236
- return `${key}: ${val}`;
237
- });
238
- }
239
-
240
- // ── SEO extraction from source files (React 19 SSR-safe) ─────────────────────
241
- // react-helmet-async v3 disabled server-side context for React 19 —
242
- // HelmetProvider is a Fragment at SSR time so helmetContext.helmet is never set.
243
- // Instead we parse <SEO .../> props directly from the source TSX file.
244
-
245
- function extractSeoPropsFromSource(filePath: string): Record<string, string> {
246
- if (!filePath || !existsSync(filePath)) return {};
247
-
248
- let src = readFileSync(filePath, "utf8");
249
-
250
- // Strip JSX block comments so we don't match <SEO /> mentions inside them
251
- src = src.replace(/\{\/\*[\s\S]*?\*\/\}/g, "");
252
-
253
- // Find the first <SEO ... /> or <WpHead ... /> (multiline, s flag)
254
- const seoMatch = src.match(/<(?:SEO|WpHead)\b([^>]*?)(?:\/>|>)/s);
255
- if (!seoMatch) {
256
- // If not found, let's look for local imports to follow
257
- const importRegex = /import\s+.*?\s+from\s+['"](\.\.?\/[^'"]+)['"]/g;
258
- let match;
259
- const dir = path.dirname(filePath);
260
- while ((match = importRegex.exec(src)) !== null) {
261
- const relativePath = match[1];
262
- // Try resolving with common extensions
263
- for (const ext of [".tsx", ".ts", "/index.tsx", "/index.ts"]) {
264
- const resolvedPath = path.resolve(dir, relativePath + ext);
265
- if (existsSync(resolvedPath)) {
266
- const importedProps = extractSeoPropsFromSource(resolvedPath);
267
- if (Object.keys(importedProps).length > 0) {
268
- return importedProps; // Return the first matching props we find
269
- }
270
- }
271
- }
272
- }
273
- return {};
274
- }
275
-
276
- const attribsStr = seoMatch[1];
277
- const props: Record<string, string> = {};
278
-
279
- // Double-quoted values: prop="value with & and spaces"
280
- let m: RegExpExecArray | null;
281
- const dqPattern = /(\w+)\s*=\s*"([^"]*)"/g;
282
- while ((m = dqPattern.exec(attribsStr)) !== null) props[m[1]] = m[2];
283
-
284
- // Single-quoted values: prop='value'
285
- const sqPattern = /(\w+)\s*=\s*'([^']*)'/g;
286
- while ((m = sqPattern.exec(attribsStr)) !== null) if (!props[m[1]]) props[m[1]] = m[2];
287
-
288
- // JSX string expressions: prop={"value"} or prop={'value'}
289
- const jsxPattern = /(\w+)\s*=\s*\{["']([^"']*)["']\}/g;
290
- while ((m = jsxPattern.exec(attribsStr)) !== null) if (!props[m[1]]) props[m[1]] = m[2];
291
-
292
- // JSX brace expressions: prop={expression}
293
- const exprPattern = /(\w+)\s*=\s*\{([^}]*)\}/g;
294
- while ((m = exprPattern.exec(attribsStr)) !== null) {
295
- const propName = m[1];
296
- const expression = m[2].trim();
297
- if (!props[propName]) {
298
- let resolvedExpression = expression;
299
-
300
- // Trace variable name back to declaration if it is a simple identifier
301
- if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(expression)) {
302
- const declRegex = new RegExp(`(?:const|let|var)\\s+${expression}\\s*=\\s*([^;\\n]+)`);
303
- const declMatch = src.match(declRegex);
304
- if (declMatch) {
305
- resolvedExpression = declMatch[1].trim();
306
- }
307
- }
308
-
309
- const phpVal = translateExpressionToPhp(resolvedExpression, propName);
310
- if (phpVal) {
311
- props[propName] = phpVal;
312
- }
313
- }
314
- }
315
-
316
- // Extract and compile inline schema if present
317
- if (attribsStr.includes("schema=")) {
318
- const rawSchema = extractBalancedJsxExpression(src, "schema");
319
- if (rawSchema) {
320
- const compiledSchema = compileSchemaObject(rawSchema, src);
321
- if (compiledSchema) {
322
- props["schema"] = compiledSchema;
323
- }
324
- }
325
- }
326
-
327
- return props;
328
- }
329
-
330
- function buildHeadHtml(
331
- base: Record<string, string>,
332
- override: Record<string, string> = {}
333
- ): string {
334
- // Merge: per-page overrides win over layout defaults
335
- const p = { ...base, ...override };
336
-
337
- const {
338
- title,
339
- description,
340
- keywords,
341
- ogTitle,
342
- ogDescription,
343
- ogImage,
344
- ogType = "website",
345
- twitterCard = "summary_large_image",
346
- twitterCreator,
347
- canonical,
348
- } = p;
349
-
350
- const tags: string[] = [];
351
-
352
- if (title && !title.includes("FORGEWP")) tags.push(`<title>${title}</title>`);
353
- if (description) tags.push(`<meta name="description" content="${description}">`);
354
- if (keywords) tags.push(`<meta name="keywords" content="${keywords}">`);
355
- if (canonical) tags.push(`<link rel="canonical" href="${canonical}">`);
356
-
357
- // Open Graph
358
- tags.push(`<meta property="og:type" content="${ogType}">`);
359
- const ogTitleVal = ogTitle || title;
360
- if (ogTitleVal && !ogTitleVal.includes("FORGEWP")) {
361
- tags.push(`<meta property="og:title" content="${ogTitleVal}">`);
362
- }
363
- const ogDescVal = ogDescription || description;
364
- if (ogDescVal) tags.push(`<meta property="og:description" content="${ogDescVal}">`);
365
- if (ogImage) tags.push(`<meta property="og:image" content="${ogImage}">`);
366
-
367
- // Twitter
368
- tags.push(`<meta name="twitter:card" content="${twitterCard}">`);
369
- if (ogTitleVal && !ogTitleVal.includes("FORGEWP")) {
370
- tags.push(`<meta name="twitter:title" content="${ogTitleVal}">`);
371
- }
372
- if (ogDescVal) tags.push(`<meta name="twitter:description" content="${ogDescVal}">`);
373
- if (twitterCreator) tags.push(`<meta name="twitter:creator" content="${twitterCreator}">`);
374
- if (p.schema) {
375
- tags.push(`<script type="application/ld+json">\n${p.schema}\n</script>`);
376
- }
377
-
378
- return tags.join("\n");
379
- }
380
-
381
- // ── Render header / footer fragments ─────────────────────────────────────────
382
- let headerFile = "";
383
- let headerCompName = "";
384
-
385
- if (themeConfig.headerPath) {
386
- const absolutePath = path.isAbsolute(themeConfig.headerPath) ? themeConfig.headerPath : path.join(themeRoot, themeConfig.headerPath);
387
- if (existsSync(absolutePath)) {
388
- headerFile = absolutePath;
389
- headerCompName = path.basename(absolutePath, path.extname(absolutePath));
390
- }
391
- }
392
-
393
- if (!headerFile) {
394
- const headerFallbacks = [
395
- "src/components/SiteHeader.tsx",
396
- "src/components/Header.tsx",
397
- "src/components/Navbar.tsx",
398
- "src/components/NavBar.tsx",
399
- "src/components/Navigation.tsx"
400
- ];
401
- for (const relPath of headerFallbacks) {
402
- const p = path.join(themeRoot, relPath);
403
- if (existsSync(p)) {
404
- headerFile = p;
405
- headerCompName = path.basename(p, path.extname(p));
406
- break;
407
- }
408
- }
409
- }
410
-
411
- let headerHtml = "";
412
- if (headerFile) {
413
- try {
414
- const headerUrl = pathToFileURL(headerFile).href;
415
- const module = await import(headerUrl);
416
- const HeaderComponent = module[headerCompName] || module.default;
417
- if (!HeaderComponent) {
418
- throw new Error(`${headerCompName} component not found in export (expects named export '${headerCompName}' or default export).`);
419
- }
420
- headerHtml = renderToStaticMarkup(React.createElement(HeaderComponent));
421
- } catch (err: any) {
422
- console.error(`\n[ForgeWP Compiler Error] Failed to load or render the Header component (${headerFile}).`);
423
- console.error(`Error details: ${err.stack || err.message || err}\n`);
424
- process.exit(1);
425
- }
426
- } else {
427
- console.warn("No separate Header component found, skipping separate header render");
428
- }
429
-
430
- let footerFile = "";
431
- let footerCompName = "";
432
-
433
- if (themeConfig.footerPath) {
434
- const absolutePath = path.isAbsolute(themeConfig.footerPath) ? themeConfig.footerPath : path.join(themeRoot, themeConfig.footerPath);
435
- if (existsSync(absolutePath)) {
436
- footerFile = absolutePath;
437
- footerCompName = path.basename(absolutePath, path.extname(absolutePath));
438
- }
439
- }
440
-
441
- if (!footerFile) {
442
- const footerFallbacks = [
443
- "src/components/SiteFooter.tsx",
444
- "src/components/Footer.tsx"
445
- ];
446
- for (const relPath of footerFallbacks) {
447
- const p = path.join(themeRoot, relPath);
448
- if (existsSync(p)) {
449
- footerFile = p;
450
- footerCompName = path.basename(p, path.extname(p));
451
- break;
452
- }
453
- }
454
- }
455
-
456
- let footerHtml = "";
457
- if (footerFile) {
458
- try {
459
- const footerUrl = pathToFileURL(footerFile).href;
460
- const module = await import(footerUrl);
461
- const FooterComponent = module[footerCompName] || module.default;
462
- if (!FooterComponent) {
463
- throw new Error(`${footerCompName} component not found in export (expects named export '${footerCompName}' or default export).`);
464
- }
465
- footerHtml = renderToStaticMarkup(React.createElement(FooterComponent));
466
- } catch (err: any) {
467
- console.error(`\n[ForgeWP Compiler Error] Failed to load or render the Footer component (${footerFile}).`);
468
- console.error(`Error details: ${err.stack || err.message || err}\n`);
469
- process.exit(1);
470
- }
471
- } else {
472
- console.warn("No separate Footer component found, skipping separate footer render");
473
- }
474
-
475
- // ── Render pages ──────────────────────────────────────────────────────────────
476
- const appHtml = renderPage(App);
477
- let layoutExtraHeadTags = "";
478
- const cleanAppHtml = appHtml.replace(/<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs, (match, childrenHtml) => {
479
- layoutExtraHeadTags += "\n" + childrenHtml;
480
- return "";
481
- });
482
-
483
- // ── Compile Dynamic WordPress Template Hierarchy ──────────────────────────────
484
- const layoutSeo = extractSeoPropsFromSource(layoutPath);
485
- let headHtml = buildHeadHtml(layoutSeo);
486
- const outDir = path.join(themeRoot, ".forgewp");
487
- mkdirSync(outDir, { recursive: true });
488
-
489
- const appDir = path.join(themeRoot, "src", "app");
490
- if (existsSync(appDir)) {
491
- const { readdirSync } = require("node:fs");
492
- const files = readdirSync(appDir);
493
- for (const file of files) {
494
- if (file.endsWith(".tsx")) {
495
- const name = file.replace(".tsx", "");
496
- const isWpTemplate =
497
- name === "single" ||
498
- name === "archive" ||
499
- name === "404" ||
500
- name === "taxonomy" ||
501
- name.startsWith("single-") ||
502
- name.startsWith("taxonomy-") ||
503
- name.startsWith("archive-");
504
-
505
- if (isWpTemplate) {
506
- const filePath = path.join(appDir, file);
507
- console.warn(`[ForgeWP Compiler] Attempting to compile template: ${file}`);
508
- try {
509
- const module = await import(pathToFileURL(filePath).href);
510
- const TemplateComponent = module.default;
511
- if (TemplateComponent) {
512
- globalThis.__forgewpSsrQueries = {};
513
- const html = name === "404"
514
- ? renderToStaticMarkup(React.createElement(TemplateComponent))
515
- : renderPage(TemplateComponent);
516
-
517
- const ssrState = globalThis.__forgewpSsrQueries || {};
518
- let stateScript = "";
519
- if (Object.keys(ssrState).length > 0) {
520
- stateScript = `\n<script id="forgewp-initial-state" type="application/json">${JSON.stringify({ queries: ssrState })}</script>`;
521
- }
522
-
523
- let extraHeadTags = "";
524
- const cleanHtml = html.replace(/<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs, (match, childrenHtml) => {
525
- extraHeadTags += "\n" + childrenHtml;
526
- return "";
527
- });
528
-
529
- const finalHtml = cleanHtml + stateScript;
530
- writeFileSync(path.join(outDir, `${name}.html`), finalHtml, "utf8");
531
- console.warn(`[ForgeWP Compiler] WROTE ${name}.html to ${outDir}`);
532
-
533
- const seoProps = extractSeoPropsFromSource(filePath);
534
- let customHeadHtml = buildHeadHtml(layoutSeo, seoProps);
535
- if (extraHeadTags) {
536
- customHeadHtml += "\n" + extraHeadTags;
537
- }
538
- writeFileSync(path.join(outDir, `${name}-head.html`), customHeadHtml, "utf8");
539
- console.warn(`[ForgeWP Compiler] WROTE ${name}-head.html to ${outDir}`);
540
- }
541
- } catch (e: any) {
542
- console.warn(`[ForgeWP Compiler Warning] Failed to render WP template ${file}:`, e.message);
543
- }
544
- }
545
- }
546
- }
547
- }
548
-
549
- // ── Write outputs ─────────────────────────────────────────────────────────────
550
-
551
-
552
- writeFileSync(path.join(outDir, "header.html"), headerHtml, "utf8");
553
- writeFileSync(path.join(outDir, "footer.html"), footerHtml, "utf8");
554
- writeFileSync(path.join(outDir, "app.html"), cleanAppHtml, "utf8");
555
- let finalHeadHtml = headHtml;
556
- if (layoutExtraHeadTags) {
557
- finalHeadHtml += "\n" + layoutExtraHeadTags;
558
- }
559
- writeFileSync(path.join(outDir, "head.html"), finalHeadHtml, "utf8");
560
-
561
-
562
- // ── Compile Custom Page Templates ──────────────────────────────────────────────
563
- const pagesDir = path.join(themeRoot, "src", "app", "pages");
564
- console.warn("CHECKING PAGES DIR: " + pagesDir + " EXISTS: " + existsSync(pagesDir));
565
- if (existsSync(pagesDir)) {
566
- const { readdirSync } = require("node:fs");
567
- const pages = readdirSync(pagesDir).filter(f => f.endsWith(".tsx"));
568
-
569
- for (const pageFile of pages) {
570
- const pagePath = path.join(pagesDir, pageFile);
571
- console.warn(`Attempting to compile template: ${pageFile}`);
572
- try {
573
- const module = await import(pathToFileURL(pagePath).href);
574
- const CustomPage = module.default || Object.values(module)[0];
575
- if (CustomPage) {
576
- globalThis.__forgewpSsrQueries = {};
577
- const customHtml = renderPage(CustomPage);
578
- const ssrState = globalThis.__forgewpSsrQueries || {};
579
- let stateScript = "";
580
- if (Object.keys(ssrState).length > 0) {
581
- stateScript = `\n<script id="forgewp-initial-state" type="application/json">${JSON.stringify({ queries: ssrState })}</script>`;
582
- }
583
-
584
- let customExtraHeadTags = "";
585
- const cleanCustomHtml = customHtml.replace(/<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs, (match, childrenHtml) => {
586
- customExtraHeadTags += "\n" + childrenHtml;
587
- return "";
588
- });
589
- const pageName = pageFile.replace(".tsx", "");
590
- const slug = pageName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
591
-
592
- let finalHtml = cleanCustomHtml + stateScript;
593
- if (module.pageConfig && typeof module.pageConfig === "object" && module.pageConfig.protected) {
594
- const allowedAttr = module.pageConfig.allowed ? ` allowed="${module.pageConfig.allowed}"` : "";
595
- const redirectAttr = module.pageConfig.redirect ? ` redirect="${module.pageConfig.redirect}"` : "";
596
- finalHtml = `<forgewp-require-auth${allowedAttr}${redirectAttr}></forgewp-require-auth>` + finalHtml;
597
- }
598
-
599
- writeFileSync(path.join(outDir, `template-${slug}.html`), finalHtml, "utf8");
600
- console.warn(`WROTE template-${slug}.html to ${outDir}`);
601
-
602
- const customSeo = extractSeoPropsFromSource(pagePath);
603
- let customHeadHtml = buildHeadHtml(layoutSeo, customSeo);
604
- if (customExtraHeadTags) {
605
- customHeadHtml += "\n" + customExtraHeadTags;
606
- }
607
- writeFileSync(path.join(outDir, `template-${slug}-head.html`), customHeadHtml, "utf8");
608
- console.warn(`WROTE template-${slug}-head.html to ${outDir}`);
609
- }
610
- } catch (e) {
611
- console.warn(`Failed to render custom page ${pageFile}:`, e.message);
612
- }
613
- }
614
- }
615
-
616
- process.stdout.write(outDir);
1
+ import {
2
+ existsSync,
3
+ readFileSync,
4
+ mkdirSync,
5
+ writeFileSync,
6
+ readdirSync,
7
+ unlinkSync,
8
+ } from 'node:fs';
9
+ import path from 'node:path';
10
+ import { pathToFileURL, fileURLToPath } from 'node:url';
11
+ import { createRequire, register } from 'node:module';
12
+ import { isComponentInteractive } from './hydration/is-interactive.js';
13
+ import { getComponentRootClassName } from './hydration/root-class-extractor.js';
14
+ import {
15
+ scanAppProviders,
16
+ fileImportsProvider,
17
+ } from './hydration/scan-app-providers.js';
18
+ import { visibleFirstPaintProps } from './hydration/enter-hidden-initial.js';
19
+ import { layoutOwnsDocument, resolveFrontPageLayout } from './route-layout.js';
20
+ import { collectStaticRouteDefinitions } from './collect-static-routes.js';
21
+ import { loadMenusData } from './functions/load-menus.js';
22
+ import { loadMockData } from './functions/seed-mock-data.js';
23
+ import { loadProductsData } from './functions/seed-products.js';
24
+ import { usesBlockArea } from './hydration/uses-block-area.js';
25
+ import { discoverReactTemplates, resolvePageTemplateIntent, pageTemplateDiagnostic, writePageTemplateCache } from './template-discovery.js';
26
+
27
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
28
+ register(pathToFileURL(path.join(__dirname, 'asset-loader.js')).href);
29
+
30
+ const themeRoot = process.argv[2];
31
+ const VERBOSE = process.env.FORGEWP_VERBOSE === '1';
32
+
33
+ if (!themeRoot) {
34
+ console.error('Usage: render-theme.mts <theme-root>');
35
+ process.exit(1);
36
+ }
37
+
38
+ // Use the theme's own node_modules for ALL packages (React 19)
39
+ const require = createRequire(path.join(themeRoot, 'package.json'));
40
+ const React = require('react');
41
+ const forgeWpGlobal = globalThis as typeof globalThis & {
42
+ React: any;
43
+ __forgewpSsrQueries: Record<string, any>;
44
+ };
45
+ forgeWpGlobal.React = React; // Polyfill for classic JSX transform in Node.js
46
+
47
+ // Resilient browser globals polyfills for Node SSR/compile-time rendering
48
+ if (typeof globalThis.window === 'undefined') {
49
+ const mockLocation = {
50
+ pathname: '/',
51
+ search: '',
52
+ hash: '',
53
+ href: 'http://localhost/',
54
+ origin: 'http://localhost',
55
+ assign: () => {},
56
+ replace: () => {},
57
+ reload: () => {},
58
+ };
59
+ const mockMatchMedia = (query: string) => {
60
+ // Do NOT report prefers-reduced-motion during compile-time SSR.
61
+ // Components that branch on useReducedMotion() would bake the no-hover
62
+ // fallback into static HTML and then never hydrate. Hover/CSS structure
63
+ // must ship. First-paint visibility is handled by skipping enter-hidden
64
+ // `initial` styles on motion nodes, not by lying about user preference.
65
+ return {
66
+ matches: false,
67
+ media: query,
68
+ onchange: null,
69
+ addListener: () => {},
70
+ removeListener: () => {},
71
+ addEventListener: () => {},
72
+ removeEventListener: () => {},
73
+ dispatchEvent: () => false,
74
+ };
75
+ };
76
+
77
+ globalThis.window = {
78
+ location: mockLocation,
79
+ navigator: { userAgent: 'Node' },
80
+ addEventListener: () => {},
81
+ removeEventListener: () => {},
82
+ dispatchEvent: () => false,
83
+ matchMedia: mockMatchMedia,
84
+ _forgeWpCompileTime: true,
85
+ } as any;
86
+ globalThis.matchMedia = mockMatchMedia as any;
87
+ globalThis.location = mockLocation as any;
88
+ globalThis.document = {
89
+ addEventListener: () => {},
90
+ removeEventListener: () => {},
91
+ querySelector: () => null,
92
+ querySelectorAll: () => [],
93
+ } as any;
94
+ globalThis.SVGElement = class SVGElement {} as any;
95
+
96
+ if (typeof globalThis.IntersectionObserver === 'undefined') {
97
+ globalThis.IntersectionObserver = class MockIntersectionObserver {
98
+ observe() {}
99
+ unobserve() {}
100
+ disconnect() {}
101
+ } as any;
102
+ }
103
+ if (typeof globalThis.ResizeObserver === 'undefined') {
104
+ globalThis.ResizeObserver = class MockResizeObserver {
105
+ observe() {}
106
+ unobserve() {}
107
+ disconnect() {}
108
+ } as any;
109
+ }
110
+
111
+ const originalEncode = globalThis.encodeURIComponent;
112
+ globalThis.encodeURIComponent = function (val: any): string {
113
+ const str = String(val);
114
+ if (
115
+ str.includes('__FORGEWP_') &&
116
+ !str.includes('_DEFAULT_') &&
117
+ !str.includes('__FORGEWP_I18N_') &&
118
+ !str.includes('__FORGEWP_OPTION_') &&
119
+ !str.includes('__FORGEWP_THEME_MOD_')
120
+ ) {
121
+ return `__FORGEWP_URLENCODE_START__${str}__FORGEWP_URLENCODE_END__`;
122
+ }
123
+ return originalEncode ? originalEncode(str) : encodeURIComponent(str);
124
+ };
125
+
126
+ (globalThis.window as any)._forgeWpMockMenus = loadMenusData(themeRoot);
127
+ }
128
+
129
+ const { renderToStaticMarkup } = require('react-dom/server');
130
+
131
+ // ── Auto-Hydration Island Injection ─────────────────────────────────────────
132
+ // For Smart Discovery islands (components detected as interactive but with no explicit
133
+ // <Hydrate> wrapper), monkey-patch React.createElement to auto-wrap them with a
134
+ // data-forgewp-auto-island div during SSR. This lets generate-theme.js inject the
135
+ // proper data-forgewp-hydrate wrappers in the final HTML output.
136
+ import {
137
+ scanForHydrationIslandsWithProps,
138
+ findComponentPath,
139
+ } from './hydration/index.js';
140
+
141
+ const layoutProvidersForSsr = scanAppProviders(themeRoot);
142
+ const detailedIslandsForSsr = scanForHydrationIslandsWithProps(themeRoot);
143
+ const autoIslandNames = new Set(
144
+ detailedIslandsForSsr
145
+ .filter((i) => i.smartDiscovered)
146
+ .map((i) => {
147
+ // Convert kebab-name back to PascalCase component names for matching
148
+ return i.name
149
+ .split('-')
150
+ .map((w: string) => w.charAt(0).toUpperCase() + w.slice(1))
151
+ .join('');
152
+ }),
153
+ );
154
+ const autoIslandKebabByPascal = new Map<string, string>();
155
+ const pagesWithBlockArea = new Set<string>();
156
+ // Root className each Smart Discovery component's own outermost JSX element carries
157
+ // (when statically resolvable) — hoisted onto the wrapper div below so auto-hydration
158
+ // doesn't silently strip layout-critical classes (w-full, flex, grid, ...) from the tree.
159
+ const autoIslandRootClassByPascal = new Map<string, string>();
160
+ const autoIslandNeedsProviders = new Set<string>();
161
+ for (const island of detailedIslandsForSsr.filter((i) => i.smartDiscovered)) {
162
+ const pascal = island.name
163
+ .split('-')
164
+ .map((w: string) => w.charAt(0).toUpperCase() + w.slice(1))
165
+ .join('');
166
+ autoIslandKebabByPascal.set(pascal, island.name);
167
+ if (island.rootClassName) {
168
+ autoIslandRootClassByPascal.set(pascal, island.rootClassName);
169
+ }
170
+ }
171
+ for (const island of detailedIslandsForSsr.filter((i) => i.smartDiscovered)) {
172
+ const file = findComponentPath(themeRoot, island.name);
173
+ if (file && fileImportsProvider(file, layoutProvidersForSsr)) {
174
+ const pascal = island.name
175
+ .split('-')
176
+ .map((w: string) => w.charAt(0).toUpperCase() + w.slice(1))
177
+ .join('');
178
+ autoIslandNeedsProviders.add(pascal);
179
+ }
180
+ }
181
+
182
+ function hasRenderableChildren(props: any, childArgs: any[]): boolean {
183
+ const list: any[] = [];
184
+ if (childArgs && childArgs.length) list.push(...childArgs);
185
+ if (props && props.children != null) {
186
+ if (Array.isArray(props.children)) list.push(...props.children);
187
+ else list.push(props.children);
188
+ }
189
+ return list.some((c) => {
190
+ if (c == null || c === false || c === true) return false;
191
+ if (typeof c === 'string') return c.trim().length > 0;
192
+ if (typeof c === 'number') return true;
193
+ if (React.isValidElement(c)) return true;
194
+ if (Array.isArray(c))
195
+ return c.some((x) => x != null && x !== false && x !== true);
196
+ return false;
197
+ });
198
+ }
199
+
200
+ function componentIslandName(type: any): string | null {
201
+ if (!type) return null;
202
+ if (typeof type === 'function') return type.displayName || type.name || null;
203
+ if (typeof type === 'object' && typeof type.render === 'function') {
204
+ return (
205
+ type.displayName || type.render.displayName || type.render.name || null
206
+ );
207
+ }
208
+ return null;
209
+ }
210
+
211
+ function paintVisibleProps(props: any) {
212
+ // Skip enter-hidden animation styles on static HTML so first paint is
213
+ // visible. Handles both `initial={{ opacity: 0 }}` and `initial="hidden"`
214
+ // + variants. Do not toggle useReducedMotion — that strips CSS hover
215
+ // structures from any theme that branches on that hook.
216
+ if (!props || typeof props !== 'object') return props;
217
+ return visibleFirstPaintProps(props);
218
+ }
219
+
220
+ function islandWrapperProps(
221
+ name: string,
222
+ props: any,
223
+ childArgs: any[],
224
+ ): Record<string, any> {
225
+ const kebab =
226
+ autoIslandKebabByPascal.get(name) ||
227
+ name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
228
+ const rootClassName = autoIslandRootClassByPascal.get(name);
229
+ const childStyle =
230
+ props && typeof props.style === 'object' && props.style !== null
231
+ ? props.style
232
+ : {};
233
+ const wrapperProps: Record<string, any> = {
234
+ 'data-forgewp-auto-island': kebab,
235
+ style: {
236
+ display: (childStyle && childStyle.display) || 'contents',
237
+ ...childStyle,
238
+ },
239
+ };
240
+ if (rootClassName) wrapperProps.className = rootClassName;
241
+ // Forward the JSX call-site's actual props so the client hydrator mounts
242
+ // the real component with them. Functions and elements are not init data.
243
+ let serializedProps = '{}';
244
+ if (props && typeof props === 'object') {
245
+ const serializable: Record<string, any> = {};
246
+ for (const [k, v] of Object.entries(props)) {
247
+ if (k === 'children') continue;
248
+ if (typeof v === 'function') continue;
249
+ if (v === undefined) continue;
250
+ if (React.isValidElement(v)) continue;
251
+ serializable[k] = v;
252
+ }
253
+ try {
254
+ serializedProps = JSON.stringify(serializable);
255
+ } catch {
256
+ serializedProps = '{}';
257
+ }
258
+ }
259
+ wrapperProps['data-forgewp-auto-island-props'] = serializedProps;
260
+ if (hasRenderableChildren(props, childArgs)) {
261
+ wrapperProps['data-forgewp-slot-children'] = 'true';
262
+ }
263
+ if (autoIslandNeedsProviders.has(name)) {
264
+ wrapperProps['data-forgewp-needs-providers'] = 'true';
265
+ }
266
+ return wrapperProps;
267
+ }
268
+
269
+ const origCreate = React.createElement;
270
+ React.createElement = function patchedCreateElement(
271
+ type: any,
272
+ props: any,
273
+ ...children: any[]
274
+ ) {
275
+ props = paintVisibleProps(props);
276
+ const name = componentIslandName(type);
277
+ if (name && autoIslandNames.has(name) && !pagesWithBlockArea.has(name)) {
278
+ const inner = origCreate.call(this, type, props, ...children);
279
+ return origCreate.call(
280
+ this,
281
+ 'div',
282
+ islandWrapperProps(name, props, children),
283
+ inner,
284
+ );
285
+ }
286
+ return origCreate.call(this, type, props, ...children);
287
+ };
288
+
289
+ // Theme TSX is compiled either to React.createElement (the SSR loader) or to
290
+ // react/jsx-runtime (tsx + the theme's "jsx": "react-jsx"). Both have to
291
+ // mark islands, or a component is interactive in React and static in WordPress.
292
+ function patchJsxRuntime(runtime: any) {
293
+ if (!runtime || runtime.__forgewpIslandPatched) return;
294
+ const origJsx = runtime.jsx;
295
+ const origJsxs = runtime.jsxs;
296
+ const origJsxDEV = runtime.jsxDEV;
297
+ const wrap =
298
+ (orig: any) =>
299
+ (type: any, props: any, key: any, ...rest: any[]) => {
300
+ const nextProps = paintVisibleProps(props);
301
+ const name = componentIslandName(type);
302
+ if (
303
+ !name ||
304
+ !autoIslandNames.has(name) ||
305
+ pagesWithBlockArea.has(name) ||
306
+ typeof orig !== 'function'
307
+ ) {
308
+ return orig(type, nextProps, key, ...rest);
309
+ }
310
+ const inner = orig(type, nextProps, undefined, ...rest);
311
+ const wrapperProps = islandWrapperProps(name, nextProps, []);
312
+ wrapperProps.children = inner;
313
+ const create = typeof origJsx === 'function' ? origJsx : orig;
314
+ return create('div', wrapperProps, key);
315
+ };
316
+ if (typeof origJsx === 'function') runtime.jsx = wrap(origJsx);
317
+ if (typeof origJsxs === 'function') runtime.jsxs = wrap(origJsxs);
318
+ if (typeof origJsxDEV === 'function') runtime.jsxDEV = wrap(origJsxDEV);
319
+ runtime.__forgewpIslandPatched = true;
320
+ }
321
+
322
+ try {
323
+ patchJsxRuntime(require('react/jsx-runtime'));
324
+ } catch {}
325
+ try {
326
+ patchJsxRuntime(require('react/jsx-dev-runtime'));
327
+ } catch {}
328
+
329
+ const appUrl = pathToFileURL(
330
+ path.join(themeRoot, 'src', 'app', 'page.tsx'),
331
+ ).href;
332
+ const layoutUrl = pathToFileURL(
333
+ path.join(themeRoot, 'src', 'app', 'layout.tsx'),
334
+ ).href;
335
+ const layoutPath = path.join(themeRoot, 'src', 'app', 'layout.tsx');
336
+
337
+ // ── Load pages ────────────────────────────────────────────────────────────────
338
+ let App: any;
339
+ try {
340
+ const module = await import(appUrl);
341
+ App = module.default;
342
+ if (!App) {
343
+ throw new Error('Page component lacks a default export.');
344
+ }
345
+ } catch (err: any) {
346
+ console.error(
347
+ `\n[ForgeWP Compiler Error] Failed to load the main Page component (src/app/page.tsx).`,
348
+ );
349
+ console.error(
350
+ `Check for syntax errors, incorrect imports, or invalid references inside your page component.`,
351
+ );
352
+ console.error(`Error details: ${err.stack || err.message || err}\n`);
353
+ process.exit(1);
354
+ }
355
+
356
+ let RootLayout: (props: any) => any = ({ children }: any) =>
357
+ React.createElement(React.Fragment, null, children);
358
+ if (existsSync(layoutPath)) {
359
+ try {
360
+ const module = await import(layoutUrl);
361
+ RootLayout = module.default;
362
+ if (!RootLayout) {
363
+ throw new Error('Root layout component lacks a default export.');
364
+ }
365
+ } catch (err: any) {
366
+ console.error(
367
+ `\n[ForgeWP Compiler Error] Failed to load the Root Layout component (src/app/layout.tsx).`,
368
+ );
369
+ console.error(
370
+ `Check for syntax errors, incorrect imports, or invalid references inside your layout component.`,
371
+ );
372
+ console.error(`Error details: ${err.stack || err.message || err}\n`);
373
+ process.exit(1);
374
+ }
375
+ } else {
376
+ console.warn(
377
+ 'RootLayout (src/app/layout.tsx) not found, using Fragment fallback',
378
+ );
379
+ }
380
+
381
+ // ── Render a page inside RootLayout ──────────────────────────────────────────
382
+ let WpAuthProvider: any = null;
383
+ try {
384
+ const authModule = require('@forgewp/auth');
385
+ WpAuthProvider = authModule.WpAuthProvider;
386
+ } catch (e) {}
387
+
388
+ async function resolveLayoutComponent(
389
+ layoutName?: string | false,
390
+ ): Promise<any> {
391
+ if (layoutName === false || layoutName === 'blank') {
392
+ return React.Fragment;
393
+ }
394
+ const layoutsDir = path.join(themeRoot, 'src', 'app', 'layouts');
395
+ if (existsSync(layoutsDir)) {
396
+ const targetName = layoutName || 'default';
397
+ const candidates = [
398
+ path.join(layoutsDir, `${targetName}.tsx`),
399
+ path.join(layoutsDir, `${targetName}.jsx`),
400
+ path.join(layoutsDir, `${targetName}.ts`),
401
+ path.join(layoutsDir, `${targetName}.js`),
402
+ path.join(layoutsDir, `${targetName}/index.tsx`),
403
+ path.join(layoutsDir, `${targetName}/index.jsx`),
404
+ ];
405
+ for (const cand of candidates) {
406
+ if (existsSync(cand)) {
407
+ try {
408
+ const mod = await import(pathToFileURL(cand).href);
409
+ const comp =
410
+ mod.default ||
411
+ Object.values(mod).find((v) => typeof v === 'function');
412
+ if (comp) return comp;
413
+ } catch (e: any) {
414
+ console.warn(
415
+ `[ForgeWP Compiler] Failed to import layout ${cand}:`,
416
+ e.message,
417
+ );
418
+ }
419
+ }
420
+ }
421
+ }
422
+ // Fallback to RootLayout (src/app/layout.tsx)
423
+ return RootLayout;
424
+ }
425
+
426
+ function wrapWithRootProviders(inner: any, LayoutComponent: any = RootLayout) {
427
+ const ResolvedLayout = LayoutComponent || RootLayout;
428
+ let element = React.createElement(ResolvedLayout, null, inner);
429
+ if (ResolvedLayout !== RootLayout && ResolvedLayout !== React.Fragment) {
430
+ element = React.createElement(RootLayout, null, element);
431
+ }
432
+ if (WpAuthProvider) {
433
+ element = React.createElement(WpAuthProvider, null, element);
434
+ }
435
+ return element;
436
+ }
437
+
438
+ function renderPage(
439
+ PageComponent: any,
440
+ filePath?: string,
441
+ LayoutComponent: any = RootLayout,
442
+ options: { ownsShell?: boolean } = {},
443
+ ): string {
444
+ try {
445
+ const hasBlockArea =
446
+ Boolean(filePath) &&
447
+ existsSync(filePath!) &&
448
+ usesBlockArea(readFileSync(filePath!, 'utf8'));
449
+ const pageName = hasBlockArea ? componentIslandName(PageComponent) : null;
450
+ if (pageName) pagesWithBlockArea.add(pageName);
451
+
452
+ let pageEl = React.createElement(PageComponent);
453
+ if (
454
+ filePath &&
455
+ existsSync(filePath) &&
456
+ isComponentInteractive(filePath) &&
457
+ !hasBlockArea
458
+ ) {
459
+ const compName = path.basename(filePath, path.extname(filePath));
460
+ const kebabName = compName
461
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
462
+ .toLowerCase();
463
+ const rootInfo = getComponentRootClassName(filePath);
464
+ const wrapperProps: Record<string, any> = {
465
+ 'data-forgewp-auto-island': kebabName,
466
+ style: { display: 'contents' },
467
+ };
468
+ if (rootInfo.resolvable && rootInfo.className) {
469
+ wrapperProps.className = rootInfo.className;
470
+ }
471
+ pageEl = React.createElement('div', wrapperProps, pageEl);
472
+ }
473
+ const boundaryProps: Record<string, any> | null = options.ownsShell
474
+ ? { 'data-forgewp-owns-shell': 'true' }
475
+ : null;
476
+ const pageBoundary = React.createElement(
477
+ 'forgewp-content-boundary',
478
+ boundaryProps,
479
+ pageEl,
480
+ );
481
+ return renderToStaticMarkup(
482
+ wrapWithRootProviders(pageBoundary, LayoutComponent),
483
+ );
484
+ } catch (err: any) {
485
+ console.error(
486
+ `\n[ForgeWP Compiler Error] Server-Side Rendering (SSR) failed for Page Component.`,
487
+ );
488
+ console.error(
489
+ `This typically happens if you use browser-only globals (like 'window', 'document', 'localStorage') at render-time, or if a component throws during execution.`,
490
+ );
491
+ console.error(
492
+ `Ensure browser-specific logic is placed inside useEffect() or is executed only in the client.`,
493
+ );
494
+ console.error(`Error details: ${err.stack || err.message || err}\n`);
495
+ process.exit(1);
496
+ }
497
+ }
498
+
499
+ let textDomain = 'forgewp';
500
+ let themeConfig: any = {};
501
+ try {
502
+ const wpConfigPath = path.join(themeRoot, 'wp.config.ts');
503
+ if (existsSync(wpConfigPath)) {
504
+ const wpConfigUrl = pathToFileURL(wpConfigPath).href;
505
+ const configModule = await import(wpConfigUrl);
506
+ themeConfig = configModule.default || configModule;
507
+ if (themeConfig.textDomain) {
508
+ textDomain = themeConfig.textDomain;
509
+ }
510
+ }
511
+ } catch (e) {
512
+ // fallback if import fails
513
+ try {
514
+ const wpConfigPath = path.join(themeRoot, 'wp.config.ts');
515
+ if (existsSync(wpConfigPath)) {
516
+ const configContent = readFileSync(wpConfigPath, 'utf8');
517
+ const domainMatch = configContent.match(
518
+ /textDomain\s*:\s*['"]([^'"]+)['"]/,
519
+ );
520
+ if (domainMatch) {
521
+ textDomain = domainMatch[1];
522
+ }
523
+ }
524
+ } catch (e2) {}
525
+ }
526
+
527
+ function translateExpressionToPhp(
528
+ expression: string,
529
+ propName: string,
530
+ ): string {
531
+ expression = expression.trim();
532
+
533
+ // 1. Check for useWpTitle()
534
+ if (expression.includes('useWpTitle(')) {
535
+ return `<?php echo esc_attr(get_the_title()); ?>`;
536
+ }
537
+ // 2. Check for useWpExcerpt()
538
+ if (expression.includes('useWpExcerpt(')) {
539
+ return `<?php echo esc_attr(get_the_excerpt()); ?>`;
540
+ }
541
+ // 3. Check for useWpFeaturedImage()
542
+ if (expression.includes('useWpFeaturedImage(')) {
543
+ return `<?php $wp_id = (isset($block) && is_object($block) && isset($block->context['postId'])) ? $block->context['postId'] : get_the_ID(); echo esc_url(get_the_post_thumbnail_url($wp_id, 'full')); ?>`;
544
+ }
545
+ // 4. Check for useWpPermalink()
546
+ if (expression.includes('useWpPermalink(')) {
547
+ return `<?php $wp_id = (isset($block) && is_object($block) && isset($block->context['postId'])) ? $block->context['postId'] : get_the_ID(); echo esc_url(get_permalink($wp_id)); ?>`;
548
+ }
549
+ // 5. Check for useWpCustomField / useWpField / useWpMeta
550
+ const metaMatch = expression.match(
551
+ /useWp(?:CustomField|Field|Meta)\s*\(\s*['"]([^'"]+)['"]\s*(?:,\s*([\s\S]+?))?\s*\)/,
552
+ );
553
+ if (metaMatch) {
554
+ const key = metaMatch[1];
555
+ const rawFallback = metaMatch[2];
556
+
557
+ let fallbackPhp = '';
558
+ if (rawFallback) {
559
+ const trimmed = rawFallback.trim();
560
+ const i18nMatch = trimmed.match(/__\(\s*['"]([^'"]+)['"]\s*\)/);
561
+ if (i18nMatch) {
562
+ fallbackPhp = ` ?: __('${i18nMatch[1].replace(/'/g, "\\'")}', 'hotelchecker24')`;
563
+ } else if (trimmed.startsWith("'") || trimmed.startsWith('"')) {
564
+ fallbackPhp = ` ?: ${trimmed}`;
565
+ } else {
566
+ fallbackPhp = ` ?: ${trimmed}`;
567
+ }
568
+ }
569
+
570
+ const isUrl =
571
+ propName === 'canonical' ||
572
+ propName === 'ogImage' ||
573
+ key.includes('url') ||
574
+ key.includes('image') ||
575
+ key.includes('website');
576
+ const escFn = isUrl ? 'esc_url' : 'esc_attr';
577
+ return `<?php $wp_id = (isset($block) && is_object($block) && isset($block->context['postId'])) ? $block->context['postId'] : get_the_ID(); echo ${escFn}(get_post_meta($wp_id, '${key}', true)${fallbackPhp}); ?>`;
578
+ }
579
+ // 6. Check for useWpAuthor()
580
+ if (expression.includes('useWpAuthor(')) {
581
+ return `<?php echo esc_attr(get_the_author()); ?>`;
582
+ }
583
+ // 7. Check for useWpDate()
584
+ if (expression.includes('useWpDate(')) {
585
+ return `<?php echo esc_attr(get_the_date()); ?>`;
586
+ }
587
+ // 8. Check for useWpOption()
588
+ const optionMatch = expression.match(/useWpOption\s*\(\s*['"]([^'"]+)['"]/);
589
+ if (optionMatch) {
590
+ const key = optionMatch[1];
591
+ return `<?php echo esc_attr(get_option('${key}', '')); ?>`;
592
+ }
593
+ // 9. Check for useWpThemeMod()
594
+ const themeModMatch = expression.match(
595
+ /useWpThemeMod\s*\(\s*['"]([^'"]+)['"]/,
596
+ );
597
+ if (themeModMatch) {
598
+ const key = themeModMatch[1];
599
+ return `<?php echo esc_attr(get_theme_mod('${key}', '')); ?>`;
600
+ }
601
+ // 10. Check for useWpPageLink
602
+ const pageLinkMatch = expression.match(
603
+ /useWpPageLink\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/,
604
+ );
605
+ if (pageLinkMatch) {
606
+ const templateName = pageLinkMatch[1];
607
+ const fallbackUrl = pageLinkMatch[2];
608
+ return `<?php $matched = get_pages(array('meta_key' => '_wp_page_template', 'meta_value' => 'page-${templateName.replace(/-page$/, '')}.php', 'number' => 1)); echo esc_url(!empty($matched) ? get_permalink($matched[0]->ID) : home_url('${fallbackUrl}')); ?>`;
609
+ }
610
+ // 11. Check for internationalization __()
611
+ const i18nMatch = expression.match(/__\s*\(\s*['"]([^'"]+)['"]/);
612
+ if (i18nMatch) {
613
+ const str = i18nMatch[1];
614
+ return `<?php echo esc_attr(__('${str}', '${textDomain}')); ?>`;
615
+ }
616
+ // 12. Check for literal string in quotes
617
+ const literalMatch = expression.match(/^\s*['"]([^'"]+)['"]\s*$/);
618
+ if (literalMatch) {
619
+ return literalMatch[1];
620
+ }
621
+ return '';
622
+ }
623
+
624
+ function extractBalancedJsxExpression(src: string, propName: string): string {
625
+ const marker = `${propName}={`;
626
+ const index = src.indexOf(marker);
627
+ if (index === -1) return '';
628
+ let braces = 1;
629
+ let start = index + marker.length;
630
+ let i = start;
631
+ while (braces > 0 && i < src.length) {
632
+ if (src[i] === '{') braces++;
633
+ else if (src[i] === '}') braces--;
634
+ i++;
635
+ }
636
+ return src.slice(start, i - 1).trim();
637
+ }
638
+
639
+ function compileSchemaObject(schemaExpr: string, fileSrc: string): string {
640
+ return schemaExpr.replace(
641
+ /("[\w@]+"|[\w@]+)\s*:\s*([^,\n}]+)/g,
642
+ (match, key, valStr) => {
643
+ let val = valStr.trim();
644
+ if (/^["']([^"']*)["']$/.test(val)) {
645
+ return `${key}: ${val}`;
646
+ }
647
+ if (/^(true|false|[0-9.]+)$/i.test(val)) {
648
+ return `${key}: ${val}`;
649
+ }
650
+ let resolved = val;
651
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(val)) {
652
+ const declRegex = new RegExp(
653
+ `(?:const|let|var)\\s+${val}\\s*=\\s*([^;\\n]+)`,
654
+ );
655
+ const declMatch = fileSrc.match(declRegex);
656
+ if (declMatch) {
657
+ resolved = declMatch[1].trim();
658
+ }
659
+ }
660
+ const phpVal = translateExpressionToPhp(resolved, '');
661
+ if (phpVal) {
662
+ return `${key}: "${phpVal}"`;
663
+ }
664
+ return `${key}: ${val}`;
665
+ },
666
+ );
667
+ }
668
+
669
+ // ── SEO extraction from source files (React 19 SSR-safe) ─────────────────────
670
+ // react-helmet-async v3 disabled server-side context for React 19 —
671
+ // HelmetProvider is a Fragment at SSR time so helmetContext.helmet is never set.
672
+ // Instead we parse <SEO .../> props directly from the source TSX file.
673
+
674
+ function extractSeoPropsFromSource(filePath: string): Record<string, string> {
675
+ if (!filePath || !existsSync(filePath)) return {};
676
+
677
+ let src = readFileSync(filePath, 'utf8');
678
+
679
+ // Strip JSX block comments so we don't match <SEO /> mentions inside them
680
+ src = src.replace(/\{\/\*[\s\S]*?\*\/\}/g, '');
681
+
682
+ // Find the first <SEO ... /> or <WpHead ... /> (multiline, s flag)
683
+ const seoMatch = src.match(/<(?:SEO|WpHead)\b([^>]*?)(?:\/>|>)/s);
684
+ if (!seoMatch) {
685
+ // If not found, let's look for local imports to follow
686
+ const importRegex = /import\s+.*?\s+from\s+['"](\.\.?\/[^'"]+)['"]/g;
687
+ let match;
688
+ const dir = path.dirname(filePath);
689
+ while ((match = importRegex.exec(src)) !== null) {
690
+ const relativePath = match[1];
691
+ // Try resolving with common extensions
692
+ for (const ext of ['.tsx', '.ts', '/index.tsx', '/index.ts']) {
693
+ const resolvedPath = path.resolve(dir, relativePath + ext);
694
+ if (existsSync(resolvedPath)) {
695
+ const importedProps = extractSeoPropsFromSource(resolvedPath);
696
+ if (Object.keys(importedProps).length > 0) {
697
+ return importedProps; // Return the first matching props we find
698
+ }
699
+ }
700
+ }
701
+ }
702
+ return {};
703
+ }
704
+
705
+ const attribsStr = seoMatch[1];
706
+ const props: Record<string, string> = {};
707
+
708
+ // Double-quoted values: prop="value with & and spaces"
709
+ let m: RegExpExecArray | null;
710
+ const dqPattern = /(\w+)\s*=\s*"([^"]*)"/g;
711
+ while ((m = dqPattern.exec(attribsStr)) !== null) props[m[1]] = m[2];
712
+
713
+ // Single-quoted values: prop='value'
714
+ const sqPattern = /(\w+)\s*=\s*'([^']*)'/g;
715
+ while ((m = sqPattern.exec(attribsStr)) !== null)
716
+ if (!props[m[1]]) props[m[1]] = m[2];
717
+
718
+ // JSX string expressions: prop={"value"} or prop={'value'}
719
+ const jsxPattern = /(\w+)\s*=\s*\{["']([^"']*)["']\}/g;
720
+ while ((m = jsxPattern.exec(attribsStr)) !== null)
721
+ if (!props[m[1]]) props[m[1]] = m[2];
722
+
723
+ // JSX brace expressions: prop={expression}
724
+ const exprPattern = /(\w+)\s*=\s*\{([^}]*)\}/g;
725
+ while ((m = exprPattern.exec(attribsStr)) !== null) {
726
+ const propName = m[1];
727
+ const expression = m[2].trim();
728
+ if (!props[propName]) {
729
+ let resolvedExpression = expression;
730
+
731
+ // Trace variable name back to declaration if it is a simple identifier
732
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(expression)) {
733
+ const declRegex = new RegExp(
734
+ `(?:const|let|var)\\s+${expression}\\s*=\\s*([^;\\n]+)`,
735
+ );
736
+ const declMatch = src.match(declRegex);
737
+ if (declMatch) {
738
+ resolvedExpression = declMatch[1].trim();
739
+ }
740
+ }
741
+
742
+ const phpVal = translateExpressionToPhp(resolvedExpression, propName);
743
+ if (phpVal) {
744
+ props[propName] = phpVal;
745
+ }
746
+ }
747
+ }
748
+
749
+ // Extract and compile inline schema if present
750
+ if (attribsStr.includes('schema=')) {
751
+ const rawSchema = extractBalancedJsxExpression(src, 'schema');
752
+ if (rawSchema) {
753
+ const compiledSchema = compileSchemaObject(rawSchema, src);
754
+ if (compiledSchema) {
755
+ props['schema'] = compiledSchema;
756
+ }
757
+ }
758
+ }
759
+
760
+ return props;
761
+ }
762
+
763
+ function buildHeadHtml(
764
+ base: Record<string, string>,
765
+ override: Record<string, string> = {},
766
+ ): string {
767
+ // Merge: per-page overrides win over layout defaults
768
+ const p = { ...base, ...override };
769
+
770
+ const {
771
+ title,
772
+ description,
773
+ keywords,
774
+ ogTitle,
775
+ ogDescription,
776
+ ogImage,
777
+ ogType = 'website',
778
+ twitterCard = 'summary_large_image',
779
+ twitterCreator,
780
+ canonical,
781
+ } = p;
782
+
783
+ const tags: string[] = [];
784
+
785
+ if (title && !title.includes('FORGEWP')) tags.push(`<title>${title}</title>`);
786
+ if (description)
787
+ tags.push(`<meta name="description" content="${description}">`);
788
+ if (keywords) tags.push(`<meta name="keywords" content="${keywords}">`);
789
+ if (canonical) tags.push(`<link rel="canonical" href="${canonical}">`);
790
+
791
+ // Open Graph
792
+ tags.push(`<meta property="og:type" content="${ogType}">`);
793
+ const ogTitleVal = ogTitle || title;
794
+ if (ogTitleVal && !ogTitleVal.includes('FORGEWP')) {
795
+ tags.push(`<meta property="og:title" content="${ogTitleVal}">`);
796
+ }
797
+ const ogDescVal = ogDescription || description;
798
+ if (ogDescVal)
799
+ tags.push(`<meta property="og:description" content="${ogDescVal}">`);
800
+ if (ogImage) tags.push(`<meta property="og:image" content="${ogImage}">`);
801
+
802
+ // Twitter
803
+ tags.push(`<meta name="twitter:card" content="${twitterCard}">`);
804
+ if (ogTitleVal && !ogTitleVal.includes('FORGEWP')) {
805
+ tags.push(`<meta name="twitter:title" content="${ogTitleVal}">`);
806
+ }
807
+ if (ogDescVal)
808
+ tags.push(`<meta name="twitter:description" content="${ogDescVal}">`);
809
+ if (twitterCreator)
810
+ tags.push(`<meta name="twitter:creator" content="${twitterCreator}">`);
811
+ if (p.schema) {
812
+ tags.push(`<script type="application/ld+json">\n${p.schema}\n</script>`);
813
+ }
814
+
815
+ return tags.join('\n');
816
+ }
817
+
818
+ // ── Render header / footer fragments ─────────────────────────────────────────
819
+ let headerHtml = '';
820
+ let footerHtml = '';
821
+
822
+ const hasLayoutsArchitecture =
823
+ existsSync(path.join(themeRoot, 'src', 'app', 'layouts')) ||
824
+ existsSync(layoutPath);
825
+
826
+ if (hasLayoutsArchitecture) {
827
+ // 1. In modern layout-driven projects, the default layout is the single source of truth
828
+ try {
829
+ const DefaultLayoutComp = await resolveLayoutComponent();
830
+ if (DefaultLayoutComp) {
831
+ const layoutMarkup = renderToStaticMarkup(
832
+ wrapWithRootProviders(
833
+ React.createElement('forgewp-slot-content'),
834
+ DefaultLayoutComp,
835
+ ),
836
+ );
837
+ const slotMatch = layoutMarkup.match(
838
+ /([\s\S]*?)<forgewp-slot-content\s*(?:\/>|>[\s\S]*?<\/forgewp-slot-content>)([\s\S]*)/i,
839
+ );
840
+ if (slotMatch) {
841
+ headerHtml = slotMatch[1];
842
+ footerHtml = slotMatch[2];
843
+ if (headerHtml.trim() || footerHtml.trim()) {
844
+ if (VERBOSE)
845
+ console.warn(
846
+ `[ForgeWP Compiler] Extracted header and footer shells from layout.`,
847
+ );
848
+ }
849
+ }
850
+ }
851
+ } catch (e: any) {
852
+ console.warn(
853
+ `[ForgeWP Compiler] Layout slot extraction error: ${e.message}`,
854
+ );
855
+ }
856
+ } else {
857
+ // 2. Legacy fallback ONLY for older projects with no src/app/layouts or src/app/layout.tsx
858
+ let headerFile = '';
859
+ let headerCompName = '';
860
+
861
+ if (themeConfig.headerPath) {
862
+ const absolutePath = path.isAbsolute(themeConfig.headerPath)
863
+ ? themeConfig.headerPath
864
+ : path.join(themeRoot, themeConfig.headerPath);
865
+ if (existsSync(absolutePath)) {
866
+ headerFile = absolutePath;
867
+ headerCompName = path.basename(absolutePath, path.extname(absolutePath));
868
+ }
869
+ }
870
+
871
+ if (!headerFile) {
872
+ const headerFallbacks = [
873
+ 'src/components/SiteHeader.tsx',
874
+ 'src/components/Header.tsx',
875
+ 'src/components/Navbar.tsx',
876
+ 'src/components/NavBar.tsx',
877
+ 'src/components/Navigation.tsx',
878
+ 'src/components/layout/header.tsx',
879
+ 'src/components/layout/Header.tsx',
880
+ 'src/components/layout/navbar.tsx',
881
+ 'src/components/layout/Navbar.tsx',
882
+ 'src/components/layout/navigation.tsx',
883
+ 'src/components/layout/Navigation.tsx',
884
+ ];
885
+ for (const relPath of headerFallbacks) {
886
+ const p = path.join(themeRoot, relPath);
887
+ if (existsSync(p)) {
888
+ headerFile = p;
889
+ headerCompName = path.basename(p, path.extname(p));
890
+ break;
891
+ }
892
+ }
893
+ }
894
+
895
+ if (headerFile) {
896
+ try {
897
+ const headerUrl = pathToFileURL(headerFile).href;
898
+ const module = await import(headerUrl);
899
+ const HeaderComponent =
900
+ module[headerCompName] ||
901
+ module.default ||
902
+ Object.values(module).find((v) => typeof v === 'function');
903
+ if (!HeaderComponent) {
904
+ throw new Error(`${headerCompName} component not found in export.`);
905
+ }
906
+ headerHtml = renderToStaticMarkup(React.createElement(HeaderComponent));
907
+ } catch (err: any) {
908
+ console.error(
909
+ `\n[ForgeWP Compiler Error] Failed to load or render the Header component (${headerFile}).`,
910
+ );
911
+ console.error(`Error details: ${err.stack || err.message || err}\n`);
912
+ process.exit(1);
913
+ }
914
+ } else {
915
+ console.warn(
916
+ 'No separate Header component found, skipping separate header render',
917
+ );
918
+ }
919
+
920
+ let footerFile = '';
921
+ let footerCompName = '';
922
+
923
+ if (themeConfig.footerPath) {
924
+ const absolutePath = path.isAbsolute(themeConfig.footerPath)
925
+ ? themeConfig.footerPath
926
+ : path.join(themeRoot, themeConfig.footerPath);
927
+ if (existsSync(absolutePath)) {
928
+ footerFile = absolutePath;
929
+ footerCompName = path.basename(absolutePath, path.extname(absolutePath));
930
+ }
931
+ }
932
+
933
+ if (!footerFile) {
934
+ const footerFallbacks = [
935
+ 'src/components/SiteFooter.tsx',
936
+ 'src/components/Footer.tsx',
937
+ 'src/components/layout/footer.tsx',
938
+ 'src/components/layout/Footer.tsx',
939
+ ];
940
+ for (const relPath of footerFallbacks) {
941
+ const p = path.join(themeRoot, relPath);
942
+ if (existsSync(p)) {
943
+ footerFile = p;
944
+ footerCompName = path.basename(p, path.extname(p));
945
+ break;
946
+ }
947
+ }
948
+ }
949
+
950
+ if (footerFile) {
951
+ try {
952
+ const footerUrl = pathToFileURL(footerFile).href;
953
+ const module = await import(footerUrl);
954
+ const pascalFooter =
955
+ footerCompName.charAt(0).toUpperCase() + footerCompName.slice(1);
956
+ const FooterComponent =
957
+ module[footerCompName] ||
958
+ module[pascalFooter] ||
959
+ module.default ||
960
+ Object.values(module).find((v) => typeof v === 'function');
961
+ if (!FooterComponent) {
962
+ throw new Error(`${footerCompName} component not found in export.`);
963
+ }
964
+ footerHtml = renderToStaticMarkup(React.createElement(FooterComponent));
965
+ } catch (err: any) {
966
+ console.error(
967
+ `\n[ForgeWP Compiler Error] Failed to load or render the Footer component (${footerFile}).`,
968
+ );
969
+ console.error(`Error details: ${err.stack || err.message || err}\n`);
970
+ process.exit(1);
971
+ }
972
+ } else {
973
+ console.warn(
974
+ 'No separate Footer component found, skipping separate footer render',
975
+ );
976
+ }
977
+ }
978
+
979
+ // ── Render pages ──────────────────────────────────────────────────────────────
980
+ const appPagePath = path.join(themeRoot, 'src', 'app', 'page.tsx');
981
+ const appPageSource = existsSync(appPagePath)
982
+ ? readFileSync(appPagePath, 'utf8')
983
+ : '';
984
+ const routesPath = path.join(themeRoot, 'src', 'app', 'routes.tsx');
985
+ const routesSource = existsSync(routesPath)
986
+ ? readFileSync(routesPath, 'utf8')
987
+ : '';
988
+ const defaultLayout = await resolveLayoutComponent('default');
989
+ // Same decision local React makes in withLayout: a blank (or false) layout
990
+ // means this page rendered its own shell. Keep that tree intact so its
991
+ // state, refs, and animations run on WordPress. Do not guess from a
992
+ // component name.
993
+ const frontPageOwnsShell = layoutOwnsDocument(
994
+ resolveFrontPageLayout({
995
+ pageSource: appPageSource,
996
+ routesSource,
997
+ }),
998
+ );
999
+ const appHtml = renderPage(
1000
+ App,
1001
+ appPagePath,
1002
+ frontPageOwnsShell ? React.Fragment : defaultLayout,
1003
+ { ownsShell: frontPageOwnsShell },
1004
+ );
1005
+
1006
+ let layoutExtraHeadTags = '';
1007
+ const cleanAppHtml = appHtml.replace(
1008
+ /<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs,
1009
+ (match, childrenHtml) => {
1010
+ layoutExtraHeadTags += '\n' + childrenHtml;
1011
+ return '';
1012
+ },
1013
+ );
1014
+
1015
+ // ── Compile Dynamic WordPress Template Hierarchy ──────────────────────────────
1016
+ const layoutSeo = extractSeoPropsFromSource(layoutPath);
1017
+ let headHtml = buildHeadHtml(layoutSeo);
1018
+ const outDir = path.join(themeRoot, '.forgewp');
1019
+ mkdirSync(outDir, { recursive: true });
1020
+ if (existsSync(outDir)) {
1021
+ const existingFiles = readdirSync(outDir);
1022
+ for (const f of existingFiles) {
1023
+ if (
1024
+ (f.startsWith('template-') || f.startsWith('single-')) &&
1025
+ f.endsWith('.html')
1026
+ ) {
1027
+ try {
1028
+ unlinkSync(path.join(outDir, f));
1029
+ } catch {}
1030
+ }
1031
+ }
1032
+ }
1033
+
1034
+ const appDir = path.join(themeRoot, 'src', 'app');
1035
+ const templateDiscovery = discoverReactTemplates(themeRoot);
1036
+ if (existsSync(appDir)) {
1037
+ const { readdirSync } = require('node:fs');
1038
+ const files = templateDiscovery.roots;
1039
+ for (const file of files) {
1040
+ if (file.endsWith('.tsx')) {
1041
+ const name = file.replace('.tsx', '');
1042
+ const isWpTemplate =
1043
+ name === 'single' ||
1044
+ name === 'archive' ||
1045
+ name === '404' ||
1046
+ name === 'taxonomy' ||
1047
+ name.startsWith('single-') ||
1048
+ name.startsWith('taxonomy-') ||
1049
+ name.startsWith('archive-');
1050
+
1051
+ if (isWpTemplate) {
1052
+ const filePath = path.join(appDir, file);
1053
+ if (VERBOSE) {
1054
+ console.warn(
1055
+ `[ForgeWP Compiler] Attempting to compile template: ${file}`,
1056
+ );
1057
+ }
1058
+ try {
1059
+ const module = await import(pathToFileURL(filePath).href);
1060
+ const TemplateComponent = module.default;
1061
+ if (TemplateComponent) {
1062
+ forgeWpGlobal.__forgewpSsrQueries = {};
1063
+ let html = '';
1064
+ if (name === '404') {
1065
+ let pageEl = React.createElement(TemplateComponent);
1066
+ if (isComponentInteractive(filePath)) {
1067
+ const rootInfo = getComponentRootClassName(filePath);
1068
+ const wrapperProps: Record<string, any> = {
1069
+ 'data-forgewp-auto-island': '404',
1070
+ style: { display: 'contents' },
1071
+ };
1072
+ if (rootInfo.resolvable && rootInfo.className) {
1073
+ wrapperProps.className = rootInfo.className;
1074
+ }
1075
+ pageEl = React.createElement('div', wrapperProps, pageEl);
1076
+ }
1077
+ html = renderToStaticMarkup(pageEl);
1078
+ } else {
1079
+ html = renderPage(TemplateComponent, filePath);
1080
+ }
1081
+
1082
+ const ssrState = forgeWpGlobal.__forgewpSsrQueries || {};
1083
+ let stateScript = '';
1084
+ if (Object.keys(ssrState).length > 0) {
1085
+ stateScript = `\n<script id="forgewp-initial-state" type="application/json">${JSON.stringify({ queries: ssrState })}</script>`;
1086
+ }
1087
+
1088
+ let extraHeadTags = '';
1089
+ const cleanHtml = html.replace(
1090
+ /<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs,
1091
+ (match, childrenHtml) => {
1092
+ extraHeadTags += '\n' + childrenHtml;
1093
+ return '';
1094
+ },
1095
+ );
1096
+
1097
+ const finalHtml = cleanHtml + stateScript;
1098
+ writeFileSync(path.join(outDir, `${name}.html`), finalHtml, 'utf8');
1099
+ console.warn(`[ForgeWP Templates] src/app/${file} -> ${name}.php (WordPress hierarchy; URL follows WordPress routing).`);
1100
+ console.warn(`[ForgeWP Compiler] WROTE ${name}.html to ${outDir}`);
1101
+
1102
+ const seoProps = extractSeoPropsFromSource(filePath);
1103
+ let customHeadHtml = buildHeadHtml(layoutSeo, seoProps);
1104
+ if (extraHeadTags) {
1105
+ customHeadHtml += '\n' + extraHeadTags;
1106
+ }
1107
+ writeFileSync(
1108
+ path.join(outDir, `${name}-head.html`),
1109
+ customHeadHtml,
1110
+ 'utf8',
1111
+ );
1112
+ console.warn(
1113
+ `[ForgeWP Compiler] WROTE ${name}-head.html to ${outDir}`,
1114
+ );
1115
+ }
1116
+ } catch (e: any) {
1117
+ console.warn(
1118
+ `[ForgeWP Compiler Warning] Failed to render WP template ${file}:`,
1119
+ e.message,
1120
+ );
1121
+ }
1122
+ }
1123
+ }
1124
+ }
1125
+ }
1126
+
1127
+ // ── Write outputs ─────────────────────────────────────────────────────────────
1128
+
1129
+ writeFileSync(path.join(outDir, 'header.html'), headerHtml, 'utf8');
1130
+ writeFileSync(path.join(outDir, 'footer.html'), footerHtml, 'utf8');
1131
+ writeFileSync(path.join(outDir, 'app.html'), cleanAppHtml, 'utf8');
1132
+ let finalHeadHtml = headHtml;
1133
+ if (layoutExtraHeadTags) {
1134
+ finalHeadHtml += '\n' + layoutExtraHeadTags;
1135
+ }
1136
+ writeFileSync(path.join(outDir, 'head.html'), finalHeadHtml, 'utf8');
1137
+
1138
+ // ── Compile Custom Page Templates ──────────────────────────────────────────────
1139
+ const pagesDir = path.join(themeRoot, 'src', 'app', 'pages');
1140
+ if (VERBOSE) {
1141
+ console.warn(
1142
+ 'CHECKING PAGES DIR: ' + pagesDir + ' EXISTS: ' + existsSync(pagesDir),
1143
+ );
1144
+ }
1145
+ if (existsSync(pagesDir)) {
1146
+ const { readdirSync } = require('node:fs');
1147
+ const pages = templateDiscovery.pages;
1148
+
1149
+ for (const pageFile of pages) {
1150
+ const pagePath = path.join(pagesDir, pageFile);
1151
+ if (VERBOSE) {
1152
+ console.warn(`Attempting to compile template: ${pageFile}`);
1153
+ }
1154
+ try {
1155
+ const module = await import(pathToFileURL(pagePath).href);
1156
+ const discoveryConfig = module.pageConfig && typeof module.pageConfig === 'object' ? module.pageConfig : {};
1157
+ const intent = resolvePageTemplateIntent(pageFile, discoveryConfig);
1158
+ if (intent.kind === 'component') {
1159
+ console.warn(pageTemplateDiagnostic(`src/app/pages/${pageFile}`, intent, discoveryConfig));
1160
+ continue;
1161
+ }
1162
+ const CustomPage = module.default || Object.values(module)[0];
1163
+ if (CustomPage) {
1164
+ forgeWpGlobal.__forgewpSsrQueries = {};
1165
+ const pageConfig =
1166
+ module.pageConfig && typeof module.pageConfig === 'object'
1167
+ ? module.pageConfig
1168
+ : {};
1169
+ const { slug, singleSlug } = intent;
1170
+ const isPostTypeSingle = intent.kind === 'single';
1171
+
1172
+ // Dynamically discover a representative sample item for this post type
1173
+ // so SSR renders a rich, complete preview skeleton instead of a not-found fallback
1174
+ let sampleSlug = '';
1175
+ let samplePost: any = null;
1176
+ if (isPostTypeSingle) {
1177
+ try {
1178
+ if (singleSlug === 'product') {
1179
+ const products = loadProductsData(themeRoot);
1180
+ if (Array.isArray(products) && products.length > 0) {
1181
+ samplePost = products[0];
1182
+ sampleSlug = products[0].slug || '';
1183
+ }
1184
+ }
1185
+ if (!sampleSlug) {
1186
+ const mockData = loadMockData(themeRoot);
1187
+ if (
1188
+ mockData &&
1189
+ Array.isArray(mockData[singleSlug]) &&
1190
+ mockData[singleSlug].length > 0
1191
+ ) {
1192
+ samplePost = mockData[singleSlug][0];
1193
+ sampleSlug = mockData[singleSlug][0].slug || '';
1194
+ }
1195
+ }
1196
+ } catch {}
1197
+ }
1198
+
1199
+ if (sampleSlug) {
1200
+ if (globalThis.window && globalThis.window.location) {
1201
+ (globalThis.window.location as any).pathname =
1202
+ `/${singleSlug}/${sampleSlug}`;
1203
+ }
1204
+ if (globalThis.location) {
1205
+ (globalThis.location as any).pathname =
1206
+ `/${singleSlug}/${sampleSlug}`;
1207
+ }
1208
+ (globalThis.window as any).forgeWpHydration = {
1209
+ post: samplePost
1210
+ ? { id: samplePost.id || 1, slug: sampleSlug, ...samplePost }
1211
+ : { id: 1, slug: sampleSlug },
1212
+ };
1213
+ } else {
1214
+ if (globalThis.window && globalThis.window.location) {
1215
+ (globalThis.window.location as any).pathname = `/${slug}`;
1216
+ }
1217
+ if (globalThis.location) {
1218
+ (globalThis.location as any).pathname = `/${slug}`;
1219
+ }
1220
+ (globalThis.window as any).forgeWpHydration = undefined;
1221
+ }
1222
+
1223
+ const LayoutComponent = await resolveLayoutComponent(pageConfig.layout);
1224
+ const customHtml = renderPage(CustomPage, pagePath, LayoutComponent);
1225
+ const ssrState = forgeWpGlobal.__forgewpSsrQueries || {};
1226
+ let stateScript = '';
1227
+ if (Object.keys(ssrState).length > 0) {
1228
+ stateScript = `\n<script id="forgewp-initial-state" type="application/json">${JSON.stringify({ queries: ssrState })}</script>`;
1229
+ }
1230
+
1231
+ let customExtraHeadTags = '';
1232
+ const cleanCustomHtml = customHtml.replace(
1233
+ /<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs,
1234
+ (match, childrenHtml) => {
1235
+ customExtraHeadTags += '\n' + childrenHtml;
1236
+ return '';
1237
+ },
1238
+ );
1239
+
1240
+ let finalHtml = cleanCustomHtml + stateScript;
1241
+ if (pageConfig.protected) {
1242
+ const allowedAttr = pageConfig.allowed
1243
+ ? ` allowed="${pageConfig.allowed}"`
1244
+ : '';
1245
+ const redirectAttr = pageConfig.redirect
1246
+ ? ` redirect="${pageConfig.redirect}"`
1247
+ : '';
1248
+ finalHtml =
1249
+ `<forgewp-require-auth${allowedAttr}${redirectAttr}></forgewp-require-auth>` +
1250
+ finalHtml;
1251
+ }
1252
+
1253
+ const pageConfigAttrs: string[] = [];
1254
+ if (pageConfig.header !== undefined)
1255
+ pageConfigAttrs.push(`header="${pageConfig.header}"`);
1256
+ if (pageConfig.footer !== undefined)
1257
+ pageConfigAttrs.push(`footer="${pageConfig.footer}"`);
1258
+ if (pageConfig.layout !== undefined)
1259
+ pageConfigAttrs.push(`layout="${pageConfig.layout}"`);
1260
+
1261
+ if (pageConfigAttrs.length > 0) {
1262
+ finalHtml =
1263
+ `<forgewp-page-config ${pageConfigAttrs.join(' ')}></forgewp-page-config>` +
1264
+ finalHtml;
1265
+ }
1266
+
1267
+ const customSeo = extractSeoPropsFromSource(pagePath);
1268
+ let customHeadHtml = buildHeadHtml(layoutSeo, customSeo);
1269
+ if (customExtraHeadTags) {
1270
+ customHeadHtml += '\n' + customExtraHeadTags;
1271
+ }
1272
+ writePageTemplateCache(outDir, intent, finalHtml, customHeadHtml);
1273
+ console.warn(pageTemplateDiagnostic(`src/app/pages/${pageFile}`, intent, discoveryConfig, templateDiscovery.importers.get(pageFile)));
1274
+ }
1275
+ } catch (e: any) {
1276
+ console.warn(`Failed to render custom page ${pageFile}:`, e.message);
1277
+ }
1278
+ }
1279
+ }
1280
+
1281
+ // ── Compile Declared Routes from routes.tsx ────────────────────────────────────
1282
+ const routesFile = path.join(themeRoot, 'src', 'app', 'routes.tsx');
1283
+ if (existsSync(routesFile)) {
1284
+ try {
1285
+ const routesSource = readFileSync(routesFile, 'utf8');
1286
+ const routesModule = await import(pathToFileURL(routesFile).href);
1287
+ const AppRoutes =
1288
+ routesModule.default ||
1289
+ Object.values(routesModule).find((v) => typeof v === 'function');
1290
+
1291
+ let RouterComp: any = null;
1292
+ try {
1293
+ const forgewpReactPath = require.resolve('@forgewp/react');
1294
+ const forgewpReact = await import(pathToFileURL(forgewpReactPath).href);
1295
+ RouterComp = forgewpReact.Router || forgewpReact.default?.Router;
1296
+ } catch {
1297
+ try {
1298
+ const forgewpReact = require('@forgewp/react');
1299
+ RouterComp = forgewpReact.Router || forgewpReact.default?.Router;
1300
+ } catch {}
1301
+ }
1302
+
1303
+ if (AppRoutes) {
1304
+ const staticRouteSlugs = new Set<string>();
1305
+ for (const route of collectStaticRouteDefinitions(routesSource)) {
1306
+ const raw = route.path.replace(/^\/+|\/+$/g, '');
1307
+ if (raw && !raw.includes(':') && !raw.includes('*')) {
1308
+ staticRouteSlugs.add(raw);
1309
+ }
1310
+ }
1311
+
1312
+ for (const slug of staticRouteSlugs) {
1313
+ const templateSlug = slug.replace(/\//g, '-');
1314
+ const outTemplateFile = path.join(
1315
+ outDir,
1316
+ `template-${templateSlug}.html`,
1317
+ );
1318
+ // If template was already compiled by a dedicated page file, do not overwrite
1319
+ if (existsSync(outTemplateFile)) continue;
1320
+
1321
+ // Skip reserved system paths
1322
+ const reservedRoots = new Set([
1323
+ 'product',
1324
+ 'products',
1325
+ 'category',
1326
+ 'categories',
1327
+ 'search',
1328
+ 'wp-admin',
1329
+ 'wp-json',
1330
+ 'wp-content',
1331
+ 'wp-includes',
1332
+ ]);
1333
+ if (reservedRoots.has(slug) || reservedRoots.has(templateSlug))
1334
+ continue;
1335
+
1336
+ try {
1337
+ forgeWpGlobal.__forgewpSsrQueries = {};
1338
+ if (globalThis.window && globalThis.window.location) {
1339
+ (globalThis.window.location as any).pathname = '/' + slug;
1340
+ }
1341
+ if (globalThis.location) {
1342
+ (globalThis.location as any).pathname = '/' + slug;
1343
+ }
1344
+
1345
+ let routeElement: any;
1346
+ if (RouterComp) {
1347
+ routeElement = React.createElement(
1348
+ RouterComp,
1349
+ { location: '/' + slug },
1350
+ React.createElement(AppRoutes),
1351
+ );
1352
+ } else {
1353
+ routeElement = React.createElement(AppRoutes);
1354
+ }
1355
+
1356
+ const pageBoundary = React.createElement(
1357
+ 'forgewp-content-boundary',
1358
+ null,
1359
+ routeElement,
1360
+ );
1361
+ const customHtml = renderToStaticMarkup(
1362
+ wrapWithRootProviders(pageBoundary, RootLayout),
1363
+ );
1364
+
1365
+ const ssrState = forgeWpGlobal.__forgewpSsrQueries || {};
1366
+ let stateScript = '';
1367
+ if (Object.keys(ssrState).length > 0) {
1368
+ stateScript = `\n<script id="forgewp-initial-state" type="application/json">${JSON.stringify({ queries: ssrState })}</script>`;
1369
+ }
1370
+
1371
+ let customExtraHeadTags = '';
1372
+ const cleanCustomHtml = customHtml.replace(
1373
+ /<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs,
1374
+ (match: string, childrenHtml: string) => {
1375
+ customExtraHeadTags += '\n' + childrenHtml;
1376
+ return '';
1377
+ },
1378
+ );
1379
+
1380
+ const finalHtml = cleanCustomHtml + stateScript;
1381
+ writeFileSync(outTemplateFile, finalHtml, 'utf8');
1382
+ if (VERBOSE) {
1383
+ console.warn(
1384
+ `WROTE template-${templateSlug}.html from routes.tsx to ${outDir}`,
1385
+ );
1386
+ }
1387
+
1388
+ let customHeadHtml = buildHeadHtml(layoutSeo, {});
1389
+ if (customExtraHeadTags) {
1390
+ customHeadHtml += '\n' + customExtraHeadTags;
1391
+ }
1392
+ writeFileSync(
1393
+ path.join(outDir, `template-${templateSlug}-head.html`),
1394
+ customHeadHtml,
1395
+ 'utf8',
1396
+ );
1397
+ } catch (routeErr: any) {
1398
+ console.warn(
1399
+ `Failed to render route /${slug} from routes.tsx:`,
1400
+ routeErr.message,
1401
+ );
1402
+ }
1403
+ }
1404
+ }
1405
+ } catch (e: any) {
1406
+ console.warn(`Failed to load routes.tsx for route SSR:`, e.message);
1407
+ }
1408
+ }
1409
+
1410
+ process.stdout.write(outDir);