@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
@@ -11,7 +11,13 @@ import fs, {
11
11
  } from 'node:fs';
12
12
  import path from 'node:path';
13
13
  import { fileURLToPath, pathToFileURL } from 'node:url';
14
- import { scanForEditableSchemas } from './hydration-scanner.js';
14
+ import { createRequire } from 'node:module';
15
+ import {
16
+ scanForEditableSchemas,
17
+ scanForHydrationIslandsWithProps,
18
+ resolveIslandChunk,
19
+ scanAppProviders,
20
+ } from './hydration/index.js';
15
21
  import { loadFrameworkAdapter } from './framework-adapter.js';
16
22
  import {
17
23
  analyzeHydrationIslands,
@@ -29,9 +35,30 @@ import {
29
35
  build404Php,
30
36
  buildArchivePhp,
31
37
  buildPagePhp,
38
+ buildPlaceholderPagePhp,
39
+ buildBuilderPagePhp,
40
+ buildGeneratedPageTemplateContentPhp,
41
+ LINK_RESET_CSS,
32
42
  } from './php-builders.js';
33
- import { buildFunctionsPhp } from './functions-builder.js';
34
- import { compileBlocks } from './block-compiler.js';
43
+ import { collectFallbackPageRoutes } from './collect-static-routes.js';
44
+ import { collectPageTemplateRoutes } from './collect-page-template-routes.js';
45
+ import { buildFunctionsPhp } from './functions/index.js';
46
+ import { loadMenusData } from './functions/load-menus.js';
47
+ import {
48
+ loadTranslationsData,
49
+ translationsSourcePath,
50
+ } from './functions/load-translations.js';
51
+ import { lintFormsUsage } from './functions/forms.js';
52
+ import { buildSettingsPagePhp } from './functions/settings-page.js';
53
+ import { compileBlocks, warmupIconCache } from './blocks/index.js';
54
+ import { findHtmlTagEnd } from './blocks/shared-utils.js';
55
+ import {
56
+ buildEditorIconRegistry,
57
+ FORGEWP_DEFAULT_ICON_SLUGS,
58
+ } from './icon-registry.js';
59
+ import { scanAssetGraph, generatePreloadTags } from './assets/index.js';
60
+ import { rewriteThemePublicAssetUrls } from './assets/public-url.js';
61
+ import { extractTemplateContent } from './extract-template-content.js';
35
62
 
36
63
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
37
64
 
@@ -46,7 +73,14 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
46
73
  * @param {string} options.appHtml
47
74
  * @param {string} [options.headerHtml]
48
75
  * @param {string} [options.footerHtml]
76
+ * @param {string} [options.headHtml]
77
+ * @param {string} [options.singleHeadHtml]
78
+ * @param {string} [options.singleHtml]
79
+ * @param {string} [options.notFoundHtml]
80
+ * @param {string} [options.archiveHtml]
49
81
  * @param {import('./types.js').ForgeWPBuildAssets} options.assets
82
+ * @param {boolean} [options.strict] Fail export on editable from/pick issues
83
+ * @param {boolean} [options.preserveOutDir] Keep assets already generated in the output directory
50
84
  */
51
85
  export async function generateTheme({
52
86
  themeRoot,
@@ -61,15 +95,62 @@ export async function generateTheme({
61
95
  notFoundHtml = '',
62
96
  archiveHtml = '',
63
97
  assets,
98
+ assetGraph,
99
+ preserveOutDir = false,
100
+ strict = false,
64
101
  }) {
65
- if (existsSync(outDir)) {
102
+ if (!preserveOutDir && existsSync(outDir)) {
66
103
  rmSync(outDir, { recursive: true, force: true });
67
104
  }
68
105
 
69
106
  mkdirSync(outDir, { recursive: true });
107
+ const effectiveAssetGraph = assetGraph || scanAssetGraph(themeRoot);
108
+
109
+ // Pre-warm the icon library cache asynchronously to speed up block transpilation
110
+ await warmupIconCache(themeRoot);
70
111
 
71
112
  const schemas = scanForEditableSchemas(themeRoot);
72
- console.log(`[ForgeWP Compiler] Discovered colocated editable schemas for templates: ${Object.keys(schemas).join(', ') || '<none>'}`);
113
+ if (process.env.FORGEWP_VERBOSE === '1')
114
+ console.log(
115
+ `[ForgeWP Compiler] Discovered colocated editable schemas for templates: ${Object.keys(schemas).join(', ') || '<none>'}`,
116
+ );
117
+
118
+ // Real richText-ness per field key, from the actual editable schema type —
119
+ // used by processMarkup instead of guessing from the key name (a field
120
+ // like hero_subtitle declared as text() must not be wpautop-wrapped just
121
+ // because its key happens to contain "subtitle").
122
+ //
123
+ // Different templates' schemas can independently reuse the same key name
124
+ // (e.g. both front-page.ts and ber-uns-page.ts declare "hero_subtitle",
125
+ // one as text() and the other as richText()) — a single flat, merged Set
126
+ // would misclassify whichever template DIDN'T mean it as rich text. Where
127
+ // the template is known, getRichTextKeysForSlug() below scopes the check
128
+ // to that one schema. Where it isn't (shared header/footer/404/archive
129
+ // markup), richTextFieldKeys excludes any key that's ambiguous across
130
+ // templates — safer to under-format a rare cross-template collision than
131
+ // to wpautop-wrap a plain field and break its styling.
132
+ const richTextFieldKeysBySlug = {};
133
+ const textOnlyKeysAnywhere = new Set();
134
+ const richTextKeysAnywhere = new Set();
135
+ for (const [slug, schema] of Object.entries(schemas)) {
136
+ const slugSet = new Set();
137
+ for (const [key, field] of Object.entries(schema)) {
138
+ if (!field) continue;
139
+ if (field.type === 'richText') {
140
+ slugSet.add(key);
141
+ richTextKeysAnywhere.add(key);
142
+ } else if (field.type === 'text') {
143
+ textOnlyKeysAnywhere.add(key);
144
+ }
145
+ }
146
+ richTextFieldKeysBySlug[slug] = slugSet;
147
+ }
148
+ const richTextFieldKeys = new Set(
149
+ [...richTextKeysAnywhere].filter((key) => !textOnlyKeysAnywhere.has(key)),
150
+ );
151
+ function getRichTextKeysForSlug(slug) {
152
+ return richTextFieldKeysBySlug[slug] || richTextFieldKeys;
153
+ }
73
154
 
74
155
  // Load project-specific compiler hooks if they exist in theme src
75
156
  let projectHooks = null;
@@ -77,25 +158,29 @@ export async function generateTheme({
77
158
  if (existsSync(hooksPath)) {
78
159
  console.warn(
79
160
  '\x1b[33m%s\x1b[0m',
80
- '⚠️ [ForgeWP Deprecation Warning]: "compiler-hooks.js" is deprecated. Please migrate custom PHP logic to "src/server/*.php" files.'
161
+ '⚠️ [ForgeWP Deprecation Warning]: "compiler-hooks.js" is deprecated. Please migrate custom PHP logic to "src/server/*.php" files.',
81
162
  );
82
163
  try {
83
164
  const fileUrl = pathToFileURL(hooksPath).href;
84
165
  projectHooks = await import(fileUrl);
85
166
  } catch (e) {
86
- console.warn('[ForgeWP Compiler] Failed to import project compiler hooks:', e.message);
167
+ console.warn(
168
+ '[ForgeWP Compiler] Failed to import project compiler hooks:',
169
+ e.message,
170
+ );
87
171
  }
88
172
  }
89
173
 
90
- // Load menus configuration for auto-registration and setup
91
- let menus = {};
92
- const menusJsonSrc = path.join(themeRoot, 'cms', 'menus.json');
93
- if (existsSync(menusJsonSrc)) {
94
- try {
95
- menus = JSON.parse(readFileSync(menusJsonSrc, 'utf8'));
96
- } catch (e) {
97
- console.warn('Failed to parse menus.json:', e.message);
98
- }
174
+ // Prefer cms/menus.ts (defineWpMenus); fall back to legacy cms/menus.json.
175
+ const menus = loadMenusData(themeRoot);
176
+ const loadedMenuLocations = Object.keys(menus).filter(
177
+ (k) => !k.startsWith('_'),
178
+ );
179
+ if (loadedMenuLocations.length > 0) {
180
+ if (process.env.FORGEWP_VERBOSE === '1')
181
+ console.log(
182
+ `[ForgeWP Compiler] Nav menu locations: ${loadedMenuLocations.join(', ')}`,
183
+ );
99
184
  }
100
185
 
101
186
  // Merge static menu definitions from defineTheme/wp.config.ts config.menus
@@ -107,97 +192,132 @@ export async function generateTheme({
107
192
  }
108
193
  }
109
194
 
110
- // Gather compiled custom page templates for auto-creation with smart slug mapping
111
- const pagesToAutoCreate = [];
112
- const pageTemplateSlugs = [];
195
+ // Map compiled Page templates to menu paths, including nested menu items.
113
196
  const forgewpDir = path.join(themeRoot, '.forgewp');
114
- if (existsSync(forgewpDir)) {
115
- const templateFiles = readdirSync(forgewpDir);
116
- for (const file of templateFiles) {
117
- if (
118
- file.startsWith('template-') &&
119
- file.endsWith('.html') &&
120
- !file.includes('-head')
121
- ) {
122
- const slug = file.replace('.html', '');
123
- const pageTemplateSlug = slug.replace('template-', '');
124
- pageTemplateSlugs.push(pageTemplateSlug);
125
-
126
- let matchedSlug = null;
127
- let matchedTitle = null;
128
-
129
- const toKebabTemplateSlug = (str) => {
130
- const compName =
131
- str
132
- .replace(/[^a-zA-Z0-9]/g, ' ')
133
- .trim()
134
- .split(/\s+/)
135
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
136
- .join('') + 'Page';
137
- return compName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
138
- };
139
-
140
- const targetKebab = pageTemplateSlug;
141
-
142
- // Search in menus to find matching target URL slugs defined by the developer
143
- for (const [location, items] of Object.entries(menus)) {
144
- if (!Array.isArray(items)) continue;
145
- for (const item of items) {
146
- if (!item.url || !item.url.startsWith('/')) continue;
147
- const menuUrlSlug = item.url.replace(/^\//, '');
148
-
149
- if (
150
- toKebabTemplateSlug(item.title) === targetKebab ||
151
- toKebabTemplateSlug(menuUrlSlug) === targetKebab
152
- ) {
153
- matchedSlug = menuUrlSlug;
154
- matchedTitle = item.title;
155
- break;
156
- }
157
- }
158
- if (matchedSlug) break;
159
- }
160
-
161
- // Fallback 1: Strip trailing "-page" from template slug
162
- if (!matchedSlug) {
163
- matchedSlug = pageTemplateSlug.endsWith('-page')
164
- ? pageTemplateSlug.slice(0, -5)
165
- : pageTemplateSlug;
166
- }
167
-
168
- // Fallback 2: Generate clean human-readable title
169
- if (!matchedTitle) {
170
- const cleanName = pageTemplateSlug.endsWith('-page')
171
- ? pageTemplateSlug.slice(0, -5)
172
- : pageTemplateSlug;
173
- matchedTitle = cleanName
174
- .split('-')
175
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
176
- .join(' ');
177
- }
197
+ const pageTemplateSlugs = existsSync(forgewpDir)
198
+ ? readdirSync(forgewpDir)
199
+ .filter(
200
+ (file) =>
201
+ file.startsWith('template-') &&
202
+ file.endsWith('.html') &&
203
+ !file.includes('-head'),
204
+ )
205
+ .map((file) => file.replace(/^template-|\.html$/g, ''))
206
+ : [];
207
+ const pagesToAutoCreate = collectPageTemplateRoutes(pageTemplateSlugs, menus);
178
208
 
179
- pagesToAutoCreate.push({
180
- title: matchedTitle,
181
- slug: matchedSlug,
182
- template: `page-${pageTemplateSlug}.php`,
183
- });
184
- }
185
- }
209
+ // Menu + routes.tsx paths that have no compiled template still need a WP page,
210
+ // or redirect_canonical will steal similar CPT slugs (about → about-a-chair).
211
+ let routesSource = '';
212
+ const routesPath = path.join(themeRoot, 'src', 'app', 'routes.tsx');
213
+ if (existsSync(routesPath)) {
214
+ try {
215
+ routesSource = readFileSync(routesPath, 'utf8');
216
+ } catch {}
217
+ }
218
+ const fallbackPages = collectFallbackPageRoutes({
219
+ menus,
220
+ routesSource,
221
+ existingSlugs: pagesToAutoCreate.map((p) => p.slug),
222
+ });
223
+ for (const page of fallbackPages) {
224
+ pagesToAutoCreate.push(page);
225
+ }
226
+ if (fallbackPages.length > 0) {
227
+ if (process.env.FORGEWP_VERBOSE === '1')
228
+ console.log(
229
+ `[ForgeWP Compiler] Coming-next pages for unmatched routes: ${fallbackPages.map((p) => '/' + p.slug).join(', ')}`,
230
+ );
186
231
  }
187
232
 
188
233
  const adapter = await loadFrameworkAdapter(config.frameworkAdapter);
189
234
  const scanForHydrationIslands =
190
235
  adapter.scanForHydrationIslands || adapter.default?.scanForHydrationIslands;
191
236
 
237
+ const layoutProviders = scanAppProviders(themeRoot);
192
238
  const hydrationIslands = scanForHydrationIslands
193
239
  ? scanForHydrationIslands(themeRoot)
194
240
  : [];
241
+ for (const provider of layoutProviders) {
242
+ if (!hydrationIslands.includes(provider.kebab)) {
243
+ hydrationIslands.push(provider.kebab);
244
+ }
245
+ }
195
246
  const hasHydration = hydrationIslands.length > 0;
196
247
 
248
+ // Collect Smart Discovery islands (auto-detected interactive components with no explicit <Hydrate> wrapper)
249
+ const detailedIslands = scanForHydrationIslandsWithProps(themeRoot);
250
+ const autoIslands = detailedIslands.filter((i) => i.smartDiscovered);
251
+
252
+ /**
253
+ * Post-process SSR HTML to convert data-forgewp-auto-island divs (injected by the
254
+ * React.createElement patch in render-theme.mts) into proper data-forgewp-hydrate
255
+ * hydration island wrappers that the browser micro-hydrator can activate.
256
+ *
257
+ * @param {string} html
258
+ * @returns {string}
259
+ */
260
+ function injectAutoHydrationMarkers(html) {
261
+ if (!html) return html;
262
+ // Replace data-forgewp-auto-island="name" with data-forgewp-hydrate="name"
263
+ // + trigger + data-forgewp-props. The real props (e.g. searchPlaceholder)
264
+ // are carried by a render-theme.mts-emitted data-forgewp-auto-island-props
265
+ // attribute on the SAME div.
266
+ //
267
+ // Can't find the tag's end with a naive `[^>]*"...">` regex: the props
268
+ // attribute's JSON value can itself contain an already-embedded
269
+ // `<?php ... ?>` snippet (e.g. a meta-value marker resolved earlier by
270
+ // processMarkup), and PHP's own `?>` closer contains a literal `>` that
271
+ // a bare negated-character-class scan can't tell apart from the real
272
+ // tag-closing `>` — it would cut the match off mid-attribute. Reuse
273
+ // findHtmlTagEnd (blocks/shared-utils.js), which already tracks
274
+ // <?php ?> spans and quoted strings to find the tag's true end.
275
+ // The SSR emits: <div data-forgewp-auto-island="hero-section" style="display:contents" data-forgewp-auto-island-props="{&quot;searchPlaceholder&quot;:&quot;...&quot;}">...</div>
276
+ // We need: <div data-forgewp-hydrate="hero-section" data-forgewp-trigger="visible" data-forgewp-props="{&quot;searchPlaceholder&quot;:&quot;...&quot;}" style="display:contents">...</div>
277
+ const autoIslandMap = new Map(
278
+ autoIslands.map((i) => [i.name, i.trigger || 'visible']),
279
+ );
280
+ const marker = 'data-forgewp-auto-island="';
281
+ let result = '';
282
+ let cursor = 0;
283
+ while (true) {
284
+ const markerIdx = html.indexOf(marker, cursor);
285
+ if (markerIdx === -1) {
286
+ result += html.slice(cursor);
287
+ break;
288
+ }
289
+ const tagStart = html.lastIndexOf('<div', markerIdx);
290
+ const tagEnd = tagStart !== -1 ? findHtmlTagEnd(html, tagStart) : -1;
291
+ if (tagStart === -1 || tagEnd === -1) {
292
+ // Shouldn't happen; skip past this occurrence rather than loop forever.
293
+ result += html.slice(cursor, markerIdx + marker.length);
294
+ cursor = markerIdx + marker.length;
295
+ continue;
296
+ }
297
+ result += html.slice(cursor, tagStart);
298
+ const attrsStr = html.slice(tagStart + 4, tagEnd); // strip leading "<div" and trailing ">"
299
+ const kebabMatch = attrsStr.match(/data-forgewp-auto-island="([^"]+)"/);
300
+ const kebab = kebabMatch ? kebabMatch[1] : '';
301
+ const propsMatch = attrsStr.match(
302
+ /data-forgewp-auto-island-props="([^"]*)"/,
303
+ );
304
+ const propsValue = propsMatch ? propsMatch[1] : '{}';
305
+ const trigger = autoIslandMap.get(kebab) || 'visible';
306
+ const restAttrs = attrsStr
307
+ .replace(/\s*data-forgewp-auto-island="[^"]*"/, '')
308
+ .replace(/\s*data-forgewp-auto-island-props="[^"]*"/, '')
309
+ .trim();
310
+ result += `<div data-forgewp-hydrate="${kebab}" data-forgewp-trigger="${trigger}" data-forgewp-props="${propsValue}"${restAttrs ? ' ' + restAttrs : ''}>`;
311
+ cursor = tagEnd + 1;
312
+ }
313
+ return result;
314
+ }
315
+
197
316
  const assetsOut = path.join(outDir, 'assets');
198
317
  const distAssets = path.join(themeRoot, 'dist', 'assets');
199
318
  mkdirSync(assetsOut, { recursive: true });
200
319
  cpSync(distAssets, assetsOut, { recursive: true });
320
+ rewriteThemePublicAssetUrls(themeRoot, assetsOut);
201
321
 
202
322
  // Copy all other files/folders from dist to outDir (excluding .vite, index.html, and assets)
203
323
  const distDir = path.join(themeRoot, 'dist');
@@ -224,16 +344,20 @@ export async function generateTheme({
224
344
 
225
345
  const replaceAssetPlaceholders = (markup) => {
226
346
  if (!markup) return '';
227
- return markup.replace(/__FORGEWP_ASSET__([a-zA-Z0-9_\-\.\/]+)/g, (match, srcPath) => {
228
- const manifestEntry = viteManifest[srcPath];
229
- if (manifestEntry && manifestEntry.file) {
230
- return `<?php echo esc_url( get_template_directory_uri() ); ?>/${manifestEntry.file}`;
231
- }
232
- return `<?php echo esc_url( get_template_directory_uri() ); ?>/${srcPath}`;
233
- });
347
+ return markup.replace(
348
+ /__FORGEWP_ASSET__([a-zA-Z0-9_\-\.\/]+)/g,
349
+ (match, srcPath) => {
350
+ const manifestEntry = viteManifest[srcPath];
351
+ if (manifestEntry && manifestEntry.file) {
352
+ return `<?php echo esc_url( get_template_directory_uri() ); ?>/${manifestEntry.file}`;
353
+ }
354
+ return `<?php echo esc_url( get_template_directory_uri() ); ?>/${srcPath}`;
355
+ },
356
+ );
234
357
  };
235
358
 
236
359
  let hydrationManifestJson = '{}';
360
+ let hydrationData = null;
237
361
  if (hasHydration) {
238
362
  if (!existsSync(manifestPath)) {
239
363
  console.warn(
@@ -251,28 +375,7 @@ export async function generateTheme({
251
375
  }
252
376
 
253
377
  for (const island of hydrationIslands) {
254
- const pascalName = island
255
- .split('-')
256
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
257
- .join('');
258
-
259
- let resolvedChunk = null;
260
- for (const [key, value] of Object.entries(viteManifest)) {
261
- const fileBasename = path.basename(value.file || '');
262
- const cleanName = fileBasename.replace(/-[A-Za-z0-9_-]+\.js$/, '');
263
- if (
264
- key.endsWith(`/${pascalName}.tsx`) ||
265
- key.endsWith(`/${pascalName}.ts`) ||
266
- key.endsWith(`/${island}.tsx`) ||
267
- key.endsWith(`/${island}.ts`) ||
268
- cleanName === island ||
269
- cleanName === pascalName.toLowerCase()
270
- ) {
271
- resolvedChunk = value.file;
272
- break;
273
- }
274
- }
275
-
378
+ const resolvedChunk = resolveIslandChunk(viteManifest, island);
276
379
  if (resolvedChunk) {
277
380
  mapping[island] = resolvedChunk;
278
381
  }
@@ -294,15 +397,48 @@ export async function generateTheme({
294
397
  );
295
398
  }
296
399
 
400
+ const providerIdsJson = JSON.stringify(layoutProviders.map((p) => p.kebab));
297
401
  const hydratorScript = `(function () {
298
402
  const config = window.forgeWpHydration || { themeUri: "", manifest: {} };
299
- const islands = document.querySelectorAll("[data-forgewp-hydrate]");
403
+ if (!config.providers) config.providers = ${providerIdsJson};
404
+ const allIslands = document.querySelectorAll("[data-forgewp-hydrate]");
405
+ // An outer island re-renders its own children. Hydrating a nested marker
406
+ // as well would mount that child twice and drop state the parent owns
407
+ // (a scroll observer, shared motion props, a ref). The outermost marker wins.
408
+ const islands = Array.prototype.filter.call(allIslands, function (el) {
409
+ let parent = el.parentElement;
410
+ while (parent) {
411
+ if (parent.hasAttribute && parent.hasAttribute("data-forgewp-hydrate")) return false;
412
+ parent = parent.parentElement;
413
+ }
414
+ return true;
415
+ });
416
+
417
+ function firstObservableBox(el) {
418
+ if (!el || el.nodeType !== 1) return null;
419
+ try {
420
+ const display = window.getComputedStyle(el).display;
421
+ if (display !== "contents") return el;
422
+ } catch (e) {
423
+ return el;
424
+ }
425
+ for (let i = 0; i < el.children.length; i++) {
426
+ const found = firstObservableBox(el.children[i]);
427
+ if (found) return found;
428
+ }
429
+ return null;
430
+ }
300
431
 
301
432
  const observer = new IntersectionObserver((entries) => {
302
433
  entries.forEach((entry) => {
303
434
  if (entry.isIntersecting) {
304
- const hydrate = entry.target.__forgewpHydrate;
305
- if (typeof hydrate === "function") hydrate();
435
+ let node = entry.target;
436
+ while (node && typeof node.__forgewpHydrate !== "function") {
437
+ node = node.parentElement;
438
+ }
439
+ if (node && typeof node.__forgewpHydrate === "function") {
440
+ node.__forgewpHydrate();
441
+ }
306
442
  observer.unobserve(entry.target);
307
443
  }
308
444
  });
@@ -329,7 +465,19 @@ export async function generateTheme({
329
465
  },
330
466
  visible: (el, hydrate) => {
331
467
  el.__forgewpHydrate = hydrate;
332
- observer.observe(el);
468
+ const target = firstObservableBox(el);
469
+ if (!target || (target === el && window.getComputedStyle(el).display === "contents")) {
470
+ hydrate();
471
+ return;
472
+ }
473
+ const rect = target.getBoundingClientRect();
474
+ const vw = window.innerWidth || document.documentElement.clientWidth;
475
+ const vh = window.innerHeight || document.documentElement.clientHeight;
476
+ if (rect.bottom >= -200 && rect.right >= -200 && rect.top <= vh + 200 && rect.left <= vw + 200) {
477
+ hydrate();
478
+ return;
479
+ }
480
+ observer.observe(target);
333
481
  },
334
482
  interaction: (el, hydrate) => {
335
483
  const run = () => {
@@ -444,6 +592,13 @@ export async function generateTheme({
444
592
  console.error("[ForgeWP Hydrator] Missing data-forgewp-hydrate attribute on hydration boundary.");
445
593
  return;
446
594
  }
595
+ if (el.__forgewpHydrated) return;
596
+ let parent = el.parentElement;
597
+ while (parent) {
598
+ if (parent.__forgewpHydrated) return;
599
+ parent = parent.parentElement;
600
+ }
601
+ el.__forgewpHydrated = true;
447
602
 
448
603
  const rawProps = el.getAttribute("data-forgewp-props") || "{}";
449
604
  let props = {};
@@ -467,17 +622,11 @@ export async function generateTheme({
467
622
 
468
623
  import(scriptUrl)
469
624
  .then((module) => {
470
- let Component = module.default;
471
- if (!Component) {
472
- Component = Object.values(module).find((val) => typeof val === "function");
473
- if (!Component) {
474
- Component = Object.values(module)[0];
475
- }
476
- }
477
- if (typeof Component !== "function") {
625
+ const Component = resolveExport(module, islandName);
626
+ if (!isReactComponentType(Component)) {
478
627
  const exportsList = Object.keys(module).join(", ");
479
628
  console.error(
480
- "[ForgeWP Hydrator] Chunk for " + islandName + " does not export a valid React component. " +
629
+ "[ForgeWP Hydrator] Chunk for " + islandName + " does not export a valid React component type. " +
481
630
  "Available exports: " + exportsList
482
631
  );
483
632
  return;
@@ -492,8 +641,35 @@ export async function generateTheme({
492
641
  const React = window.React;
493
642
 
494
643
  if (ReactDOM && React) {
495
- const root = ReactDOM.createRoot(el);
496
- root.render(React.createElement(Component, props));
644
+ const backup = el.innerHTML;
645
+ const needsProviders = el.getAttribute("data-forgewp-needs-providers") === "true";
646
+ const providerReady = needsProviders ? loadProviderComponents() : Promise.resolve([]);
647
+ providerReady.then(function (providerComponents) {
648
+ const nextProps = Object.assign({}, props);
649
+ if (el.getAttribute("data-forgewp-slot-children") === "true") {
650
+ const ssrHtml = el.innerHTML;
651
+ if (ssrHtml && String(ssrHtml).trim()) {
652
+ nextProps.children = React.createElement("span", {
653
+ style: { display: "contents" },
654
+ dangerouslySetInnerHTML: { __html: ssrHtml },
655
+ });
656
+ }
657
+ }
658
+ let nextTree = React.createElement(Component, nextProps);
659
+ for (let i = providerComponents.length - 1; i >= 0; i--) {
660
+ nextTree = React.createElement(providerComponents[i], null, nextTree);
661
+ }
662
+ try {
663
+ const root = ReactDOM.createRoot(el);
664
+ root.render(nextTree);
665
+ } catch (err) {
666
+ el.innerHTML = backup;
667
+ console.error("[ForgeWP Hydrator] Render failed for " + islandName + ", restored SSR HTML:", err);
668
+ }
669
+ }).catch(function (err) {
670
+ el.innerHTML = backup;
671
+ console.error("[ForgeWP Hydrator] Provider wrap failed for " + islandName + ":", err);
672
+ });
497
673
  } else {
498
674
  console.error("[ForgeWP Hydration Error] React or ReactDOM not found on window. Ensure main.tsx exposes window.React and window.ReactDOM.");
499
675
  }
@@ -502,6 +678,96 @@ export async function generateTheme({
502
678
  console.error("[ForgeWP Hydrator] Failed to load chunk for " + islandName + ":", err);
503
679
  });
504
680
  }
681
+
682
+ function isReactComponentType(value) {
683
+ if (typeof value === "function" || typeof value === "string") return true;
684
+ if (!value || typeof value !== "object") return false;
685
+ const type = value.$$typeof;
686
+ return type === Symbol.for("react.forward_ref") ||
687
+ type === Symbol.for("react.memo") ||
688
+ type === Symbol.for("react.lazy") ||
689
+ type === Symbol.for("react.provider") ||
690
+ type === Symbol.for("react.context");
691
+ }
692
+
693
+ function resolveExport(module, islandName) {
694
+ if (!module || typeof module !== "object") return undefined;
695
+ const pascalName = islandName
696
+ .split("-")
697
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
698
+ .join("");
699
+ const camelName = pascalName.charAt(0).toLowerCase() + pascalName.slice(1);
700
+
701
+ if (isReactComponentType(module[pascalName])) return module[pascalName];
702
+ if (isReactComponentType(module[camelName])) return module[camelName];
703
+ if (isReactComponentType(module.default)) return module.default;
704
+
705
+ const keys = Object.keys(module);
706
+ for (let i = 0; i < keys.length; i++) {
707
+ const val = module[keys[i]];
708
+ if (isReactComponentType(val)) {
709
+ const componentName = val.displayName || val.name || (val.render && val.render.name);
710
+ if (componentName === pascalName || componentName === camelName) return val;
711
+ }
712
+ }
713
+
714
+ const cleanIsland = islandName.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
715
+ for (let i = 0; i < keys.length; i++) {
716
+ const k = keys[i];
717
+ if (k.toLowerCase() === cleanIsland && isReactComponentType(module[k])) {
718
+ return module[k];
719
+ }
720
+ }
721
+
722
+ const componentKeys = keys.filter(function (k) {
723
+ return isReactComponentType(module[k]);
724
+ });
725
+ if (componentKeys.length === 1) return module[componentKeys[0]];
726
+
727
+ const nonHooks = componentKeys.filter(function (k) {
728
+ const component = module[k];
729
+ const componentName = component.displayName || component.name || (component.render && component.render.name) || k;
730
+ return !/^use[A-Z]/.test(componentName);
731
+ });
732
+ if (nonHooks.length === 1) return module[nonHooks[0]];
733
+
734
+ if (islandName.endsWith("-provider") || islandName.includes("provider")) {
735
+ const provMatch = componentKeys.find(function (k) {
736
+ const component = module[k];
737
+ const componentName = component.displayName || component.name || (component.render && component.render.name) || k;
738
+ return /Provider$/i.test(componentName);
739
+ });
740
+ if (provMatch) return module[provMatch];
741
+ }
742
+
743
+ if (nonHooks.length > 0) return module[nonHooks[0]];
744
+ if (componentKeys.length > 0) return module[componentKeys[0]];
745
+ return undefined;
746
+ }
747
+
748
+ let providerComponentsPromise = null;
749
+ function loadProviderComponents() {
750
+ if (providerComponentsPromise) return providerComponentsPromise;
751
+ const ids = config.providers || [];
752
+ if (!ids.length) {
753
+ providerComponentsPromise = Promise.resolve([]);
754
+ return providerComponentsPromise;
755
+ }
756
+ providerComponentsPromise = Promise.all(ids.map(function (id) {
757
+ const chunkPath = config.manifest && config.manifest[id];
758
+ if (!chunkPath) return Promise.resolve(null);
759
+ const scriptUrl = config.themeUri + "/assets/" + chunkPath.replace("assets/", "").replace("assets\\\\", "");
760
+ return import(scriptUrl).then(function (module) {
761
+ return resolveExport(module, id);
762
+ }).catch(function (err) {
763
+ console.error("[ForgeWP Hydrator] Failed to load provider " + id + ":", err);
764
+ return null;
765
+ });
766
+ })).then(function (list) {
767
+ return list.filter(function (component) { return isReactComponentType(component); });
768
+ });
769
+ return providerComponentsPromise;
770
+ }
505
771
  })();`;
506
772
 
507
773
  writeFileSync(
@@ -509,10 +775,11 @@ export async function generateTheme({
509
775
  hydratorScript,
510
776
  'utf8',
511
777
  );
512
- hydrationManifestJson = JSON.stringify({
778
+ hydrationData = {
513
779
  mainJsFile,
514
780
  mapping,
515
- });
781
+ };
782
+ hydrationManifestJson = JSON.stringify(hydrationData);
516
783
 
517
784
  // Run compiler diagnostics & output detailed metrics
518
785
  const analysis = analyzeHydrationIslands(themeRoot, mapping);
@@ -568,77 +835,141 @@ export async function generateTheme({
568
835
  }
569
836
  }
570
837
 
571
- // Load and merge keys from cms/translations.json
572
- const translationsFileSrc = path.join(themeRoot, 'cms', 'translations.json');
573
- if (existsSync(translationsFileSrc)) {
574
- try {
575
- const transData = JSON.parse(readFileSync(translationsFileSrc, 'utf8'));
576
- for (const locale of Object.keys(transData)) {
577
- if (transData[locale] && typeof transData[locale] === 'object') {
578
- for (const key of Object.keys(transData[locale])) {
579
- i18nKeys.add(key);
580
- }
581
- }
838
+ // Load and merge keys from cms/translations.ts (preferred) or translations.json
839
+ const transData = loadTranslationsData(themeRoot);
840
+ for (const locale of Object.keys(transData)) {
841
+ if (transData[locale] && typeof transData[locale] === 'object') {
842
+ for (const key of Object.keys(transData[locale])) {
843
+ i18nKeys.add(key);
582
844
  }
583
- } catch (e) {
584
- // Ignore parse/read errors during build time
585
845
  }
586
846
  }
587
847
 
588
848
  // Fix nav links and split markup
589
- const processedApp = processMarkup(appHtml, config.textDomain);
590
- const processedHeader = processMarkup(headerHtml, config.textDomain);
591
- const processedFooter = processMarkup(footerHtml, config.textDomain);
592
-
593
- // Extract content (App markup minus Header/Footer)
594
- let contentHtml = processedApp;
595
- if (processedHeader) {
596
- const replaced = contentHtml.replace(processedHeader, '');
597
- contentHtml = replaced !== contentHtml ? replaced : contentHtml.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
598
- }
599
- if (processedFooter) {
600
- const replaced = contentHtml.replace(processedFooter, '');
601
- contentHtml = replaced !== contentHtml ? replaced : contentHtml.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
602
- }
603
- contentHtml = contentHtml.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
849
+ const processedApp = injectAutoHydrationMarkers(
850
+ processMarkup(
851
+ appHtml,
852
+ config.textDomain,
853
+ getRichTextKeysForSlug('front-page'),
854
+ effectiveAssetGraph,
855
+ ),
856
+ );
857
+ const processedHeader = injectAutoHydrationMarkers(
858
+ processMarkup(
859
+ headerHtml,
860
+ config.textDomain,
861
+ richTextFieldKeys,
862
+ effectiveAssetGraph,
863
+ ),
864
+ );
865
+ const processedFooter = injectAutoHydrationMarkers(
866
+ processMarkup(
867
+ footerHtml,
868
+ config.textDomain,
869
+ richTextFieldKeys,
870
+ effectiveAssetGraph,
871
+ ),
872
+ );
873
+
874
+ // Extract content (App markup minus Header/Footer, unless the page owns its shell)
875
+ let contentHtml = extractTemplateContent(
876
+ processedApp,
877
+ processedHeader,
878
+ processedFooter,
879
+ );
880
+ contentHtml = contentHtml.replace(
881
+ /<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g,
882
+ '',
883
+ );
884
+ contentHtml = contentHtml.replace(
885
+ /<\/?forgewp-content-boundary\b[^>]*>/gi,
886
+ '',
887
+ );
888
+
889
+ let cleanHeader = processedHeader.replace(
890
+ /<\/?forgewp-content-boundary\b[^>]*>/gi,
891
+ '',
892
+ );
893
+ let cleanFooter = processedFooter.replace(
894
+ /<\/?forgewp-content-boundary\b[^>]*>/gi,
895
+ '',
896
+ );
604
897
 
605
898
  // Process single post template if exists
606
899
  let processedSingle = '';
607
900
  if (singleHtml) {
608
- processedSingle = processMarkup(singleHtml, config.textDomain);
609
- if (processedHeader) {
610
- const replaced = processedSingle.replace(processedHeader, '');
611
- processedSingle = replaced !== processedSingle ? replaced : processedSingle.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
612
- }
613
- if (processedFooter) {
614
- const replaced = processedSingle.replace(processedFooter, '');
615
- processedSingle = replaced !== processedSingle ? replaced : processedSingle.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
616
- }
617
- processedSingle = processedSingle.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
901
+ processedSingle = injectAutoHydrationMarkers(
902
+ processMarkup(
903
+ singleHtml,
904
+ config.textDomain,
905
+ richTextFieldKeys,
906
+ effectiveAssetGraph,
907
+ ),
908
+ );
909
+ processedSingle = extractTemplateContent(
910
+ processedSingle,
911
+ processedHeader,
912
+ processedFooter,
913
+ );
914
+ processedSingle = processedSingle.replace(
915
+ /<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g,
916
+ '',
917
+ );
918
+ processedSingle = processedSingle.replace(
919
+ /<\/?forgewp-content-boundary\b[^>]*>/gi,
920
+ '',
921
+ );
618
922
  }
619
923
 
620
924
  // Process 404 template if exists
621
925
  let processedNotFound = '';
622
926
  if (notFoundHtml) {
623
- processedNotFound = processMarkup(notFoundHtml, config.textDomain);
624
- if (processedHeader) {
625
- const replaced = processedNotFound.replace(processedHeader, '');
626
- processedNotFound = replaced !== processedNotFound ? replaced : processedNotFound.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
627
- }
628
- if (processedFooter) {
629
- const replaced = processedNotFound.replace(processedFooter, '');
630
- processedNotFound = replaced !== processedNotFound ? replaced : processedNotFound.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
631
- }
632
- processedNotFound = processedNotFound.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
927
+ processedNotFound = injectAutoHydrationMarkers(
928
+ processMarkup(
929
+ notFoundHtml,
930
+ config.textDomain,
931
+ richTextFieldKeys,
932
+ effectiveAssetGraph,
933
+ ),
934
+ );
935
+ processedNotFound = extractTemplateContent(
936
+ processedNotFound,
937
+ processedHeader,
938
+ processedFooter,
939
+ );
940
+ processedNotFound = processedNotFound.replace(
941
+ /<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g,
942
+ '',
943
+ );
944
+ processedNotFound = processedNotFound.replace(
945
+ /<\/?forgewp-content-boundary\b[^>]*>/gi,
946
+ '',
947
+ );
633
948
  }
634
949
 
635
950
  const staticDir = path.join(outDir, 'forgewp-static');
636
951
  mkdirSync(staticDir, { recursive: true });
637
- writeFileSync(path.join(staticDir, 'content.html'), replaceAssetPlaceholders(contentHtml), 'utf8');
638
- writeFileSync(path.join(staticDir, 'header.html'), replaceAssetPlaceholders(processedHeader), 'utf8');
639
- writeFileSync(path.join(staticDir, 'footer.html'), replaceAssetPlaceholders(processedFooter), 'utf8');
952
+ writeFileSync(
953
+ path.join(staticDir, 'content.html'),
954
+ replaceAssetPlaceholders(contentHtml),
955
+ 'utf8',
956
+ );
957
+ writeFileSync(
958
+ path.join(staticDir, 'header.html'),
959
+ replaceAssetPlaceholders(cleanHeader),
960
+ 'utf8',
961
+ );
962
+ writeFileSync(
963
+ path.join(staticDir, 'footer.html'),
964
+ replaceAssetPlaceholders(cleanFooter),
965
+ 'utf8',
966
+ );
640
967
  if (headHtml) {
641
- writeFileSync(path.join(staticDir, 'head.html'), replaceAssetPlaceholders(headHtml), 'utf8');
968
+ writeFileSync(
969
+ path.join(staticDir, 'head.html'),
970
+ replaceAssetPlaceholders(headHtml),
971
+ 'utf8',
972
+ );
642
973
  }
643
974
  if (singleHeadHtml) {
644
975
  writeFileSync(
@@ -648,25 +979,44 @@ export async function generateTheme({
648
979
  );
649
980
  }
650
981
  if (processedSingle) {
651
- writeFileSync(path.join(staticDir, 'single.html'), replaceAssetPlaceholders(processedSingle), 'utf8');
982
+ writeFileSync(
983
+ path.join(staticDir, 'single.html'),
984
+ replaceAssetPlaceholders(processedSingle),
985
+ 'utf8',
986
+ );
652
987
  }
653
988
  if (processedNotFound) {
654
- writeFileSync(path.join(staticDir, '404.html'), replaceAssetPlaceholders(processedNotFound), 'utf8');
989
+ writeFileSync(
990
+ path.join(staticDir, '404.html'),
991
+ replaceAssetPlaceholders(processedNotFound),
992
+ 'utf8',
993
+ );
655
994
  }
656
995
 
657
996
  // Archive page (category / tag / date archives)
658
997
  let processedArchive = '';
659
998
  if (archiveHtml) {
660
- processedArchive = processMarkup(archiveHtml, config.textDomain);
661
- if (processedHeader) {
662
- const replaced = processedArchive.replace(processedHeader, '');
663
- processedArchive = replaced !== processedArchive ? replaced : processedArchive.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
664
- }
665
- if (processedFooter) {
666
- const replaced = processedArchive.replace(processedFooter, '');
667
- processedArchive = replaced !== processedArchive ? replaced : processedArchive.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
668
- }
669
- processedArchive = processedArchive.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
999
+ processedArchive = injectAutoHydrationMarkers(
1000
+ processMarkup(
1001
+ archiveHtml,
1002
+ config.textDomain,
1003
+ richTextFieldKeys,
1004
+ effectiveAssetGraph,
1005
+ ),
1006
+ );
1007
+ processedArchive = extractTemplateContent(
1008
+ processedArchive,
1009
+ processedHeader,
1010
+ processedFooter,
1011
+ );
1012
+ processedArchive = processedArchive.replace(
1013
+ /<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g,
1014
+ '',
1015
+ );
1016
+ processedArchive = processedArchive.replace(
1017
+ /<\/?forgewp-content-boundary\b[^>]*>/gi,
1018
+ '',
1019
+ );
670
1020
  writeFileSync(
671
1021
  path.join(staticDir, 'archive.html'),
672
1022
  replaceAssetPlaceholders(processedArchive),
@@ -675,14 +1025,532 @@ export async function generateTheme({
675
1025
  }
676
1026
 
677
1027
  // Dynamic Gutenberg blocks compilation (Phase 5)
678
- const compiledBlocks = compileBlocks(themeRoot, outDir);
1028
+ // Pass strict so from/pick issues fail export only when `forgewp export --strict`
1029
+ const compiledBlocks = compileBlocks(themeRoot, outDir, { strict: !!strict });
1030
+
1031
+ const iconRegistryJson = JSON.stringify(buildEditorIconRegistry());
1032
+ const defaultIconSlugsJson = JSON.stringify(FORGEWP_DEFAULT_ICON_SLUGS);
679
1033
 
680
1034
  const editorScriptContent = `
681
1035
  const { registerBlockType } = wp.blocks;
682
- const { createElement } = wp.element;
683
- const { InspectorControls, useBlockProps } = wp.blockEditor;
684
- const { PanelBody, TextControl } = wp.components;
685
- const ServerSideRender = wp.serverSideRender;
1036
+ const { createElement, useState, Fragment } = wp.element;
1037
+ const { InspectorControls, useBlockProps, MediaUpload, URLInput, InnerBlocks, useInnerBlocksProps } = wp.blockEditor;
1038
+ const { PanelBody, TextControl, ToggleControl, SelectControl, RangeControl, Placeholder, Spinner, Button, ColorPalette, BaseControl } = wp.components;
1039
+ const ServerSideRender = wp.serverSideRender?.default || wp.serverSideRender;
1040
+ function forgeWpResolveEditorImage(source) {
1041
+ if (source && typeof source === 'object') source = source.url || source.src || '';
1042
+ if (typeof source !== 'string' || !source || source.startsWith('//') || /^(?:[a-z]+:|data:|blob:)/i.test(source)) return source;
1043
+ if (source.charAt(0) === '/') {
1044
+ const themeUri = window.forgeWpEditorConfig && window.forgeWpEditorConfig.themeUri;
1045
+ return themeUri ? themeUri.replace(/\\/$/, '') + source : source;
1046
+ }
1047
+ return source;
1048
+ }
1049
+ function resolveWpAsset(path) {
1050
+ if (!path) return '';
1051
+ if (/^(?:https?:|\\/\\/|data:|blob:)/i.test(path)) return path;
1052
+ const themeUri = window.forgeWpEditorConfig && window.forgeWpEditorConfig.themeUri;
1053
+ if (themeUri) {
1054
+ return themeUri.replace(/\\/+$/, '') + '/' + path.replace(/^(\\/|\\.\\/)+/, '');
1055
+ }
1056
+ return path;
1057
+ }
1058
+ function forgeWpEditorImageAlt(source, fallback) {
1059
+ return source && typeof source === 'object' && source.alt ? source.alt : (fallback || '');
1060
+ }
1061
+
1062
+ // Set only inside the block editor's customEditJsx preview environment — never true on
1063
+ // the real frontend. Components can check this to distinguish "genuinely no results" from
1064
+ // "this is just the editor preview, which can't run a real fetch" — e.g. rendering a
1065
+ // loading skeleton instead of an empty-state message when useWpQuery's stub can only ever
1066
+ // return an empty result set.
1067
+ window.forgeWpIsEditorPreview = true;
1068
+
1069
+ // Curated Lucide SVG registry for icon fields + <WpIcon /> in the canvas
1070
+ window.forgeWpIconRegistry = ${iconRegistryJson};
1071
+ window.forgeWpDefaultIconSlugs = ${defaultIconSlugsJson};
1072
+
1073
+ function forgeWpApplyIconClass(svg, className) {
1074
+ if (!svg) return '';
1075
+ if (!className) return svg;
1076
+ if (/\\sclass="/.test(svg)) {
1077
+ return svg.replace(/\\sclass="([^"]*)"/, function(_, existing) {
1078
+ return ' class="' + existing + ' ' + className + '"';
1079
+ });
1080
+ }
1081
+ return svg.replace('<svg ', '<svg class="' + className + '" ');
1082
+ }
1083
+
1084
+ function forgeWpRenderIcon(name, className, provider) {
1085
+ provider = provider || 'lucide';
1086
+ var slug = (name == null ? '' : String(name)).replace(/^dashicons-/, '');
1087
+ var registry = window.forgeWpIconRegistry || {};
1088
+ // Prefer provider-scoped key when present, then bare slug (lucide curated set)
1089
+ var svg = registry[provider + ':' + slug] || registry[slug] || registry[name] || '';
1090
+ if (svg && provider !== 'dashicons') {
1091
+ var html = forgeWpApplyIconClass(svg, className || '');
1092
+ return createElement('span', {
1093
+ className: 'forgewp-icon forgewp-icon--' + slug,
1094
+ style: { display: 'inline-flex', lineHeight: 0 },
1095
+ dangerouslySetInnerHTML: { __html: html }
1096
+ });
1097
+ }
1098
+ // Dashicons (explicit provider or fallback when SVG missing) — always available in wp-admin
1099
+ return createElement('span', {
1100
+ className: ('dashicons dashicons-' + slug + (className ? ' ' + className : '')).trim(),
1101
+ title: provider && provider !== 'lucide' && provider !== 'dashicons'
1102
+ ? ('Provider "' + provider + '" not in editor registry — showing dashicons fallback')
1103
+ : undefined,
1104
+ 'aria-hidden': true
1105
+ });
1106
+ }
1107
+
1108
+ function ForgeWpIconPicker({ value, onChange, options, label, provider }) {
1109
+ var slugs = Array.isArray(options) && options.length
1110
+ ? options.map(function(o) { return typeof o === 'string' ? o : (o && o.value); }).filter(Boolean)
1111
+ : (window.forgeWpDefaultIconSlugs || Object.keys(window.forgeWpIconRegistry || {}));
1112
+ var current = value || slugs[0] || 'star';
1113
+ return createElement(BaseControl, { label: label || 'Icon', className: 'forgewp-icon-picker' },
1114
+ createElement('div', {
1115
+ style: {
1116
+ display: 'grid',
1117
+ gridTemplateColumns: 'repeat(auto-fill, minmax(40px, 1fr))',
1118
+ gap: '6px',
1119
+ maxHeight: '180px',
1120
+ overflowY: 'auto',
1121
+ padding: '4px',
1122
+ border: '1px solid #e0e0e0',
1123
+ borderRadius: '4px',
1124
+ background: '#fff'
1125
+ }
1126
+ },
1127
+ slugs.map(function(slug) {
1128
+ var selected = slug === current;
1129
+ return createElement('button', {
1130
+ key: slug,
1131
+ type: 'button',
1132
+ title: slug,
1133
+ onClick: function() { onChange(slug); },
1134
+ style: {
1135
+ display: 'flex',
1136
+ alignItems: 'center',
1137
+ justifyContent: 'center',
1138
+ width: '100%',
1139
+ aspectRatio: '1',
1140
+ padding: '6px',
1141
+ border: selected ? '2px solid #2271b1' : '1px solid #ddd',
1142
+ borderRadius: '4px',
1143
+ background: selected ? '#f0f6fc' : '#fafafa',
1144
+ cursor: 'pointer'
1145
+ }
1146
+ }, forgeWpRenderIcon(slug, 'w-5 h-5', provider || 'lucide'));
1147
+ })
1148
+ ),
1149
+ createElement('p', {
1150
+ style: { margin: '6px 0 0', fontSize: '11px', color: '#646970' }
1151
+ }, 'Selected: ' + current)
1152
+ );
1153
+ }
1154
+
1155
+ // Stub implementations for every hook exported by .forgewp/wordpress.tsx, so that
1156
+ // arbitrary component code inlined into customEditJsx (via expandNestedComponentTags)
1157
+ // can execute in the block editor's preview without throwing "X is not defined".
1158
+ // Keep this list in sync with wordpress.tsx's exported useWp* hooks — a component using
1159
+ // any hook missing here will crash its editor preview with a ReferenceError.
1160
+ const useWpLocation = () => ['/', () => {}, () => {}];
1161
+ const useWpTerms = () => ({ terms: [], loading: false });
1162
+ const useWpI18n = () => ({ __: (s) => s });
1163
+ // Free __ for inlined JSX that calls __(s) without a local destructure.
1164
+ const __ = (s) => s;
1165
+ const useWpPagePath = (name, fallback) => fallback || '/';
1166
+ const useWpPageLink = (name, fallback) => fallback || '/';
1167
+ const useWpQuery = () => ({ posts: [], total: 0, loading: false });
1168
+ const useWpMeta = (key, fallback, postId) => fallback;
1169
+ const useWpOption = (name, fallback) => fallback || '';
1170
+ const useWpThemeMod = (name, fallback) => fallback || '';
1171
+ const useWpThemeUri = () => '';
1172
+ const useWpSearch = () => '';
1173
+ const useWpSearchParams = () => new URLSearchParams();
1174
+ const useWpTitle = () => '';
1175
+ const useWpContent = () => '';
1176
+ const useWpExcerpt = () => '';
1177
+ const useWpPermalink = () => '#';
1178
+ const useWpDate = () => '';
1179
+ const useWpModifiedDate = () => '';
1180
+ const useWpAuthor = () => '';
1181
+ const useWpFeaturedImage = () => '';
1182
+ const useWpCustomField = (name, fallback) => fallback || '';
1183
+ const useWpField = (name, fallback) => fallback || '';
1184
+ const useWpArchiveTitle = () => '';
1185
+ const useWpCategories = () => '';
1186
+ const useWpTaxonomyList = (taxonomy, fallback) => fallback || '';
1187
+ const useWpMenu = (location) => ({ items: [], loading: false });
1188
+ const useWpPrefetch = () => (to) => {};
1189
+ const useWpLanguage = () => ({
1190
+ currentLanguage: ${JSON.stringify(
1191
+ config.i18n?.defaultLocale ||
1192
+ (Array.isArray(config.i18n?.locales) && config.i18n.locales[0]) ||
1193
+ 'en',
1194
+ )},
1195
+ languages: ${JSON.stringify(
1196
+ Array.isArray(config.i18n?.locales) && config.i18n.locales.length > 0
1197
+ ? config.i18n.locales
1198
+ : ['en'],
1199
+ )},
1200
+ homeUrl: '/',
1201
+ urls: {},
1202
+ homeUrls: {},
1203
+ switchLanguage: () => {},
1204
+ });
1205
+ // Public ForgeWP helpers — prefer these over reading window.forgeWpIsEditorPreview directly.
1206
+ const isEditorPreview = () => typeof window !== 'undefined' && !!window.forgeWpIsEditorPreview;
1207
+ const useIsEditorPreview = () => isEditorPreview();
1208
+
1209
+ const WpLink = (props) => {
1210
+ // Inside the Gutenberg block editor canvas, a real navigation would take
1211
+ // the admin away from wp-admin entirely (and can 404 if the resolved
1212
+ // href doesn't correspond to a real page yet) — intercept the click so
1213
+ // any WpEditable content nested inside can still be clicked for inline
1214
+ // editing without the link itself firing a real page navigation.
1215
+ if (isEditorPreview()) {
1216
+ return createElement('a', Object.assign({}, props, {
1217
+ onClick: function (e) { e.preventDefault(); }
1218
+ }));
1219
+ }
1220
+ return createElement('a', props);
1221
+ };
1222
+
1223
+ /**
1224
+ * Canvas-safe link used for every <a>/<WpLink> in customEditJsx.
1225
+ * - Never navigates inside the editor (link text stays clickable for RichText).
1226
+ * - When the compiler detected an href bound to a block attribute it passes
1227
+ * forgeWpUrl/forgeWpOnUrlChange, and clicking the link opens a small URL
1228
+ * popover so the URL is editable inline (the sidebar field still works too).
1229
+ */
1230
+ function ForgeWpEditorLink(props) {
1231
+ const forgeWpUrl = props.forgeWpUrl;
1232
+ const onUrlChange = props.forgeWpOnUrlChange;
1233
+ const urlLabel = props.forgeWpUrlLabel;
1234
+ const rest = Object.assign({}, props);
1235
+ delete rest.forgeWpUrl;
1236
+ delete rest.forgeWpOnUrlChange;
1237
+ delete rest.forgeWpUrlLabel;
1238
+ delete rest.children;
1239
+ const editable = typeof onUrlChange === 'function';
1240
+ const anchorState = useState(null);
1241
+ const openState = useState(false);
1242
+ const anchor = anchorState[0];
1243
+ const open = openState[0];
1244
+ const setOpen = openState[1];
1245
+ const Popover = wp.components.Popover;
1246
+ const linkProps = Object.assign({}, rest, {
1247
+ onClickCapture: function (event) { event.preventDefault(); },
1248
+ onClick: function (event) {
1249
+ event.preventDefault();
1250
+ if (editable) setOpen(true);
1251
+ },
1252
+ });
1253
+ if (editable) linkProps.ref = anchorState[1];
1254
+ const popover = editable && open && anchor && Popover
1255
+ ? createElement(Popover, {
1256
+ anchor: anchor,
1257
+ placement: 'bottom-start',
1258
+ focusOnMount: false,
1259
+ onClose: function () { setOpen(false); },
1260
+ className: 'forgewp-link-url-popover',
1261
+ },
1262
+ createElement('div', { style: { padding: '12px', minWidth: '280px' } },
1263
+ createElement(TextControl, {
1264
+ label: urlLabel || 'Link URL',
1265
+ type: 'url',
1266
+ value: forgeWpUrl == null ? '' : String(forgeWpUrl),
1267
+ onChange: onUrlChange,
1268
+ __nextHasNoMarginBottom: true,
1269
+ })
1270
+ )
1271
+ )
1272
+ : null;
1273
+ return createElement(Fragment, null, createElement('a', linkProps, props.children), popover);
1274
+ }
1275
+
1276
+ /**
1277
+ * Build a blank row object from a repeater field schema (editor metadata).
1278
+ */
1279
+ function forgeWpBlankRepeaterRow(fields) {
1280
+ const row = {};
1281
+ const schema = fields || {};
1282
+ Object.keys(schema).forEach((subKey) => {
1283
+ const sub = schema[subKey] || {};
1284
+ if (sub.default !== undefined) {
1285
+ row[subKey] = sub.default;
1286
+ } else if (sub.control === 'image' || sub.type === 'object') {
1287
+ row[subKey] = '';
1288
+ } else if (sub.control === 'icon') {
1289
+ row[subKey] = 'star';
1290
+ } else if (sub.control === 'toggle' || sub.type === 'boolean') {
1291
+ row[subKey] = false;
1292
+ } else if (sub.control === 'number' || sub.type === 'number') {
1293
+ row[subKey] = sub.min != null ? sub.min : 0;
1294
+ } else if (sub.control === 'repeater' || sub.type === 'array') {
1295
+ row[subKey] = [];
1296
+ } else {
1297
+ row[subKey] = '';
1298
+ }
1299
+ });
1300
+ return row;
1301
+ }
1302
+
1303
+ /**
1304
+ * Sidebar repeater control.
1305
+ * - mode: 'fixed' → edit subfields only (no add/remove/reorder of cardinality)
1306
+ * - mode: 'dynamic' → add / remove / move up / move down within min/max
1307
+ * Canvas remains responsible for visual text via WpEditable.
1308
+ */
1309
+ function ForgeWpRepeaterControl({ attrKey, config, attributes, setAttributes }) {
1310
+ const label = config.label || attrKey;
1311
+ const mode = config.mode === 'fixed' ? 'fixed' : 'dynamic';
1312
+ const fields = config.fields || {};
1313
+ const fieldKeys = Object.keys(fields);
1314
+ const defaults = Array.isArray(config.default) ? config.default : [];
1315
+ const rows = Array.isArray(attributes[attrKey]) ? attributes[attrKey] : defaults.slice();
1316
+ const fixedCount = defaults.length > 0 ? defaults.length : rows.length;
1317
+ const minRows = mode === 'fixed'
1318
+ ? fixedCount
1319
+ : (typeof config.min === 'number' ? config.min : 0);
1320
+ const maxRows = mode === 'fixed'
1321
+ ? fixedCount
1322
+ : (typeof config.max === 'number' ? config.max : Infinity);
1323
+
1324
+ const commit = (next) => {
1325
+ let clamped = Array.isArray(next) ? next.slice() : [];
1326
+ if (mode === 'fixed') {
1327
+ // Lock cardinality to default length when known
1328
+ if (fixedCount > 0) {
1329
+ while (clamped.length < fixedCount) clamped.push(forgeWpBlankRepeaterRow(fields));
1330
+ if (clamped.length > fixedCount) clamped = clamped.slice(0, fixedCount);
1331
+ }
1332
+ } else {
1333
+ if (clamped.length < minRows) {
1334
+ while (clamped.length < minRows) clamped.push(forgeWpBlankRepeaterRow(fields));
1335
+ }
1336
+ if (clamped.length > maxRows) clamped = clamped.slice(0, maxRows);
1337
+ }
1338
+ setAttributes({ [attrKey]: clamped });
1339
+ };
1340
+
1341
+ const updateCell = (index, subKey, value) => {
1342
+ commit(rows.map((r, i) => (i === index ? Object.assign({}, r, { [subKey]: value }) : r)));
1343
+ };
1344
+
1345
+ const addRow = () => {
1346
+ if (mode !== 'dynamic' || rows.length >= maxRows) return;
1347
+ commit(rows.concat([forgeWpBlankRepeaterRow(fields)]));
1348
+ };
1349
+
1350
+ const removeRow = (index) => {
1351
+ if (mode !== 'dynamic' || rows.length <= minRows) return;
1352
+ commit(rows.filter((_, i) => i !== index));
1353
+ };
1354
+
1355
+ const moveRow = (index, delta) => {
1356
+ if (mode !== 'dynamic') return;
1357
+ const target = index + delta;
1358
+ if (target < 0 || target >= rows.length) return;
1359
+ const next = rows.slice();
1360
+ const tmp = next[index];
1361
+ next[index] = next[target];
1362
+ next[target] = tmp;
1363
+ commit(next);
1364
+ };
1365
+
1366
+ const rowLabel = (row, index) => {
1367
+ for (const k of fieldKeys) {
1368
+ const v = row && row[k];
1369
+ if (typeof v === 'string' && v.trim()) return v.trim().slice(0, 40);
1370
+ if (v && typeof v === 'object' && v.url) return String(v.url).slice(0, 40);
1371
+ }
1372
+ return 'Item ' + (index + 1);
1373
+ };
1374
+
1375
+ const renderSubField = (row, index, subKey) => {
1376
+ const sub = fields[subKey] || {};
1377
+ const subLabel = sub.label || subKey;
1378
+ const control = sub.control || (sub.type === 'boolean' ? 'toggle' : sub.type === 'number' ? 'number' : sub.type === 'object' ? 'image' : 'text');
1379
+ const value = row ? row[subKey] : undefined;
1380
+
1381
+ if (control === 'image') {
1382
+ const url = typeof value === 'string' ? value : (value && value.url) || '';
1383
+ const mediaId = value && typeof value === 'object' ? value.id : undefined;
1384
+ return createElement(BaseControl, { label: subLabel, key: subKey },
1385
+ createElement(MediaUpload, {
1386
+ onSelect: (media) => updateCell(index, subKey, media.url || ''),
1387
+ allowedTypes: ['image'],
1388
+ value: mediaId,
1389
+ render: ({ open }) => createElement('div', null,
1390
+ url
1391
+ ? createElement('img', {
1392
+ src: url,
1393
+ style: { maxWidth: '100%', marginBottom: '8px', display: 'block', borderRadius: '4px' }
1394
+ })
1395
+ : null,
1396
+ createElement('div', { style: { display: 'flex', gap: '8px', flexWrap: 'wrap' } },
1397
+ createElement(Button, { onClick: open, variant: 'secondary', isSmall: true },
1398
+ url ? 'Replace Image' : 'Select Image'
1399
+ ),
1400
+ url
1401
+ ? createElement(Button, {
1402
+ onClick: () => updateCell(index, subKey, ''),
1403
+ variant: 'link',
1404
+ isDestructive: true,
1405
+ isSmall: true
1406
+ }, 'Remove')
1407
+ : null
1408
+ )
1409
+ )
1410
+ })
1411
+ );
1412
+ }
1413
+
1414
+ if (control === 'toggle') {
1415
+ return createElement(ToggleControl, {
1416
+ key: subKey,
1417
+ label: subLabel,
1418
+ checked: !!value,
1419
+ onChange: (val) => updateCell(index, subKey, val)
1420
+ });
1421
+ }
1422
+
1423
+ if (control === 'number') {
1424
+ return createElement(RangeControl, {
1425
+ key: subKey,
1426
+ label: subLabel,
1427
+ value: typeof value === 'number' ? value : (sub.min || 0),
1428
+ onChange: (val) => updateCell(index, subKey, val),
1429
+ min: sub.min != null ? sub.min : 0,
1430
+ max: sub.max != null ? sub.max : 100
1431
+ });
1432
+ }
1433
+
1434
+ if (control === 'select') {
1435
+ return createElement(SelectControl, {
1436
+ key: subKey,
1437
+ label: subLabel,
1438
+ value: value || '',
1439
+ options: (sub.options || []).map((opt) =>
1440
+ typeof opt === 'string' ? { label: opt, value: opt } : opt
1441
+ ),
1442
+ onChange: (val) => updateCell(index, subKey, val)
1443
+ });
1444
+ }
1445
+
1446
+ if (control === 'color') {
1447
+ return createElement(BaseControl, { label: subLabel, key: subKey },
1448
+ createElement(ColorPalette, {
1449
+ value: value || '',
1450
+ onChange: (val) => updateCell(index, subKey, val || '')
1451
+ })
1452
+ );
1453
+ }
1454
+
1455
+ if (control === 'icon') {
1456
+ return createElement(ForgeWpIconPicker, {
1457
+ key: subKey,
1458
+ label: subLabel,
1459
+ value: value || sub.default || 'star',
1460
+ options: sub.options,
1461
+ provider: sub.provider || 'lucide',
1462
+ onChange: (val) => updateCell(index, subKey, val)
1463
+ });
1464
+ }
1465
+
1466
+ // text, richText, url, default
1467
+ return createElement(TextControl, {
1468
+ key: subKey,
1469
+ label: subLabel,
1470
+ value: value == null ? '' : String(value),
1471
+ type: control === 'url' ? 'url' : 'text',
1472
+ onChange: (val) => updateCell(index, subKey, val)
1473
+ });
1474
+ };
1475
+
1476
+ const helpText = mode === 'fixed'
1477
+ ? ('Fixed list (' + rows.length + ' item' + (rows.length === 1 ? '' : 's') + '). Edit fields below or inline on the canvas.')
1478
+ : (
1479
+ 'Dynamic list' +
1480
+ (minRows > 0 ? ' · min ' + minRows : '') +
1481
+ (maxRows !== Infinity ? ' · max ' + maxRows : '') +
1482
+ '. Reorder with ↑/↓. Text is also editable on the canvas.'
1483
+ );
1484
+
1485
+ return createElement('div', {
1486
+ key: attrKey,
1487
+ style: { display: 'flex', flexDirection: 'column', gap: '12px' }
1488
+ },
1489
+ createElement('p', {
1490
+ style: { margin: 0, fontSize: '12px', color: '#646970' }
1491
+ }, helpText),
1492
+ rows.map((row, index) =>
1493
+ createElement('div', {
1494
+ key: index,
1495
+ style: {
1496
+ border: '1px solid #e0e0e0',
1497
+ borderRadius: '4px',
1498
+ padding: '10px',
1499
+ background: '#fafafa'
1500
+ }
1501
+ },
1502
+ createElement('div', {
1503
+ style: {
1504
+ display: 'flex',
1505
+ alignItems: 'center',
1506
+ justifyContent: 'space-between',
1507
+ gap: '8px',
1508
+ marginBottom: '8px'
1509
+ }
1510
+ },
1511
+ createElement('strong', {
1512
+ style: { fontSize: '12px', textTransform: 'uppercase', letterSpacing: '0.04em' }
1513
+ }, rowLabel(row, index)),
1514
+ mode === 'dynamic'
1515
+ ? createElement('div', { style: { display: 'flex', gap: '4px', flexShrink: 0 } },
1516
+ createElement(Button, {
1517
+ icon: 'arrow-up-alt2',
1518
+ label: 'Move up',
1519
+ isSmall: true,
1520
+ disabled: index === 0,
1521
+ onClick: () => moveRow(index, -1)
1522
+ }),
1523
+ createElement(Button, {
1524
+ icon: 'arrow-down-alt2',
1525
+ label: 'Move down',
1526
+ isSmall: true,
1527
+ disabled: index >= rows.length - 1,
1528
+ onClick: () => moveRow(index, 1)
1529
+ }),
1530
+ createElement(Button, {
1531
+ icon: 'trash',
1532
+ label: 'Remove',
1533
+ isSmall: true,
1534
+ isDestructive: true,
1535
+ disabled: rows.length <= minRows,
1536
+ onClick: () => removeRow(index)
1537
+ })
1538
+ )
1539
+ : null
1540
+ ),
1541
+ fieldKeys.map((subKey) => renderSubField(row, index, subKey))
1542
+ )
1543
+ ),
1544
+ mode === 'dynamic'
1545
+ ? createElement(Button, {
1546
+ variant: 'secondary',
1547
+ onClick: addRow,
1548
+ disabled: rows.length >= maxRows,
1549
+ style: { alignSelf: 'flex-start' }
1550
+ }, '+ Add ' + (label.replace(/s$/i, '') || 'item'))
1551
+ : null
1552
+ );
1553
+ }
686
1554
 
687
1555
  if (window.forgeWpBlocks) {
688
1556
  window.forgeWpBlocks.forEach(block => {
@@ -690,36 +1558,246 @@ if (window.forgeWpBlocks) {
690
1558
  title: block.title,
691
1559
  icon: block.icon,
692
1560
  category: block.category,
1561
+ description: block.description || '',
1562
+ example: block.example || undefined,
693
1563
  attributes: block.attributes,
694
1564
  edit: function(props) {
695
1565
  const { attributes, setAttributes } = props;
1566
+
1567
+ // ── Parent shell: layout chrome + InnerBlocks ───────────────
1568
+ // Children stay independently insertable unless they declare WP parent.
1569
+ if (block.isParentShell && block.innerBlocks) {
1570
+ const shellClass = ((block.shell && block.shell.className) || '').trim();
1571
+ const gridClass = ((block.shell && block.shell.gridClassName) || '').trim();
1572
+ const outerClass = ('forgewp-block-shell ' + shellClass).trim();
1573
+ const innerClass = ('forgewp-block-shell__grid ' + gridClass).trim();
1574
+ const blockProps = useBlockProps({ className: outerClass });
1575
+ const ibConfig = {
1576
+ allowedBlocks: block.innerBlocks.allowedBlocks,
1577
+ template: block.innerBlocks.template,
1578
+ templateLock: block.innerBlocks.templateLock,
1579
+ orientation: block.innerBlocks.orientation || 'horizontal',
1580
+ };
1581
+ if (typeof useInnerBlocksProps === 'function') {
1582
+ const innerProps = useInnerBlocksProps(
1583
+ { className: innerClass, style: { minWidth: 0 } },
1584
+ ibConfig
1585
+ );
1586
+ return createElement('div', blockProps, createElement('div', innerProps));
1587
+ }
1588
+ // Older WP fallback
1589
+ return createElement('div', blockProps,
1590
+ createElement('div', { className: innerClass, style: { minWidth: 0 } },
1591
+ createElement(InnerBlocks, ibConfig)
1592
+ )
1593
+ );
1594
+ }
1595
+
696
1596
  const blockProps = useBlockProps();
697
-
1597
+
1598
+ // Scalar / simple controls (sidebar). Repeaters get their own PanelBody.
1599
+ const simpleControls = Object.entries(block.attributes || {})
1600
+ .filter(([key, config]) => key !== 'align' && config.control !== 'repeater')
1601
+ .map(([key, config]) => {
1602
+ const label = config.label || (key.replace(/([A-Z])/g, ' $1').replace(/^./, s => s.toUpperCase()));
1603
+ const control = config.control || 'text';
1604
+
1605
+ switch (control) {
1606
+ case 'color':
1607
+ return createElement(BaseControl, { label: label, key: key },
1608
+ createElement(ColorPalette, {
1609
+ value: attributes[key],
1610
+ onChange: (val) => setAttributes({ [key]: val })
1611
+ })
1612
+ );
1613
+
1614
+ case 'image':
1615
+ return createElement(BaseControl, { label: label, key: key },
1616
+ createElement(MediaUpload, {
1617
+ onSelect: (media) => setAttributes({
1618
+ [key]: { id: media.id, url: media.url, alt: media.alt || '' }
1619
+ }),
1620
+ allowedTypes: ['image'],
1621
+ value: attributes[key]?.id,
1622
+ render: ({ open }) => createElement('div', null,
1623
+ attributes[key]?.url
1624
+ ? createElement('img', {
1625
+ src: attributes[key].url,
1626
+ style: { maxWidth: '100%', marginBottom: '8px', display: 'block' }
1627
+ })
1628
+ : null,
1629
+ createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
1630
+ createElement(Button, {
1631
+ onClick: open,
1632
+ variant: 'secondary'
1633
+ }, attributes[key]?.url ? 'Replace Image' : 'Select Image'),
1634
+ attributes[key]?.url
1635
+ ? createElement(Button, {
1636
+ onClick: () => setAttributes({ [key]: null }),
1637
+ variant: 'link',
1638
+ isDestructive: true,
1639
+ style: { color: '#cc1818', textDecoration: 'none' }
1640
+ }, 'Remove Image')
1641
+ : null
1642
+ )
1643
+ )
1644
+ })
1645
+ );
1646
+
1647
+ case 'url':
1648
+ return createElement(TextControl, {
1649
+ key: key,
1650
+ label: label,
1651
+ value: attributes[key] || '',
1652
+ onChange: (val) => setAttributes({ [key]: val }),
1653
+ type: 'url'
1654
+ });
1655
+
1656
+ case 'toggle':
1657
+ return createElement(ToggleControl, {
1658
+ key: key,
1659
+ label: label,
1660
+ checked: !!attributes[key],
1661
+ onChange: (val) => setAttributes({ [key]: val })
1662
+ });
1663
+
1664
+ case 'select':
1665
+ return createElement(SelectControl, {
1666
+ key: key,
1667
+ label: label,
1668
+ value: attributes[key],
1669
+ options: (config.options || []).map(opt =>
1670
+ typeof opt === 'string' ? { label: opt, value: opt } : opt
1671
+ ),
1672
+ onChange: (val) => setAttributes({ [key]: val })
1673
+ });
1674
+
1675
+ case 'number':
1676
+ return createElement(RangeControl, {
1677
+ key: key,
1678
+ label: label,
1679
+ value: attributes[key] || 0,
1680
+ onChange: (val) => setAttributes({ [key]: val }),
1681
+ min: config.min || 0,
1682
+ max: config.max || 100
1683
+ });
1684
+
1685
+ case 'icon':
1686
+ return createElement(ForgeWpIconPicker, {
1687
+ key: key,
1688
+ label: label,
1689
+ value: attributes[key] || config.default || 'star',
1690
+ options: config.options,
1691
+ provider: config.provider || 'lucide',
1692
+ onChange: (val) => setAttributes({ [key]: val })
1693
+ });
1694
+
1695
+ case 'richText':
1696
+ case 'text':
1697
+ default:
1698
+ return createElement(TextControl, {
1699
+ key: key,
1700
+ label: label,
1701
+ value: attributes[key] || '',
1702
+ onChange: (val) => setAttributes({ [key]: val })
1703
+ });
1704
+ }
1705
+ });
1706
+
1707
+ const repeaterPanels = Object.entries(block.attributes || {})
1708
+ .filter(([key, config]) => key !== 'align' && config.control === 'repeater')
1709
+ .map(([key, config]) => {
1710
+ const panelTitle = config.label || (key.replace(/([A-Z])/g, ' $1').replace(/^./, s => s.toUpperCase()));
1711
+ return createElement(PanelBody, {
1712
+ title: panelTitle,
1713
+ initialOpen: true,
1714
+ key: 'repeater-' + key
1715
+ },
1716
+ createElement(ForgeWpRepeaterControl, {
1717
+ attrKey: key,
1718
+ config: config,
1719
+ attributes: attributes,
1720
+ setAttributes: setAttributes
1721
+ })
1722
+ );
1723
+ });
1724
+
1725
+ const inspector = (simpleControls.length > 0 || repeaterPanels.length > 0)
1726
+ ? createElement(InspectorControls, null,
1727
+ simpleControls.length > 0
1728
+ ? createElement(PanelBody, { title: 'Block Settings', initialOpen: true }, simpleControls)
1729
+ : null,
1730
+ ...repeaterPanels
1731
+ )
1732
+ : null;
1733
+
698
1734
  if (block.customEditJsx) {
699
1735
  try {
700
- const renderFn = new Function('props', 'createElement', 'useBlockProps', 'attributes', 'setAttributes', 'blockProps',
1736
+ // editorScope: serializable free vars (defaults, SECTION_PADDING_Y, …)
1737
+ // bound as Function parameters so the IIFE can close over them even if
1738
+ // string-level injections were missing.
1739
+ const editorScope = (block.editorScope && typeof block.editorScope === 'object')
1740
+ ? Object.assign({}, block.editorScope)
1741
+ : {};
1742
+ // Always ensure defaults exists so "defaults is not defined" cannot surface.
1743
+ if (typeof editorScope.defaults === 'undefined') {
1744
+ editorScope.defaults = {};
1745
+ }
1746
+ const baseParamNames = [
1747
+ 'React', 'props', 'createElement', 'useBlockProps', 'attributes', 'setAttributes', 'blockProps',
1748
+ 'useWpLocation', 'useWpTerms', 'useWpI18n', '__', 'useWpPagePath', 'useWpPageLink', 'useWpQuery', 'useWpMeta', 'useWpOption',
1749
+ 'useWpThemeMod', 'useWpThemeUri', 'useWpSearch', 'useWpSearchParams', 'useWpTitle', 'useWpContent', 'useWpExcerpt',
1750
+ 'useWpPermalink', 'useWpDate', 'useWpModifiedDate', 'useWpAuthor', 'useWpFeaturedImage', 'useWpCustomField', 'useWpField',
1751
+ 'useWpArchiveTitle', 'useWpCategories', 'useWpTaxonomyList', 'useWpMenu', 'useWpPrefetch', 'useWpLanguage', 'WpLink',
1752
+ 'isEditorPreview', 'useIsEditorPreview', 'forgeWpRenderIcon', 'WpIcon',
1753
+ 'resolveWpAsset', 'forgeWpResolveEditorImage', 'forgeWpEditorImageAlt', 'ForgeWpEditorLink'
1754
+ ];
1755
+ // Never shadow the fixed hook/param names.
1756
+ const baseParamSet = {};
1757
+ for (let bi = 0; bi < baseParamNames.length; bi++) baseParamSet[baseParamNames[bi]] = true;
1758
+ const scopeKeys = Object.keys(editorScope).filter(function(k) {
1759
+ return /^[A-Za-z_$][\w$]*$/.test(k) && !baseParamSet[k];
1760
+ });
1761
+ const scopeVals = scopeKeys.map(function(k) { return editorScope[k]; });
1762
+ // Bind scope keys as outer parameters. Inner IIFE may also declare
1763
+ // the same names with var/const — nested scopes are fine; free vars
1764
+ // resolve to these parameters via closure.
1765
+ const renderFn = new Function(
1766
+ ...baseParamNames,
1767
+ ...scopeKeys,
701
1768
  'return ' + block.customEditJsx
702
1769
  );
703
- return renderFn(props, createElement, useBlockProps, attributes, setAttributes, blockProps);
1770
+ const WpIcon = function(p) {
1771
+ return forgeWpRenderIcon(p && p.name, p && (p.className || p.class), p && p.provider);
1772
+ };
1773
+ const element = renderFn(
1774
+ wp.element, props, createElement, useBlockProps, attributes, setAttributes, blockProps,
1775
+ useWpLocation, useWpTerms, useWpI18n, __, useWpPagePath, useWpPageLink, useWpQuery, useWpMeta, useWpOption,
1776
+ useWpThemeMod, useWpThemeUri, useWpSearch, useWpSearchParams, useWpTitle, useWpContent, useWpExcerpt,
1777
+ useWpPermalink, useWpDate, useWpModifiedDate, useWpAuthor, useWpFeaturedImage, useWpCustomField, useWpField,
1778
+ useWpArchiveTitle, useWpCategories, useWpTaxonomyList, useWpMenu, useWpPrefetch, useWpLanguage, WpLink,
1779
+ isEditorPreview, useIsEditorPreview, forgeWpRenderIcon, WpIcon,
1780
+ resolveWpAsset, forgeWpResolveEditorImage, forgeWpEditorImageAlt, ForgeWpEditorLink,
1781
+ ...scopeVals
1782
+ );
1783
+ return createElement('div', blockProps,
1784
+ inspector,
1785
+ element
1786
+ );
704
1787
  } catch (e) {
705
- console.error("[ForgeWP Editor] Custom edit render failed for block " + block.name + ":", e);
706
- return createElement('div', blockProps, 'Render Error: ' + e.message);
1788
+ console.error("[ForgeWP Editor] Custom preview failed for block " + block.name + "; falling back to WordPress server rendering:", e);
1789
+ return createElement('div', blockProps,
1790
+ inspector,
1791
+ createElement(ServerSideRender, {
1792
+ block: block.name,
1793
+ attributes: attributes
1794
+ })
1795
+ );
707
1796
  }
708
1797
  }
709
1798
 
710
- // Build inspector controls dynamically from attributes
711
- const controls = Object.keys(block.attributes).map(key => {
712
- return createElement(TextControl, {
713
- label: key.charAt(0).toUpperCase() + key.slice(1),
714
- value: attributes[key],
715
- onChange: (val) => setAttributes({ [key]: val })
716
- });
717
- });
718
-
719
1799
  return createElement('div', blockProps,
720
- createElement(InspectorControls, null,
721
- createElement(PanelBody, { title: 'Block Settings', initialOpen: true }, controls)
722
- ),
1800
+ inspector,
723
1801
  createElement(ServerSideRender, {
724
1802
  block: block.name,
725
1803
  attributes: attributes
@@ -727,11 +1805,63 @@ if (window.forgeWpBlocks) {
727
1805
  );
728
1806
  },
729
1807
  save: function() {
730
- return null; // Dynamic blocks return null in save
1808
+ // Parent shells must persist InnerBlocks markup; leaf blocks stay fully dynamic.
1809
+ if (block.isParentShell) {
1810
+ return createElement(InnerBlocks.Content);
1811
+ }
1812
+ return null;
731
1813
  }
732
1814
  });
733
1815
  });
734
1816
  }
1817
+
1818
+ // ── ForgeWP Page Settings — "Hide page title" toggle ─────────────────────────
1819
+ // Lives in the Document sidebar for Pages. Backed by the '_forgewp_hide_title'
1820
+ // post meta field (registered in functions.php), read by page.php and
1821
+ // template-forgewp-builder.php so both templates respect the same setting.
1822
+ (function () {
1823
+ if (!window.wp || !window.wp.plugins || !window.wp.data || !window.wp.coreData) return;
1824
+ const { registerPlugin } = wp.plugins;
1825
+ const PluginDocumentSettingPanel =
1826
+ (wp.editor && wp.editor.PluginDocumentSettingPanel) ||
1827
+ (wp.editPost && wp.editPost.PluginDocumentSettingPanel);
1828
+ if (!PluginDocumentSettingPanel) return;
1829
+
1830
+ const { CheckboxControl } = wp.components;
1831
+ const { useEntityProp } = wp.coreData;
1832
+ const { useSelect } = wp.data;
1833
+ const { createElement: el } = wp.element;
1834
+
1835
+ function ForgeWpPageSettings() {
1836
+ const postType = useSelect(function (select) {
1837
+ return select('core/editor').getCurrentPostType();
1838
+ }, []);
1839
+
1840
+ const [meta, setMeta] = useEntityProp('postType', postType || 'page', 'meta');
1841
+
1842
+ if (postType !== 'page') return null;
1843
+
1844
+ // Default checked when meta is unset (matches PHP + register_post_meta default).
1845
+ const hideTitle = meta && Object.prototype.hasOwnProperty.call(meta, '_forgewp_hide_title')
1846
+ ? !!meta._forgewp_hide_title
1847
+ : true;
1848
+
1849
+ return el(
1850
+ PluginDocumentSettingPanel,
1851
+ { name: 'forgewp-page-settings', title: 'ForgeWP Page Settings', className: 'forgewp-page-settings' },
1852
+ el(CheckboxControl, {
1853
+ label: 'Hide page title',
1854
+ help: 'On by default for ForgeWP layouts. Uncheck to show the core page title. Applies on Default and ForgeWP Builder templates.',
1855
+ checked: hideTitle,
1856
+ onChange: function (value) {
1857
+ setMeta(Object.assign({}, meta || {}, { _forgewp_hide_title: value }));
1858
+ },
1859
+ })
1860
+ );
1861
+ }
1862
+
1863
+ registerPlugin('forgewp-page-settings', { render: ForgeWpPageSettings });
1864
+ })();
735
1865
  `;
736
1866
  writeFileSync(
737
1867
  path.join(outDir, 'assets', 'forgewp-editor.js'),
@@ -741,38 +1871,160 @@ if (window.forgeWpBlocks) {
741
1871
 
742
1872
  writeFileSync(path.join(outDir, 'style.css'), buildStyleCss(config), 'utf8');
743
1873
 
744
- let hydrationData = null;
745
- if (hasHydration) {
1874
+ if (!hydrationData && hasHydration) {
746
1875
  try {
747
1876
  hydrationData = JSON.parse(hydrationManifestJson);
748
1877
  } catch {}
749
1878
  }
750
1879
 
751
1880
  const queries = scanForQueries(themeRoot);
752
- console.log(`[ForgeWP Compiler] Scanned and compiled ${queries.length} REST endpoints: ${queries.map(q => q.queryId).join(', ') || '<none>'}`);
753
-
754
- let functionsPhpContent = buildFunctionsPhp(
755
- config,
756
- assets,
757
- compiledBlocks,
758
- themeRoot,
759
- pagesToAutoCreate,
760
- menus,
761
- hydrationData,
762
- Array.from(i18nKeys),
763
- schemas,
764
- queries,
765
- );
1881
+ if (process.env.FORGEWP_VERBOSE === '1')
1882
+ console.log(
1883
+ `[ForgeWP Compiler] Scanned and compiled ${queries.length} REST endpoints: ${queries.map((q) => q.queryId).join(', ') || '<none>'}`,
1884
+ );
1885
+
1886
+ const WP_CORE_OPTIONS = new Set([
1887
+ 'siteurl',
1888
+ 'blogname',
1889
+ 'blogdescription',
1890
+ 'admin_email',
1891
+ 'blogpublic',
1892
+ 'default_role',
1893
+ 'timezone_string',
1894
+ 'date_format',
1895
+ 'time_format',
1896
+ 'start_of_week',
1897
+ 'permalink_structure',
1898
+ 'upload_path',
1899
+ 'upload_url_path',
1900
+ 'posts_per_page',
1901
+ 'posts_per_rss',
1902
+ 'comments_notify',
1903
+ 'moderation_notify',
1904
+ 'comment_moderation',
1905
+ 'require_name_email',
1906
+ 'thread_comments',
1907
+ 'thread_comments_depth',
1908
+ 'page_comments',
1909
+ 'default_comments_page',
1910
+ 'comment_order',
1911
+ 'comments_per_page',
1912
+ 'default_ping_status',
1913
+ 'default_comment_status',
1914
+ 'show_on_front',
1915
+ 'page_on_front',
1916
+ 'page_for_posts',
1917
+ 'rss_use_excerpt',
1918
+ 'mailserver_url',
1919
+ 'mailserver_login',
1920
+ 'mailserver_pass',
1921
+ 'mailserver_port',
1922
+ 'active_plugins',
1923
+ 'template',
1924
+ 'stylesheet',
1925
+ 'woocommerce_shop_page_id',
1926
+ ]);
1927
+
1928
+ const wpOptions = [];
1929
+ if (config.options && typeof config.options === 'object') {
1930
+ for (const [name, field] of Object.entries(config.options)) {
1931
+ if (WP_CORE_OPTIONS.has(name)) continue;
1932
+
1933
+ const label =
1934
+ field.label ||
1935
+ name.replace(/[_-]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
1936
+
1937
+ wpOptions.push({
1938
+ name,
1939
+ label,
1940
+ defaultValue: field.default || '',
1941
+ postType:
1942
+ field._type === 'postPicker' ? field.postType || 'post' : null,
1943
+ });
1944
+ }
1945
+ }
1946
+
1947
+ if (wpOptions.length > 0) {
1948
+ if (process.env.FORGEWP_VERBOSE === '1')
1949
+ console.log(
1950
+ `[ForgeWP Compiler] Detected ${wpOptions.length} site option(s) via config.options: ${wpOptions.map((o) => o.name).join(', ')}`,
1951
+ );
1952
+ }
1953
+
1954
+ // The Theme Options post-picker field (optionPostPicker) uses Select2 for its AJAX
1955
+ // search dropdown. WordPress core does NOT ship a public 'select2' script/style handle,
1956
+ // so we vendor our own copy into the exported theme rather than relying on one.
1957
+ if (wpOptions.some((o) => o.postType)) {
1958
+ try {
1959
+ const vendorRequire = createRequire(import.meta.url);
1960
+ const select2JsPath = vendorRequire.resolve(
1961
+ 'select2/dist/js/select2.min.js',
1962
+ );
1963
+ const select2CssPath = vendorRequire.resolve(
1964
+ 'select2/dist/css/select2.min.css',
1965
+ );
1966
+ const select2VendorOut = path.join(assetsOut, 'vendor', 'select2');
1967
+ mkdirSync(select2VendorOut, { recursive: true });
1968
+ copyFileSync(
1969
+ select2JsPath,
1970
+ path.join(select2VendorOut, 'select2.min.js'),
1971
+ );
1972
+ copyFileSync(
1973
+ select2CssPath,
1974
+ path.join(select2VendorOut, 'select2.min.css'),
1975
+ );
1976
+ } catch (err) {
1977
+ console.warn(
1978
+ `[ForgeWP Compiler] Failed to vendor select2 assets for the Theme Options post-picker: ${err.message}`,
1979
+ );
1980
+ }
1981
+ }
1982
+
1983
+ let functionsPhpContent;
1984
+ try {
1985
+ functionsPhpContent = buildFunctionsPhp(
1986
+ config,
1987
+ assets,
1988
+ compiledBlocks,
1989
+ themeRoot,
1990
+ pagesToAutoCreate,
1991
+ menus,
1992
+ hydrationData,
1993
+ Array.from(i18nKeys),
1994
+ schemas,
1995
+ queries,
1996
+ wpOptions,
1997
+ );
1998
+ } catch (error) {
1999
+ console.error('CRITICAL ERROR in buildFunctionsPhp:', error.stack);
2000
+ throw error;
2001
+ }
2002
+
2003
+ try {
2004
+ lintFormsUsage(themeRoot, config);
2005
+ } catch (error) {
2006
+ console.warn(
2007
+ `[ForgeWP Compiler] Forms usage lint failed to run: ${error.message}`,
2008
+ );
2009
+ }
766
2010
 
767
2011
  if (projectHooks && typeof projectHooks.processFunctionsPhp === 'function') {
768
- functionsPhpContent = projectHooks.processFunctionsPhp(functionsPhpContent, config);
2012
+ functionsPhpContent = projectHooks.processFunctionsPhp(
2013
+ functionsPhpContent,
2014
+ config,
2015
+ );
769
2016
  }
770
2017
 
771
2018
  // Execute plugin functions.php transformation hooks
772
2019
  if (config.plugins && Array.isArray(config.plugins)) {
773
2020
  for (const plugin of config.plugins) {
774
2021
  if (typeof plugin.transformFunctionsPhp === 'function') {
775
- functionsPhpContent = plugin.transformFunctionsPhp(functionsPhpContent, config, themeRoot, { fs, path });
2022
+ functionsPhpContent = plugin.transformFunctionsPhp(
2023
+ functionsPhpContent,
2024
+ config,
2025
+ themeRoot,
2026
+ { fs, path },
2027
+ );
776
2028
  }
777
2029
  }
778
2030
  }
@@ -784,7 +2036,8 @@ if (window.forgeWpBlocks) {
784
2036
  .filter((file) => file.endsWith('.php'))
785
2037
  .sort();
786
2038
  if (phpFiles.length > 0) {
787
- let serverPhpContent = '\n\n/**\n * ── PHP Server Escape Hatch (src/server/) ──\n */';
2039
+ let serverPhpContent =
2040
+ '\n\n/**\n * ── PHP Server Escape Hatch (src/server/) ──\n */';
788
2041
  for (const file of phpFiles) {
789
2042
  const filePath = path.join(serverDir, file);
790
2043
  let content = readFileSync(filePath, 'utf8');
@@ -805,14 +2058,21 @@ if (window.forgeWpBlocks) {
805
2058
  'utf8',
806
2059
  );
807
2060
 
808
- // Copy translations.json directly if it exists in the project cms/ folder
809
- const translationsSrc = path.join(themeRoot, 'cms', 'translations.json');
810
- if (existsSync(translationsSrc)) {
811
- copyFileSync(translationsSrc, path.join(outDir, 'translations.json'));
2061
+ // WordPress runtime reads translations.json from the theme root. Serialize
2062
+ // cms/translations.ts (preferred) or the legacy JSON file into that artifact.
2063
+ if (translationsSourcePath(themeRoot)) {
2064
+ writeFileSync(
2065
+ path.join(outDir, 'translations.json'),
2066
+ JSON.stringify(transData, null, 2),
2067
+ 'utf8',
2068
+ );
812
2069
  }
2070
+ // Generate priority preloads for <head> in header.php
2071
+ const preloadTags = generatePreloadTags(effectiveAssetGraph, { isPhp: true });
2072
+
813
2073
  writeFileSync(
814
2074
  path.join(outDir, 'header.php'),
815
- buildHeaderPhp(config),
2075
+ buildHeaderPhp(config, { preloadTags }),
816
2076
  'utf8',
817
2077
  );
818
2078
  writeFileSync(
@@ -823,9 +2083,26 @@ if (window.forgeWpBlocks) {
823
2083
  writeFileSync(path.join(outDir, 'index.php'), buildIndexPhp(), 'utf8');
824
2084
  writeFileSync(path.join(outDir, 'single.php'), buildSinglePhp(), 'utf8');
825
2085
  writeFileSync(path.join(outDir, '404.php'), build404Php(), 'utf8');
826
- writeFileSync(path.join(outDir, 'front-page.php'), buildIndexPhp(), 'utf8');
2086
+ const frontPageOwnsShell =
2087
+ typeof appHtml === 'string' &&
2088
+ appHtml.includes('data-forgewp-owns-shell="true"');
2089
+ writeFileSync(
2090
+ path.join(outDir, 'front-page.php'),
2091
+ buildIndexPhp({ ownsShell: frontPageOwnsShell }),
2092
+ 'utf8',
2093
+ );
827
2094
  writeFileSync(path.join(outDir, 'archive.php'), buildArchivePhp(), 'utf8');
828
2095
  writeFileSync(path.join(outDir, 'page.php'), buildPagePhp(), 'utf8');
2096
+ writeFileSync(
2097
+ path.join(outDir, 'page-placeholder.php'),
2098
+ buildPlaceholderPagePhp(config),
2099
+ 'utf8',
2100
+ );
2101
+ writeFileSync(
2102
+ path.join(outDir, 'template-forgewp-builder.php'),
2103
+ buildBuilderPagePhp(),
2104
+ 'utf8',
2105
+ );
829
2106
 
830
2107
  // Dynamic Custom WP hierarchy templates compiler (single-*, taxonomy-*, archive-*, etc.)
831
2108
  if (existsSync(forgewpDir)) {
@@ -834,32 +2111,49 @@ if (window.forgeWpBlocks) {
834
2111
  const name = file.replace('.html', '');
835
2112
  const isHierarchyTemplate =
836
2113
  (name.startsWith('single-') ||
837
- name.startsWith('archive-') ||
838
- name.startsWith('taxonomy-') ||
839
- name === 'taxonomy') &&
2114
+ name.startsWith('archive-') ||
2115
+ name.startsWith('taxonomy-') ||
2116
+ name === 'taxonomy') &&
840
2117
  file.endsWith('.html') &&
841
2118
  !file.includes('-head');
842
-
2119
+
843
2120
  if (isHierarchyTemplate) {
844
2121
  const rawHtml = readFileSync(path.join(forgewpDir, file), 'utf8');
845
- let processedHtml = processMarkup(rawHtml, config.textDomain);
846
- if (processedHeader) {
847
- const replaced = processedHtml.replace(processedHeader, '');
848
- processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
849
- }
850
- if (processedFooter) {
851
- const replaced = processedHtml.replace(processedFooter, '');
852
- processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
853
- }
854
- processedHtml = processedHtml.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
2122
+ let processedHtml = injectAutoHydrationMarkers(
2123
+ processMarkup(
2124
+ rawHtml,
2125
+ config.textDomain,
2126
+ getRichTextKeysForSlug(`${name}-page`),
2127
+ effectiveAssetGraph,
2128
+ ),
2129
+ );
2130
+ processedHtml = extractTemplateContent(
2131
+ processedHtml,
2132
+ processedHeader,
2133
+ processedFooter,
2134
+ );
2135
+ processedHtml = processedHtml.replace(
2136
+ /<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g,
2137
+ '',
2138
+ );
2139
+ processedHtml = processedHtml.replace(
2140
+ /<\/?forgewp-content-boundary\b[^>]*>/gi,
2141
+ '',
2142
+ );
855
2143
 
856
- writeFileSync(path.join(staticDir, file), replaceAssetPlaceholders(processedHtml), 'utf8');
2144
+ writeFileSync(
2145
+ path.join(staticDir, file),
2146
+ replaceAssetPlaceholders(processedHtml),
2147
+ 'utf8',
2148
+ );
857
2149
 
858
2150
  const headFile = file.replace('.html', '-head.html');
859
2151
  if (existsSync(path.join(forgewpDir, headFile))) {
860
2152
  writeFileSync(
861
2153
  path.join(staticDir, headFile),
862
- replaceAssetPlaceholders(readFileSync(path.join(forgewpDir, headFile), 'utf8')),
2154
+ replaceAssetPlaceholders(
2155
+ readFileSync(path.join(forgewpDir, headFile), 'utf8'),
2156
+ ),
863
2157
  'utf8',
864
2158
  );
865
2159
  }
@@ -897,7 +2191,9 @@ ${phpLoop}
897
2191
  get_footer();
898
2192
  `;
899
2193
  writeFileSync(path.join(outDir, `${name}.php`), phpContent, 'utf8');
900
- console.warn(`[ForgeWP Compiler] Wrote dynamic WP template ${name}.php`);
2194
+ console.warn(
2195
+ `[ForgeWP Compiler] Wrote dynamic WP template ${name}.php`,
2196
+ );
901
2197
  }
902
2198
  }
903
2199
  }
@@ -957,7 +2253,9 @@ get_footer();
957
2253
  }
958
2254
 
959
2255
  if (rawHtml.includes('forgewp-capability-gate-start')) {
960
- const match = rawHtml.match(/forgewp-capability-gate-start\s+allowed="([^"]*)"/);
2256
+ const match = rawHtml.match(
2257
+ /forgewp-capability-gate-start\s+allowed="([^"]*)"/,
2258
+ );
961
2259
  authManifest.authGates.push({
962
2260
  page: slug.replace('template-', ''),
963
2261
  type: 'capability',
@@ -987,34 +2285,28 @@ get_footer();
987
2285
  let redirectSetup = '';
988
2286
  if (redirect) {
989
2287
  if (redirect.startsWith('__FORGEWP_PAGELINK_')) {
990
- const match = redirect.match(/__FORGEWP_PAGELINK_([a-zA-Z0-9_-]+)_DEFAULT_(.*?)__/);
2288
+ const match = redirect.match(
2289
+ /__FORGEWP_PAGELINK_([a-zA-Z0-9_-]+)_DEFAULT_(.*?)__/,
2290
+ );
991
2291
  if (match) {
992
2292
  const name = match[1];
993
2293
  const decoded = decodeURIComponent(match[2]);
994
2294
  redirectSetup = ` $redirect_url = home_url('${decoded.replace(/'/g, "\\'")}');
995
- $current_lang = function_exists('pll_current_language') ? pll_current_language() : '';
996
- $get_pages_args = array('meta_key' => '_wp_page_template', 'meta_value' => 'page-${name}.php', 'number' => 1);
997
- if (!empty($current_lang)) {
998
- $get_pages_args['lang'] = $current_lang;
999
- }
1000
- $matched_pages = get_pages($get_pages_args);
1001
- if (!empty($matched_pages)) {
1002
- $redirect_url = get_permalink($matched_pages[0]->ID);
2295
+ $__fwp_id = forgewp_resolve_route_page_id('${name}');
2296
+ if ($__fwp_id) {
2297
+ $redirect_url = get_permalink($__fwp_id);
1003
2298
  }`;
1004
2299
  redirectUrlExpr = '$redirect_url';
1005
2300
  } else {
1006
- const matchPlain = redirect.match(/__FORGEWP_PAGELINK_([a-zA-Z0-9_-]+)__/);
2301
+ const matchPlain = redirect.match(
2302
+ /__FORGEWP_PAGELINK_([a-zA-Z0-9_-]+)__/,
2303
+ );
1007
2304
  if (matchPlain) {
1008
2305
  const name = matchPlain[1];
1009
2306
  redirectSetup = ` $redirect_url = home_url('/');
1010
- $current_lang = function_exists('pll_current_language') ? pll_current_language() : '';
1011
- $get_pages_args = array('meta_key' => '_wp_page_template', 'meta_value' => 'page-${name}.php', 'number' => 1);
1012
- if (!empty($current_lang)) {
1013
- $get_pages_args['lang'] = $current_lang;
1014
- }
1015
- $matched_pages = get_pages($get_pages_args);
1016
- if (!empty($matched_pages)) {
1017
- $redirect_url = get_permalink($matched_pages[0]->ID);
2307
+ $__fwp_id = forgewp_resolve_route_page_id('${name}');
2308
+ if ($__fwp_id) {
2309
+ $redirect_url = get_permalink($__fwp_id);
1018
2310
  }`;
1019
2311
  redirectUrlExpr = '$redirect_url';
1020
2312
  } else {
@@ -1024,14 +2316,9 @@ get_footer();
1024
2316
  } else if (redirect.startsWith('template:')) {
1025
2317
  const name = redirect.replace('template:', '');
1026
2318
  redirectSetup = ` $redirect_url = home_url('/');
1027
- $current_lang = function_exists('pll_current_language') ? pll_current_language() : '';
1028
- $get_pages_args = array('meta_key' => '_wp_page_template', 'meta_value' => 'page-${name}.php', 'number' => 1);
1029
- if (!empty($current_lang)) {
1030
- $get_pages_args['lang'] = $current_lang;
1031
- }
1032
- $matched_pages = get_pages($get_pages_args);
1033
- if (!empty($matched_pages)) {
1034
- $redirect_url = get_permalink($matched_pages[0]->ID);
2319
+ $__fwp_id = forgewp_resolve_route_page_id('${name}');
2320
+ if ($__fwp_id) {
2321
+ $redirect_url = get_permalink($__fwp_id);
1035
2322
  }`;
1036
2323
  redirectUrlExpr = '$redirect_url';
1037
2324
  } else {
@@ -1049,14 +2336,9 @@ ${redirectSetup ? redirectSetup + '\n' : ''} wp_safe_redirect( ${redirectUrlE
1049
2336
  $email_verified = ( $verified_meta === '' ) || ( $verified_meta === '1' ) || ( $verified_meta === true );
1050
2337
  if ( $email_verification_enabled && ! $email_verified ) {
1051
2338
  $verify_url = home_url( '/verify-email' );
1052
- $current_lang = function_exists('pll_current_language') ? pll_current_language() : '';
1053
- $get_pages_args = array('meta_key' => '_wp_page_template', 'meta_value' => 'page-verify-email-page.php', 'number' => 1);
1054
- if (!empty($current_lang)) {
1055
- $get_pages_args['lang'] = $current_lang;
1056
- }
1057
- $matched_pages = get_pages($get_pages_args);
1058
- if (!empty($matched_pages)) {
1059
- $verify_url = get_permalink($matched_pages[0]->ID);
2339
+ $__fwp_id = forgewp_resolve_route_page_id('verify-email-page');
2340
+ if ($__fwp_id) {
2341
+ $verify_url = get_permalink($__fwp_id);
1060
2342
  }
1061
2343
  wp_safe_redirect( $verify_url );
1062
2344
  exit;
@@ -1071,32 +2353,105 @@ if ( ! current_user_can( '${allowed}' ) ) {
1071
2353
  }`;
1072
2354
  }
1073
2355
  }
1074
- cleanedRawHtml = rawHtml.replace(/<forgewp-require-auth\s*([^>]*)\/?>/gi, '');
1075
- cleanedRawHtml = cleanedRawHtml.replace(/<\/forgewp-require-auth>/gi, '');
2356
+ cleanedRawHtml = rawHtml.replace(
2357
+ /<forgewp-require-auth\s*([^>]*)\/?>/gi,
2358
+ '',
2359
+ );
2360
+ cleanedRawHtml = cleanedRawHtml.replace(
2361
+ /<\/forgewp-require-auth>/gi,
2362
+ '',
2363
+ );
1076
2364
  }
1077
2365
 
1078
- let processedHtml = processMarkup(cleanedRawHtml, config.textDomain);
1079
- if (processedHeader) {
1080
- const replaced = processedHtml.replace(processedHeader, '');
1081
- processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
1082
- }
1083
- if (processedFooter) {
1084
- const replaced = processedHtml.replace(processedFooter, '');
1085
- processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
2366
+ let pageConfigHeader = true;
2367
+ let pageConfigFooter = true;
2368
+ let pageConfigLayout = 'default';
2369
+
2370
+ const configMatch = rawHtml.match(
2371
+ /<forgewp-page-config\s*([^>]*)\/?>/i,
2372
+ );
2373
+ if (configMatch) {
2374
+ const attribs = configMatch[1];
2375
+ const headerAttr = attribs.match(/header="([^"]*)"/i);
2376
+ const footerAttr = attribs.match(/footer="([^"]*)"/i);
2377
+ const layoutAttr = attribs.match(/layout="([^"]*)"/i);
2378
+
2379
+ if (headerAttr) {
2380
+ if (headerAttr[1] === 'false') pageConfigHeader = false;
2381
+ else if (headerAttr[1] === 'true') pageConfigHeader = true;
2382
+ else pageConfigHeader = headerAttr[1];
2383
+ }
2384
+ if (footerAttr) {
2385
+ if (footerAttr[1] === 'false') pageConfigFooter = false;
2386
+ else if (footerAttr[1] === 'true') pageConfigFooter = true;
2387
+ else pageConfigFooter = footerAttr[1];
2388
+ }
2389
+ if (layoutAttr) {
2390
+ pageConfigLayout = layoutAttr[1];
2391
+ if (pageConfigLayout === 'blank' || pageConfigLayout === 'false') {
2392
+ pageConfigHeader = false;
2393
+ pageConfigFooter = false;
2394
+ }
2395
+ }
2396
+ cleanedRawHtml = cleanedRawHtml.replace(
2397
+ /<forgewp-page-config\s*([^>]*)\/?>/gi,
2398
+ '',
2399
+ );
2400
+ cleanedRawHtml = cleanedRawHtml.replace(
2401
+ /<\/forgewp-page-config>/gi,
2402
+ '',
2403
+ );
1086
2404
  }
1087
- processedHtml = processedHtml.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
1088
2405
 
1089
- if (projectHooks && typeof projectHooks.processTemplateMarkup === 'function') {
1090
- processedHtml = projectHooks.processTemplateMarkup(slug, processedHtml, config);
2406
+ let processedHtml = injectAutoHydrationMarkers(
2407
+ processMarkup(
2408
+ cleanedRawHtml,
2409
+ config.textDomain,
2410
+ getRichTextKeysForSlug(slug.replace('template-', '')),
2411
+ effectiveAssetGraph,
2412
+ ),
2413
+ );
2414
+ const layoutIsBlank =
2415
+ pageConfigLayout === 'blank' || pageConfigLayout === 'false';
2416
+ processedHtml = extractTemplateContent(
2417
+ processedHtml,
2418
+ processedHeader,
2419
+ processedFooter,
2420
+ { ownsShell: layoutIsBlank },
2421
+ );
2422
+ processedHtml = processedHtml.replace(
2423
+ /<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g,
2424
+ '',
2425
+ );
2426
+ processedHtml = processedHtml.replace(
2427
+ /<\/?forgewp-content-boundary\b[^>]*>/gi,
2428
+ '',
2429
+ );
2430
+
2431
+ if (
2432
+ projectHooks &&
2433
+ typeof projectHooks.processTemplateMarkup === 'function'
2434
+ ) {
2435
+ processedHtml = projectHooks.processTemplateMarkup(
2436
+ slug,
2437
+ processedHtml,
2438
+ config,
2439
+ );
1091
2440
  }
1092
2441
 
1093
- writeFileSync(path.join(staticDir, file), replaceAssetPlaceholders(processedHtml), 'utf8');
2442
+ writeFileSync(
2443
+ path.join(staticDir, file),
2444
+ replaceAssetPlaceholders(processedHtml),
2445
+ 'utf8',
2446
+ );
1094
2447
 
1095
2448
  const headFile = file.replace('.html', '-head.html');
1096
2449
  if (existsSync(path.join(forgewpDir, headFile))) {
1097
2450
  writeFileSync(
1098
2451
  path.join(staticDir, headFile),
1099
- replaceAssetPlaceholders(readFileSync(path.join(forgewpDir, headFile), 'utf8')),
2452
+ replaceAssetPlaceholders(
2453
+ readFileSync(path.join(forgewpDir, headFile), 'utf8'),
2454
+ ),
1100
2455
  'utf8',
1101
2456
  );
1102
2457
  }
@@ -1107,6 +2462,47 @@ if ( ! current_user_can( '${allowed}' ) ) {
1107
2462
  .split('-')
1108
2463
  .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
1109
2464
  .join(' ');
2465
+
2466
+ let headerCall = 'get_header();';
2467
+ let footerCall = 'get_footer();';
2468
+
2469
+ if (pageConfigHeader === false) {
2470
+ headerCall = `?><!DOCTYPE html>
2471
+ <html <?php language_attributes(); ?>>
2472
+ <head>
2473
+ <meta charset="<?php bloginfo('charset'); ?>">
2474
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2475
+ <?php
2476
+ if ( ! forgewp_seo_plugin_active() ) {
2477
+ $target = forgewp_resolve_head_target();
2478
+ if (file_exists($target)) {
2479
+ ob_start();
2480
+ include $target;
2481
+ echo preg_replace('/<title>.*?<\\/title>/is', '', ob_get_clean());
2482
+ }
2483
+ }
2484
+ ?>
2485
+ <?php wp_head(); ?>
2486
+ <style>
2487
+ ${LINK_RESET_CSS}
2488
+ </style>
2489
+ </head>
2490
+ <body <?php body_class(); ?>>
2491
+ <?php wp_body_open(); ?>
2492
+ <?php`;
2493
+ } else if (typeof pageConfigHeader === 'string') {
2494
+ headerCall = `get_header('${pageConfigHeader}');`;
2495
+ }
2496
+
2497
+ if (pageConfigFooter === false) {
2498
+ footerCall = `?>
2499
+ <?php wp_footer(); ?>
2500
+ </body>
2501
+ </html>`;
2502
+ } else if (typeof pageConfigFooter === 'string') {
2503
+ footerCall = `get_footer('${pageConfigFooter}');`;
2504
+ }
2505
+
1110
2506
  const phpContent = `<?php
1111
2507
  /**
1112
2508
  * Template Name: ${templateName}
@@ -1114,14 +2510,11 @@ if ( ! current_user_can( '${allowed}' ) ) {
1114
2510
  * @package ${config.textDomain}
1115
2511
  */
1116
2512
  ${redirectPhp}
1117
- get_header();
2513
+ ${headerCall}
1118
2514
 
1119
- $markup_file = get_template_directory() . '/forgewp-static/${file}';
1120
- if (file_exists($markup_file)) {
1121
- include $markup_file;
1122
- }
2515
+ ${buildGeneratedPageTemplateContentPhp(`forgewp-static/${file}`)}
1123
2516
 
1124
- get_footer();
2517
+ ${footerCall}
1125
2518
  `;
1126
2519
  writeFileSync(
1127
2520
  path.join(outDir, `page-${slug.replace('template-', '')}.php`),
@@ -1170,12 +2563,19 @@ get_footer();
1170
2563
  };
1171
2564
 
1172
2565
  // Smartly extract background and text colors from palette to style the WP editor canvas
1173
- if (config.settings.color.palette && Array.isArray(config.settings.color.palette)) {
2566
+ if (
2567
+ config.settings.color.palette &&
2568
+ Array.isArray(config.settings.color.palette)
2569
+ ) {
1174
2570
  if (!themeJson.styles) themeJson.styles = {};
1175
2571
  if (!themeJson.styles.color) themeJson.styles.color = {};
1176
2572
 
1177
- const bgPreset = config.settings.color.palette.find(p => p && p.slug === 'background');
1178
- const textPreset = config.settings.color.palette.find(p => p && (p.slug === 'text' || p.slug === 'primary'));
2573
+ const bgPreset = config.settings.color.palette.find(
2574
+ (p) => p && p.slug === 'background',
2575
+ );
2576
+ const textPreset = config.settings.color.palette.find(
2577
+ (p) => p && (p.slug === 'text' || p.slug === 'primary'),
2578
+ );
1179
2579
 
1180
2580
  if (bgPreset && !themeJson.styles.color.background) {
1181
2581
  themeJson.styles.color.background = bgPreset.color;
@@ -1228,10 +2628,10 @@ function extractUseWpQueryArgs(fileContent) {
1228
2628
  let endIdx = startIdx;
1229
2629
  let inString = false;
1230
2630
  let stringChar = null;
1231
-
2631
+
1232
2632
  for (let i = startIdx; i < fileContent.length; i++) {
1233
2633
  const char = fileContent[i];
1234
-
2634
+
1235
2635
  if (inString) {
1236
2636
  if (char === stringChar && fileContent[i - 1] !== '\\') {
1237
2637
  inString = false;
@@ -1243,7 +2643,7 @@ function extractUseWpQueryArgs(fileContent) {
1243
2643
  stringChar = char;
1244
2644
  continue;
1245
2645
  }
1246
-
2646
+
1247
2647
  if (char === '(') parenCount++;
1248
2648
  if (char === ')') {
1249
2649
  parenCount--;
@@ -1253,7 +2653,7 @@ function extractUseWpQueryArgs(fileContent) {
1253
2653
  }
1254
2654
  }
1255
2655
  }
1256
-
2656
+
1257
2657
  if (endIdx > startIdx) {
1258
2658
  const argText = fileContent.slice(startIdx, endIdx).trim();
1259
2659
  queries.push(argText);
@@ -1268,17 +2668,29 @@ function safeEvalObject(objText) {
1268
2668
  return null;
1269
2669
  }
1270
2670
  try {
1271
- const sandbox = new Proxy({}, {
1272
- has() { return true; },
1273
- get(target, prop) {
1274
- if (prop === 'Symbol(Symbol.toPrimitive)') return undefined;
1275
- return `__DYNAMIC_${String(prop)}__`;
1276
- }
1277
- });
1278
- const fn = new Function('sandbox', `with(sandbox) { return (${objText}); }`);
2671
+ const sandbox = new Proxy(
2672
+ {},
2673
+ {
2674
+ has() {
2675
+ return true;
2676
+ },
2677
+ get(target, prop) {
2678
+ if (prop === 'Symbol(Symbol.toPrimitive)') return undefined;
2679
+ return `__DYNAMIC_${String(prop)}__`;
2680
+ },
2681
+ },
2682
+ );
2683
+ const fn = new Function(
2684
+ 'sandbox',
2685
+ `with(sandbox) { return (${objText}); }`,
2686
+ );
1279
2687
  return fn(sandbox);
1280
2688
  } catch (e) {
1281
- console.warn('[ForgeWP Query Parser] safeEvalObject failed for:', objText, e.message);
2689
+ console.warn(
2690
+ '[ForgeWP Query Parser] safeEvalObject failed for:',
2691
+ objText,
2692
+ e.message,
2693
+ );
1282
2694
  return null;
1283
2695
  }
1284
2696
  }
@@ -1310,7 +2722,9 @@ function scanForQueries(themeRoot) {
1310
2722
  if (!parsed.queryId) {
1311
2723
  const baseName = path.basename(file, path.extname(file));
1312
2724
  const postTypePart = String(parsed.postType).toLowerCase();
1313
- const cleanBase = baseName.toLowerCase().replace(/[^a-z0-9]+/g, '-');
2725
+ const cleanBase = baseName
2726
+ .toLowerCase()
2727
+ .replace(/[^a-z0-9]+/g, '-');
1314
2728
  parsed.queryId = cleanBase + '-' + postTypePart;
1315
2729
  }
1316
2730
  queries.push(parsed);
@@ -1326,7 +2740,10 @@ function scanForQueries(themeRoot) {
1326
2740
  const uniqueQueries = [];
1327
2741
  const seenIds = new Set();
1328
2742
  for (const q of queries) {
1329
- const cleanId = q.queryId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
2743
+ const cleanId = q.queryId
2744
+ .toLowerCase()
2745
+ .replace(/[^a-z0-9]+/g, '-')
2746
+ .replace(/(^-|-$)/g, '');
1330
2747
  if (!seenIds.has(cleanId)) {
1331
2748
  seenIds.add(cleanId);
1332
2749
  uniqueQueries.push(q);
@@ -1334,3 +2751,163 @@ function scanForQueries(themeRoot) {
1334
2751
  }
1335
2752
  return uniqueQueries;
1336
2753
  }
2754
+
2755
+ function scanForWpOptions(themeRoot) {
2756
+ const optionsPath = path.join(themeRoot, 'cms', 'site-options.ts');
2757
+ if (!existsSync(optionsPath)) return [];
2758
+
2759
+ // WordPress core options that are already managed in wp-admin Settings pages —
2760
+ // exclude them from the auto-generated Theme Options page.
2761
+ const WP_CORE_OPTIONS = new Set([
2762
+ 'siteurl',
2763
+ 'blogname',
2764
+ 'blogdescription',
2765
+ 'admin_email',
2766
+ 'blogpublic',
2767
+ 'default_role',
2768
+ 'timezone_string',
2769
+ 'date_format',
2770
+ 'time_format',
2771
+ 'start_of_week',
2772
+ 'permalink_structure',
2773
+ 'upload_path',
2774
+ 'upload_url_path',
2775
+ 'posts_per_page',
2776
+ 'posts_per_rss',
2777
+ 'comments_notify',
2778
+ 'moderation_notify',
2779
+ 'comment_moderation',
2780
+ 'require_name_email',
2781
+ 'thread_comments',
2782
+ 'thread_comments_depth',
2783
+ 'page_comments',
2784
+ 'default_comments_page',
2785
+ 'comment_order',
2786
+ 'comments_per_page',
2787
+ 'default_ping_status',
2788
+ 'default_comment_status',
2789
+ 'show_on_front',
2790
+ 'page_on_front',
2791
+ 'page_for_posts',
2792
+ 'rss_use_excerpt',
2793
+ 'mailserver_url',
2794
+ 'mailserver_login',
2795
+ 'mailserver_pass',
2796
+ 'mailserver_port',
2797
+ 'active_plugins',
2798
+ 'template',
2799
+ 'stylesheet',
2800
+ 'woocommerce_shop_page_id',
2801
+ ]);
2802
+
2803
+ const optionsMap = new Map(); // name -> { name, label, defaultValue, postType? }
2804
+
2805
+ const content = readFileSync(optionsPath, 'utf8');
2806
+ if (content.includes('defineWpOptions')) {
2807
+ const objText = extractDefineWpOptionsArgs(content);
2808
+ if (objText) {
2809
+ const schema = evalDefineWpOptions(objText);
2810
+ if (schema && typeof schema === 'object') {
2811
+ for (const [name, field] of Object.entries(schema)) {
2812
+ if (WP_CORE_OPTIONS.has(name)) continue;
2813
+
2814
+ const label =
2815
+ field.label ||
2816
+ name
2817
+ .replace(/[_-]+/g, ' ')
2818
+ .replace(/\b\w/g, (c) => c.toUpperCase());
2819
+
2820
+ optionsMap.set(name, {
2821
+ name,
2822
+ label,
2823
+ defaultValue: field.default || '',
2824
+ postType:
2825
+ field._type === 'postPicker' ? field.postType || 'post' : null,
2826
+ });
2827
+ }
2828
+ }
2829
+ }
2830
+ }
2831
+
2832
+ return Array.from(optionsMap.values());
2833
+ }
2834
+
2835
+ function extractDefineWpOptionsArgs(fileContent) {
2836
+ const matchIdx = fileContent.indexOf('defineWpOptions');
2837
+ if (matchIdx === -1) return null;
2838
+ const startIdx = fileContent.indexOf('(', matchIdx);
2839
+ if (startIdx === -1) return null;
2840
+
2841
+ let parenCount = 0;
2842
+ let inString = false;
2843
+ let stringChar = '';
2844
+ let endIdx = -1;
2845
+
2846
+ for (let i = startIdx; i < fileContent.length; i++) {
2847
+ const char = fileContent[i];
2848
+ if (inString) {
2849
+ if (char === stringChar && fileContent[i - 1] !== '\\') {
2850
+ inString = false;
2851
+ }
2852
+ continue;
2853
+ }
2854
+ if (char === '"' || char === "'" || char === '`') {
2855
+ inString = true;
2856
+ stringChar = char;
2857
+ continue;
2858
+ }
2859
+ if (char === '(') parenCount++;
2860
+ if (char === ')') {
2861
+ parenCount--;
2862
+ if (parenCount === 0) {
2863
+ endIdx = i;
2864
+ break;
2865
+ }
2866
+ }
2867
+ }
2868
+
2869
+ if (endIdx > startIdx) {
2870
+ return fileContent.slice(startIdx + 1, endIdx).trim();
2871
+ }
2872
+ return null;
2873
+ }
2874
+
2875
+ function evalDefineWpOptions(objText) {
2876
+ if (!objText) return null;
2877
+ try {
2878
+ const sandbox = {
2879
+ optionText: (cfg = {}) => ({ _type: 'text', ...cfg }),
2880
+ optionUrl: (cfg = {}) => ({ _type: 'url', ...cfg }),
2881
+ optionEmail: (cfg = {}) => ({ _type: 'email', ...cfg }),
2882
+ optionTextarea: (cfg = {}) => ({ _type: 'textarea', ...cfg }),
2883
+ optionToggle: (cfg = {}) => ({ _type: 'toggle', ...cfg }),
2884
+ optionNumber: (cfg = {}) => ({ _type: 'number', ...cfg }),
2885
+ optionPostPicker: (cfg = {}) => ({ _type: 'postPicker', ...cfg }),
2886
+ };
2887
+ const fn = new Function(
2888
+ 'optionText',
2889
+ 'optionUrl',
2890
+ 'optionEmail',
2891
+ 'optionTextarea',
2892
+ 'optionToggle',
2893
+ 'optionNumber',
2894
+ 'optionPostPicker',
2895
+ `return (${objText});`,
2896
+ );
2897
+ return fn(
2898
+ sandbox.optionText,
2899
+ sandbox.optionUrl,
2900
+ sandbox.optionEmail,
2901
+ sandbox.optionTextarea,
2902
+ sandbox.optionToggle,
2903
+ sandbox.optionNumber,
2904
+ sandbox.optionPostPicker,
2905
+ );
2906
+ } catch (e) {
2907
+ console.warn(
2908
+ '[ForgeWP Options Parser] evalDefineWpOptions failed:',
2909
+ e.message,
2910
+ );
2911
+ return null;
2912
+ }
2913
+ }