@forgewp/compiler 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +70 -3
  2. package/bin/add.js +30 -15
  3. package/bin/analyze.js +66 -1
  4. package/bin/cli.js +149 -70
  5. package/bin/doctor.js +21 -12
  6. package/bin/export.js +69 -20
  7. package/bin/fresh.js +6 -1
  8. package/bin/i18n-extract.js +3 -10
  9. package/bin/i18n-translate.js +15 -24
  10. package/bin/make-block.js +24 -0
  11. package/bin/make-editable.js +166 -0
  12. package/bin/make-form.js +131 -0
  13. package/bin/make-island.js +11 -0
  14. package/bin/make-loop.js +147 -0
  15. package/bin/make-mail.js +27 -0
  16. package/bin/make-page.js +83 -0
  17. package/bin/make-post-type.js +68 -29
  18. package/bin/make-sandbox.js +609 -0
  19. package/bin/make-section.js +221 -0
  20. package/bin/make-shell.js +375 -0
  21. package/bin/repair.js +14 -26
  22. package/bin/seed.js +119 -0
  23. package/bin/sync-routes.js +107 -85
  24. package/lib/adapters/html-adapter.js +13 -3
  25. package/lib/adapters/stub-adapter.js +10 -2
  26. package/lib/add-component.js +153 -92
  27. package/lib/asset-loader.js +333 -1
  28. package/lib/assets/asset-graph.js +432 -0
  29. package/lib/assets/asset-pipeline.js +125 -0
  30. package/lib/assets/diagnostics-report.js +345 -0
  31. package/lib/assets/external-fetcher.js +173 -0
  32. package/lib/assets/font-orchestrator.js +348 -0
  33. package/lib/assets/font-usage-scanner.js +242 -0
  34. package/lib/assets/image-optimizer.js +229 -0
  35. package/lib/assets/index.js +51 -0
  36. package/lib/assets/preload-generator.js +70 -0
  37. package/lib/assets/public-url.js +153 -0
  38. package/lib/block-authoring-help.js +11 -0
  39. package/lib/blocks/ast-parser.js +67 -0
  40. package/lib/blocks/discover-blocks.js +146 -0
  41. package/lib/blocks/editor-scope.js +733 -0
  42. package/lib/blocks/editor-transpiler.js +1229 -0
  43. package/lib/blocks/index.js +2838 -0
  44. package/lib/blocks/php-transpiler.js +4928 -0
  45. package/lib/blocks/scanner.js +1487 -0
  46. package/lib/blocks/shared-utils.js +290 -0
  47. package/lib/blocks/source-sanitize.js +1449 -0
  48. package/lib/blueprints.js +77 -5
  49. package/lib/build-assets.js +38 -33
  50. package/lib/collect-page-template-routes.js +102 -0
  51. package/lib/collect-static-routes.js +175 -0
  52. package/lib/diagnostics.js +58 -33
  53. package/lib/export-theme.js +84 -5
  54. package/lib/extract-template-content.js +90 -0
  55. package/lib/forms-preview.js +42 -0
  56. package/lib/functions/cpt-routing.js +69 -0
  57. package/lib/functions/forms.js +2461 -0
  58. package/lib/functions/hydration-enqueuer.js +400 -0
  59. package/lib/functions/index.js +1623 -0
  60. package/lib/functions/load-menus.js +112 -0
  61. package/lib/functions/load-translations.js +148 -0
  62. package/lib/functions/rest-endpoints.js +2923 -0
  63. package/lib/functions/routing.js +765 -0
  64. package/lib/functions/seed-mock-data.js +392 -0
  65. package/lib/functions/seed-products.js +481 -0
  66. package/lib/functions/settings-page.js +273 -0
  67. package/lib/functions/theme-setup.js +494 -0
  68. package/lib/generate-theme.js +2076 -303
  69. package/lib/hydration/editable-schemas.js +332 -0
  70. package/lib/hydration/enter-hidden-initial.js +65 -0
  71. package/lib/hydration/form-schemas.js +227 -0
  72. package/lib/hydration/index.js +12 -0
  73. package/lib/hydration/is-interactive.js +951 -0
  74. package/lib/hydration/island-split.js +1231 -0
  75. package/lib/hydration/islands-scanner.js +599 -0
  76. package/lib/hydration/resolve-island-chunk.js +103 -0
  77. package/lib/hydration/resolve-island-component.js +52 -0
  78. package/lib/hydration/rollup-inputs.js +81 -0
  79. package/lib/hydration/root-class-extractor.js +220 -0
  80. package/lib/hydration/scan-app-providers.js +154 -0
  81. package/lib/hydration/static-lint.js +382 -0
  82. package/lib/hydration/transform.js +257 -0
  83. package/lib/hydration/uses-block-area.js +49 -0
  84. package/lib/hydration/utils.js +119 -0
  85. package/lib/i18n/translation-cache.js +141 -0
  86. package/lib/icon-registry.js +72 -0
  87. package/lib/index.d.ts +324 -8
  88. package/lib/index.js +3 -2
  89. package/lib/load-config.js +338 -144
  90. package/lib/mail-templates.js +37 -0
  91. package/lib/markup-processor.js +483 -92
  92. package/lib/node-runtime.js +7 -0
  93. package/lib/page-config-plugin.js +84 -0
  94. package/lib/php-builders.js +383 -42
  95. package/lib/react-adapter.js +1053 -246
  96. package/lib/registration-metadata.js +11 -0
  97. package/lib/render-theme.mts +1410 -543
  98. package/lib/route-layout.js +76 -0
  99. package/lib/template-discovery.js +58 -0
  100. package/lib/theme-compatibility.js +32 -0
  101. package/lib/validate-export.js +51 -2
  102. package/lib/validate.js +27 -5
  103. package/lib/virtual-plugin.js +319 -0
  104. package/lib/walkthrough.md +26 -0
  105. package/package.json +17 -5
  106. package/templates/PresetsStyle.tsx +1 -1
  107. package/templates/auth/cms/email-logs.json +9 -0
  108. package/templates/auth/cms/menus.json +11 -0
  109. package/templates/auth/cms/mock-data.json +123 -0
  110. package/templates/auth/cms/roles.json +7 -0
  111. package/templates/auth/cms/sessions.json +1 -0
  112. package/templates/auth/cms/site-settings.json +28 -0
  113. package/templates/auth/cms/translations.json +4 -0
  114. package/templates/auth/cms/users.json +46 -0
  115. package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
  116. package/templates/auth/components/forgot-password-form-wrapper.tsx +141 -0
  117. package/templates/auth/components/login-form-wrapper.tsx +300 -0
  118. package/templates/auth/components/reset-password-form-wrapper.tsx +190 -0
  119. package/templates/auth/components/signup-form-wrapper.tsx +257 -0
  120. package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
  121. package/templates/auth/pages/DashboardPage.tsx +12 -0
  122. package/templates/auth/pages/ForgotPasswordPage.tsx +11 -0
  123. package/templates/auth/pages/LoginPage.tsx +11 -0
  124. package/templates/auth/pages/ResetPasswordPage.tsx +11 -0
  125. package/templates/auth/pages/SignUpPage.tsx +11 -0
  126. package/templates/auth/pages/VerifyEmailPage.tsx +11 -0
  127. package/templates/auth/ui/button.tsx +57 -0
  128. package/templates/auth/ui/card.tsx +76 -0
  129. package/templates/auth/ui/field.tsx +242 -0
  130. package/templates/auth/ui/input.tsx +22 -0
  131. package/templates/auth/ui/label.tsx +24 -0
  132. package/templates/auth/ui/separator.tsx +31 -0
  133. package/templates/forgewp-config.ts +70 -3
  134. package/templates/menus.json +12 -10
  135. package/templates/mock-data.json +122 -433
  136. package/templates/products.json +5 -0
  137. package/templates/roles.json +7 -0
  138. package/templates/sessions.json +1 -0
  139. package/templates/users.json +38 -0
  140. package/templates/wordpress.tsx +1835 -1297
  141. package/bin/make-template.js +0 -145
  142. package/lib/block-compiler.js +0 -552
  143. package/lib/functions-builder.js +0 -2044
  144. package/lib/hydration-scanner.js +0 -821
@@ -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');
@@ -212,17 +332,34 @@ export async function generateTheme({
212
332
  }
213
333
  }
214
334
 
335
+ const manifestPath = path.join(themeRoot, 'dist', '.vite', 'manifest.json');
336
+ let viteManifest = {};
337
+ if (existsSync(manifestPath)) {
338
+ try {
339
+ viteManifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
340
+ } catch (e) {
341
+ console.warn('Failed to parse Vite manifest.json:', e.message);
342
+ }
343
+ }
344
+
345
+ const replaceAssetPlaceholders = (markup) => {
346
+ if (!markup) return '';
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
+ );
357
+ };
358
+
215
359
  let hydrationManifestJson = '{}';
360
+ let hydrationData = null;
216
361
  if (hasHydration) {
217
- const manifestPath = path.join(themeRoot, 'dist', '.vite', 'manifest.json');
218
- let viteManifest = {};
219
- if (existsSync(manifestPath)) {
220
- try {
221
- viteManifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
222
- } catch (e) {
223
- console.warn('Failed to parse Vite manifest.json:', e.message);
224
- }
225
- } else {
362
+ if (!existsSync(manifestPath)) {
226
363
  console.warn(
227
364
  'Hydration manifest not found at dist/.vite/manifest.json. Hydration asset generation may be incomplete.',
228
365
  );
@@ -238,28 +375,7 @@ export async function generateTheme({
238
375
  }
239
376
 
240
377
  for (const island of hydrationIslands) {
241
- const pascalName = island
242
- .split('-')
243
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
244
- .join('');
245
-
246
- let resolvedChunk = null;
247
- for (const [key, value] of Object.entries(viteManifest)) {
248
- const fileBasename = path.basename(value.file || '');
249
- const cleanName = fileBasename.replace(/-[A-Za-z0-9_-]+\.js$/, '');
250
- if (
251
- key.endsWith(`/${pascalName}.tsx`) ||
252
- key.endsWith(`/${pascalName}.ts`) ||
253
- key.endsWith(`/${island}.tsx`) ||
254
- key.endsWith(`/${island}.ts`) ||
255
- cleanName === island ||
256
- cleanName === pascalName.toLowerCase()
257
- ) {
258
- resolvedChunk = value.file;
259
- break;
260
- }
261
- }
262
-
378
+ const resolvedChunk = resolveIslandChunk(viteManifest, island);
263
379
  if (resolvedChunk) {
264
380
  mapping[island] = resolvedChunk;
265
381
  }
@@ -281,15 +397,48 @@ export async function generateTheme({
281
397
  );
282
398
  }
283
399
 
400
+ const providerIdsJson = JSON.stringify(layoutProviders.map((p) => p.kebab));
284
401
  const hydratorScript = `(function () {
285
402
  const config = window.forgeWpHydration || { themeUri: "", manifest: {} };
286
- 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
+ }
287
431
 
288
432
  const observer = new IntersectionObserver((entries) => {
289
433
  entries.forEach((entry) => {
290
434
  if (entry.isIntersecting) {
291
- const hydrate = entry.target.__forgewpHydrate;
292
- 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
+ }
293
442
  observer.unobserve(entry.target);
294
443
  }
295
444
  });
@@ -316,7 +465,19 @@ export async function generateTheme({
316
465
  },
317
466
  visible: (el, hydrate) => {
318
467
  el.__forgewpHydrate = hydrate;
319
- 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);
320
481
  },
321
482
  interaction: (el, hydrate) => {
322
483
  const run = () => {
@@ -431,6 +592,13 @@ export async function generateTheme({
431
592
  console.error("[ForgeWP Hydrator] Missing data-forgewp-hydrate attribute on hydration boundary.");
432
593
  return;
433
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;
434
602
 
435
603
  const rawProps = el.getAttribute("data-forgewp-props") || "{}";
436
604
  let props = {};
@@ -454,17 +622,11 @@ export async function generateTheme({
454
622
 
455
623
  import(scriptUrl)
456
624
  .then((module) => {
457
- let Component = module.default;
458
- if (!Component) {
459
- Component = Object.values(module).find((val) => typeof val === "function");
460
- if (!Component) {
461
- Component = Object.values(module)[0];
462
- }
463
- }
464
- if (typeof Component !== "function") {
625
+ const Component = resolveExport(module, islandName);
626
+ if (!isReactComponentType(Component)) {
465
627
  const exportsList = Object.keys(module).join(", ");
466
628
  console.error(
467
- "[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. " +
468
630
  "Available exports: " + exportsList
469
631
  );
470
632
  return;
@@ -479,8 +641,35 @@ export async function generateTheme({
479
641
  const React = window.React;
480
642
 
481
643
  if (ReactDOM && React) {
482
- const root = ReactDOM.createRoot(el);
483
- 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
+ });
484
673
  } else {
485
674
  console.error("[ForgeWP Hydration Error] React or ReactDOM not found on window. Ensure main.tsx exposes window.React and window.ReactDOM.");
486
675
  }
@@ -489,6 +678,96 @@ export async function generateTheme({
489
678
  console.error("[ForgeWP Hydrator] Failed to load chunk for " + islandName + ":", err);
490
679
  });
491
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
+ }
492
771
  })();`;
493
772
 
494
773
  writeFileSync(
@@ -496,10 +775,11 @@ export async function generateTheme({
496
775
  hydratorScript,
497
776
  'utf8',
498
777
  );
499
- hydrationManifestJson = JSON.stringify({
778
+ hydrationData = {
500
779
  mainJsFile,
501
780
  mapping,
502
- });
781
+ };
782
+ hydrationManifestJson = JSON.stringify(hydrationData);
503
783
 
504
784
  // Run compiler diagnostics & output detailed metrics
505
785
  const analysis = analyzeHydrationIslands(themeRoot, mapping);
@@ -555,121 +835,722 @@ export async function generateTheme({
555
835
  }
556
836
  }
557
837
 
558
- // Load and merge keys from cms/translations.json
559
- const translationsFileSrc = path.join(themeRoot, 'cms', 'translations.json');
560
- if (existsSync(translationsFileSrc)) {
561
- try {
562
- const transData = JSON.parse(readFileSync(translationsFileSrc, 'utf8'));
563
- for (const locale of Object.keys(transData)) {
564
- if (transData[locale] && typeof transData[locale] === 'object') {
565
- for (const key of Object.keys(transData[locale])) {
566
- i18nKeys.add(key);
567
- }
568
- }
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);
569
844
  }
570
- } catch (e) {
571
- // Ignore parse/read errors during build time
572
845
  }
573
846
  }
574
847
 
575
848
  // Fix nav links and split markup
576
- const processedApp = processMarkup(appHtml, config.textDomain);
577
- const processedHeader = processMarkup(headerHtml, config.textDomain);
578
- const processedFooter = processMarkup(footerHtml, config.textDomain);
579
-
580
- // Extract content (App markup minus Header/Footer)
581
- let contentHtml = processedApp;
582
- if (processedHeader) {
583
- const replaced = contentHtml.replace(processedHeader, '');
584
- contentHtml = replaced !== contentHtml ? replaced : contentHtml.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
585
- }
586
- if (processedFooter) {
587
- const replaced = contentHtml.replace(processedFooter, '');
588
- contentHtml = replaced !== contentHtml ? replaced : contentHtml.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
589
- }
590
- 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
+ );
591
897
 
592
898
  // Process single post template if exists
593
899
  let processedSingle = '';
594
900
  if (singleHtml) {
595
- processedSingle = processMarkup(singleHtml, config.textDomain);
596
- if (processedHeader) {
597
- const replaced = processedSingle.replace(processedHeader, '');
598
- processedSingle = replaced !== processedSingle ? replaced : processedSingle.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
599
- }
600
- if (processedFooter) {
601
- const replaced = processedSingle.replace(processedFooter, '');
602
- processedSingle = replaced !== processedSingle ? replaced : processedSingle.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
603
- }
604
- 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
+ );
605
922
  }
606
923
 
607
924
  // Process 404 template if exists
608
925
  let processedNotFound = '';
609
926
  if (notFoundHtml) {
610
- processedNotFound = processMarkup(notFoundHtml, config.textDomain);
611
- if (processedHeader) {
612
- const replaced = processedNotFound.replace(processedHeader, '');
613
- processedNotFound = replaced !== processedNotFound ? replaced : processedNotFound.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
614
- }
615
- if (processedFooter) {
616
- const replaced = processedNotFound.replace(processedFooter, '');
617
- processedNotFound = replaced !== processedNotFound ? replaced : processedNotFound.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
618
- }
619
- 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
+ );
620
948
  }
621
949
 
622
950
  const staticDir = path.join(outDir, 'forgewp-static');
623
951
  mkdirSync(staticDir, { recursive: true });
624
- writeFileSync(path.join(staticDir, 'content.html'), contentHtml, 'utf8');
625
- writeFileSync(path.join(staticDir, 'header.html'), processedHeader, 'utf8');
626
- writeFileSync(path.join(staticDir, 'footer.html'), 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
+ );
627
967
  if (headHtml) {
628
- writeFileSync(path.join(staticDir, 'head.html'), headHtml, 'utf8');
968
+ writeFileSync(
969
+ path.join(staticDir, 'head.html'),
970
+ replaceAssetPlaceholders(headHtml),
971
+ 'utf8',
972
+ );
629
973
  }
630
974
  if (singleHeadHtml) {
631
975
  writeFileSync(
632
976
  path.join(staticDir, 'single-head.html'),
633
- singleHeadHtml,
977
+ replaceAssetPlaceholders(singleHeadHtml),
634
978
  'utf8',
635
979
  );
636
980
  }
637
981
  if (processedSingle) {
638
- writeFileSync(path.join(staticDir, 'single.html'), processedSingle, 'utf8');
982
+ writeFileSync(
983
+ path.join(staticDir, 'single.html'),
984
+ replaceAssetPlaceholders(processedSingle),
985
+ 'utf8',
986
+ );
639
987
  }
640
988
  if (processedNotFound) {
641
- writeFileSync(path.join(staticDir, '404.html'), processedNotFound, 'utf8');
989
+ writeFileSync(
990
+ path.join(staticDir, '404.html'),
991
+ replaceAssetPlaceholders(processedNotFound),
992
+ 'utf8',
993
+ );
642
994
  }
643
995
 
644
996
  // Archive page (category / tag / date archives)
645
997
  let processedArchive = '';
646
998
  if (archiveHtml) {
647
- processedArchive = processMarkup(archiveHtml, config.textDomain);
648
- if (processedHeader) {
649
- const replaced = processedArchive.replace(processedHeader, '');
650
- processedArchive = replaced !== processedArchive ? replaced : processedArchive.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
651
- }
652
- if (processedFooter) {
653
- const replaced = processedArchive.replace(processedFooter, '');
654
- processedArchive = replaced !== processedArchive ? replaced : processedArchive.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
655
- }
656
- 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
+ );
657
1020
  writeFileSync(
658
1021
  path.join(staticDir, 'archive.html'),
659
- processedArchive,
1022
+ replaceAssetPlaceholders(processedArchive),
660
1023
  'utf8',
661
1024
  );
662
1025
  }
663
1026
 
664
1027
  // Dynamic Gutenberg blocks compilation (Phase 5)
665
- 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);
666
1033
 
667
1034
  const editorScriptContent = `
668
1035
  const { registerBlockType } = wp.blocks;
669
- const { createElement } = wp.element;
670
- const { InspectorControls, useBlockProps } = wp.blockEditor;
671
- const { PanelBody, TextControl } = wp.components;
672
- 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
+ }
673
1554
 
674
1555
  if (window.forgeWpBlocks) {
675
1556
  window.forgeWpBlocks.forEach(block => {
@@ -677,36 +1558,246 @@ if (window.forgeWpBlocks) {
677
1558
  title: block.title,
678
1559
  icon: block.icon,
679
1560
  category: block.category,
1561
+ description: block.description || '',
1562
+ example: block.example || undefined,
680
1563
  attributes: block.attributes,
681
1564
  edit: function(props) {
682
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
+
683
1596
  const blockProps = useBlockProps();
684
-
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
+
685
1734
  if (block.customEditJsx) {
686
1735
  try {
687
- 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,
688
1768
  'return ' + block.customEditJsx
689
1769
  );
690
- 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
+ );
691
1787
  } catch (e) {
692
- console.error("[ForgeWP Editor] Custom edit render failed for block " + block.name + ":", e);
693
- 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
+ );
694
1796
  }
695
1797
  }
696
1798
 
697
- // Build inspector controls dynamically from attributes
698
- const controls = Object.keys(block.attributes).map(key => {
699
- return createElement(TextControl, {
700
- label: key.charAt(0).toUpperCase() + key.slice(1),
701
- value: attributes[key],
702
- onChange: (val) => setAttributes({ [key]: val })
703
- });
704
- });
705
-
706
1799
  return createElement('div', blockProps,
707
- createElement(InspectorControls, null,
708
- createElement(PanelBody, { title: 'Block Settings', initialOpen: true }, controls)
709
- ),
1800
+ inspector,
710
1801
  createElement(ServerSideRender, {
711
1802
  block: block.name,
712
1803
  attributes: attributes
@@ -714,11 +1805,63 @@ if (window.forgeWpBlocks) {
714
1805
  );
715
1806
  },
716
1807
  save: function() {
717
- 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;
718
1813
  }
719
1814
  });
720
1815
  });
721
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
+ })();
722
1865
  `;
723
1866
  writeFileSync(
724
1867
  path.join(outDir, 'assets', 'forgewp-editor.js'),
@@ -728,38 +1871,160 @@ if (window.forgeWpBlocks) {
728
1871
 
729
1872
  writeFileSync(path.join(outDir, 'style.css'), buildStyleCss(config), 'utf8');
730
1873
 
731
- let hydrationData = null;
732
- if (hasHydration) {
1874
+ if (!hydrationData && hasHydration) {
733
1875
  try {
734
1876
  hydrationData = JSON.parse(hydrationManifestJson);
735
1877
  } catch {}
736
1878
  }
737
1879
 
738
1880
  const queries = scanForQueries(themeRoot);
739
- console.log(`[ForgeWP Compiler] Scanned and compiled ${queries.length} REST endpoints: ${queries.map(q => q.queryId).join(', ') || '<none>'}`);
740
-
741
- let functionsPhpContent = buildFunctionsPhp(
742
- config,
743
- assets,
744
- compiledBlocks,
745
- themeRoot,
746
- pagesToAutoCreate,
747
- menus,
748
- hydrationData,
749
- Array.from(i18nKeys),
750
- schemas,
751
- queries,
752
- );
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
+ }
753
2010
 
754
2011
  if (projectHooks && typeof projectHooks.processFunctionsPhp === 'function') {
755
- functionsPhpContent = projectHooks.processFunctionsPhp(functionsPhpContent, config);
2012
+ functionsPhpContent = projectHooks.processFunctionsPhp(
2013
+ functionsPhpContent,
2014
+ config,
2015
+ );
756
2016
  }
757
2017
 
758
2018
  // Execute plugin functions.php transformation hooks
759
2019
  if (config.plugins && Array.isArray(config.plugins)) {
760
2020
  for (const plugin of config.plugins) {
761
2021
  if (typeof plugin.transformFunctionsPhp === 'function') {
762
- functionsPhpContent = plugin.transformFunctionsPhp(functionsPhpContent, config, themeRoot, { fs, path });
2022
+ functionsPhpContent = plugin.transformFunctionsPhp(
2023
+ functionsPhpContent,
2024
+ config,
2025
+ themeRoot,
2026
+ { fs, path },
2027
+ );
763
2028
  }
764
2029
  }
765
2030
  }
@@ -771,7 +2036,8 @@ if (window.forgeWpBlocks) {
771
2036
  .filter((file) => file.endsWith('.php'))
772
2037
  .sort();
773
2038
  if (phpFiles.length > 0) {
774
- 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 */';
775
2041
  for (const file of phpFiles) {
776
2042
  const filePath = path.join(serverDir, file);
777
2043
  let content = readFileSync(filePath, 'utf8');
@@ -792,14 +2058,21 @@ if (window.forgeWpBlocks) {
792
2058
  'utf8',
793
2059
  );
794
2060
 
795
- // Copy translations.json directly if it exists in the project cms/ folder
796
- const translationsSrc = path.join(themeRoot, 'cms', 'translations.json');
797
- if (existsSync(translationsSrc)) {
798
- 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
+ );
799
2069
  }
2070
+ // Generate priority preloads for <head> in header.php
2071
+ const preloadTags = generatePreloadTags(effectiveAssetGraph, { isPhp: true });
2072
+
800
2073
  writeFileSync(
801
2074
  path.join(outDir, 'header.php'),
802
- buildHeaderPhp(config),
2075
+ buildHeaderPhp(config, { preloadTags }),
803
2076
  'utf8',
804
2077
  );
805
2078
  writeFileSync(
@@ -810,9 +2083,26 @@ if (window.forgeWpBlocks) {
810
2083
  writeFileSync(path.join(outDir, 'index.php'), buildIndexPhp(), 'utf8');
811
2084
  writeFileSync(path.join(outDir, 'single.php'), buildSinglePhp(), 'utf8');
812
2085
  writeFileSync(path.join(outDir, '404.php'), build404Php(), 'utf8');
813
- 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
+ );
814
2094
  writeFileSync(path.join(outDir, 'archive.php'), buildArchivePhp(), 'utf8');
815
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
+ );
816
2106
 
817
2107
  // Dynamic Custom WP hierarchy templates compiler (single-*, taxonomy-*, archive-*, etc.)
818
2108
  if (existsSync(forgewpDir)) {
@@ -821,32 +2111,49 @@ if (window.forgeWpBlocks) {
821
2111
  const name = file.replace('.html', '');
822
2112
  const isHierarchyTemplate =
823
2113
  (name.startsWith('single-') ||
824
- name.startsWith('archive-') ||
825
- name.startsWith('taxonomy-') ||
826
- name === 'taxonomy') &&
2114
+ name.startsWith('archive-') ||
2115
+ name.startsWith('taxonomy-') ||
2116
+ name === 'taxonomy') &&
827
2117
  file.endsWith('.html') &&
828
2118
  !file.includes('-head');
829
-
2119
+
830
2120
  if (isHierarchyTemplate) {
831
2121
  const rawHtml = readFileSync(path.join(forgewpDir, file), 'utf8');
832
- let processedHtml = processMarkup(rawHtml, config.textDomain);
833
- if (processedHeader) {
834
- const replaced = processedHtml.replace(processedHeader, '');
835
- processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
836
- }
837
- if (processedFooter) {
838
- const replaced = processedHtml.replace(processedFooter, '');
839
- processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
840
- }
841
- 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
+ );
842
2143
 
843
- writeFileSync(path.join(staticDir, file), processedHtml, 'utf8');
2144
+ writeFileSync(
2145
+ path.join(staticDir, file),
2146
+ replaceAssetPlaceholders(processedHtml),
2147
+ 'utf8',
2148
+ );
844
2149
 
845
2150
  const headFile = file.replace('.html', '-head.html');
846
2151
  if (existsSync(path.join(forgewpDir, headFile))) {
847
2152
  writeFileSync(
848
2153
  path.join(staticDir, headFile),
849
- readFileSync(path.join(forgewpDir, headFile), 'utf8'),
2154
+ replaceAssetPlaceholders(
2155
+ readFileSync(path.join(forgewpDir, headFile), 'utf8'),
2156
+ ),
850
2157
  'utf8',
851
2158
  );
852
2159
  }
@@ -884,11 +2191,18 @@ ${phpLoop}
884
2191
  get_footer();
885
2192
  `;
886
2193
  writeFileSync(path.join(outDir, `${name}.php`), phpContent, 'utf8');
887
- console.warn(`[ForgeWP Compiler] Wrote dynamic WP template ${name}.php`);
2194
+ console.warn(
2195
+ `[ForgeWP Compiler] Wrote dynamic WP template ${name}.php`,
2196
+ );
888
2197
  }
889
2198
  }
890
2199
  }
891
2200
 
2201
+ const authManifest = {
2202
+ protectedPages: [],
2203
+ authGates: [],
2204
+ };
2205
+
892
2206
  // Dynamic Custom Page Templates Compiler
893
2207
  if (existsSync(forgewpDir)) {
894
2208
  const templateFiles = readdirSync(forgewpDir);
@@ -901,28 +2215,243 @@ get_footer();
901
2215
  const slug = file.replace('.html', '');
902
2216
  const rawHtml = readFileSync(path.join(forgewpDir, file), 'utf8');
903
2217
 
904
- let processedHtml = processMarkup(rawHtml, config.textDomain);
905
- if (processedHeader) {
906
- const replaced = processedHtml.replace(processedHeader, '');
907
- processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
2218
+ let isProtected = false;
2219
+ let allowedCapability = null;
2220
+ let redirectUrl = null;
2221
+
2222
+ if (rawHtml.includes('<forgewp-require-auth')) {
2223
+ isProtected = true;
2224
+ const match = rawHtml.match(/<forgewp-require-auth\s+([^>]*)\/?>/i);
2225
+ if (match) {
2226
+ const attrsStr = match[1];
2227
+ const getAttr = (name) => {
2228
+ const regex = new RegExp(
2229
+ `(?:${name}|${name.toLowerCase()})=(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,
2230
+ 'i',
2231
+ );
2232
+ const m = attrsStr.match(regex);
2233
+ return m ? m[1] || m[2] || m[3] || '' : '';
2234
+ };
2235
+ allowedCapability = getAttr('allowed') || null;
2236
+ redirectUrl = getAttr('redirect') || null;
2237
+ }
2238
+ }
2239
+
2240
+ if (isProtected) {
2241
+ authManifest.protectedPages.push({
2242
+ page: slug.replace('template-', ''),
2243
+ allowed: allowedCapability,
2244
+ redirect: redirectUrl,
2245
+ });
908
2246
  }
909
- if (processedFooter) {
910
- const replaced = processedHtml.replace(processedFooter, '');
911
- processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
2247
+
2248
+ if (rawHtml.includes('forgewp-auth-gate-start')) {
2249
+ authManifest.authGates.push({
2250
+ page: slug.replace('template-', ''),
2251
+ type: 'logged_in',
2252
+ });
2253
+ }
2254
+
2255
+ if (rawHtml.includes('forgewp-capability-gate-start')) {
2256
+ const match = rawHtml.match(
2257
+ /forgewp-capability-gate-start\s+allowed="([^"]*)"/,
2258
+ );
2259
+ authManifest.authGates.push({
2260
+ page: slug.replace('template-', ''),
2261
+ type: 'capability',
2262
+ allowed: match ? match[1] : null,
2263
+ });
2264
+ }
2265
+
2266
+ let redirectPhp = '';
2267
+ let cleanedRawHtml = rawHtml;
2268
+ if (rawHtml.includes('<forgewp-require-auth')) {
2269
+ const match = rawHtml.match(/<forgewp-require-auth\s+([^>]*)\/?>/i);
2270
+ if (match) {
2271
+ const attrsStr = match[1];
2272
+ const getAttr = (name) => {
2273
+ const regex = new RegExp(
2274
+ `(?:${name}|${name.toLowerCase()})=(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,
2275
+ 'i',
2276
+ );
2277
+ const m = attrsStr.match(regex);
2278
+ return m ? m[1] || m[2] || m[3] || '' : '';
2279
+ };
2280
+
2281
+ const allowed = getAttr('allowed');
2282
+ const redirect = getAttr('redirect');
2283
+
2284
+ let redirectUrlExpr = 'wp_login_url()';
2285
+ let redirectSetup = '';
2286
+ if (redirect) {
2287
+ if (redirect.startsWith('__FORGEWP_PAGELINK_')) {
2288
+ const match = redirect.match(
2289
+ /__FORGEWP_PAGELINK_([a-zA-Z0-9_-]+)_DEFAULT_(.*?)__/,
2290
+ );
2291
+ if (match) {
2292
+ const name = match[1];
2293
+ const decoded = decodeURIComponent(match[2]);
2294
+ redirectSetup = ` $redirect_url = home_url('${decoded.replace(/'/g, "\\'")}');
2295
+ $__fwp_id = forgewp_resolve_route_page_id('${name}');
2296
+ if ($__fwp_id) {
2297
+ $redirect_url = get_permalink($__fwp_id);
2298
+ }`;
2299
+ redirectUrlExpr = '$redirect_url';
2300
+ } else {
2301
+ const matchPlain = redirect.match(
2302
+ /__FORGEWP_PAGELINK_([a-zA-Z0-9_-]+)__/,
2303
+ );
2304
+ if (matchPlain) {
2305
+ const name = matchPlain[1];
2306
+ redirectSetup = ` $redirect_url = home_url('/');
2307
+ $__fwp_id = forgewp_resolve_route_page_id('${name}');
2308
+ if ($__fwp_id) {
2309
+ $redirect_url = get_permalink($__fwp_id);
2310
+ }`;
2311
+ redirectUrlExpr = '$redirect_url';
2312
+ } else {
2313
+ redirectUrlExpr = `home_url('${redirect}')`;
2314
+ }
2315
+ }
2316
+ } else if (redirect.startsWith('template:')) {
2317
+ const name = redirect.replace('template:', '');
2318
+ redirectSetup = ` $redirect_url = home_url('/');
2319
+ $__fwp_id = forgewp_resolve_route_page_id('${name}');
2320
+ if ($__fwp_id) {
2321
+ $redirect_url = get_permalink($__fwp_id);
2322
+ }`;
2323
+ redirectUrlExpr = '$redirect_url';
2324
+ } else {
2325
+ redirectUrlExpr = `home_url('${redirect}')`;
2326
+ }
2327
+ }
2328
+
2329
+ redirectPhp = `
2330
+ if ( ! is_user_logged_in() ) {
2331
+ ${redirectSetup ? redirectSetup + '\n' : ''} wp_safe_redirect( ${redirectUrlExpr} );
2332
+ exit;
2333
+ } else {
2334
+ $email_verification_enabled = get_option( 'forgewp_auth_email_verification_enabled' ) === '1';
2335
+ $verified_meta = get_user_meta( get_current_user_id(), 'forgewp_email_verified', true );
2336
+ $email_verified = ( $verified_meta === '' ) || ( $verified_meta === '1' ) || ( $verified_meta === true );
2337
+ if ( $email_verification_enabled && ! $email_verified ) {
2338
+ $verify_url = home_url( '/verify-email' );
2339
+ $__fwp_id = forgewp_resolve_route_page_id('verify-email-page');
2340
+ if ($__fwp_id) {
2341
+ $verify_url = get_permalink($__fwp_id);
2342
+ }
2343
+ wp_safe_redirect( $verify_url );
2344
+ exit;
2345
+ }
2346
+ }`;
2347
+
2348
+ if (allowed) {
2349
+ redirectPhp += `
2350
+ if ( ! current_user_can( '${allowed}' ) ) {
2351
+ wp_safe_redirect( home_url( '/' ) );
2352
+ exit;
2353
+ }`;
2354
+ }
2355
+ }
2356
+ cleanedRawHtml = rawHtml.replace(
2357
+ /<forgewp-require-auth\s*([^>]*)\/?>/gi,
2358
+ '',
2359
+ );
2360
+ cleanedRawHtml = cleanedRawHtml.replace(
2361
+ /<\/forgewp-require-auth>/gi,
2362
+ '',
2363
+ );
2364
+ }
2365
+
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
+ );
912
2404
  }
913
- processedHtml = processedHtml.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
914
2405
 
915
- if (projectHooks && typeof projectHooks.processTemplateMarkup === 'function') {
916
- 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
+ );
917
2440
  }
918
2441
 
919
- writeFileSync(path.join(staticDir, file), processedHtml, 'utf8');
2442
+ writeFileSync(
2443
+ path.join(staticDir, file),
2444
+ replaceAssetPlaceholders(processedHtml),
2445
+ 'utf8',
2446
+ );
920
2447
 
921
2448
  const headFile = file.replace('.html', '-head.html');
922
2449
  if (existsSync(path.join(forgewpDir, headFile))) {
923
2450
  writeFileSync(
924
2451
  path.join(staticDir, headFile),
925
- readFileSync(path.join(forgewpDir, headFile), 'utf8'),
2452
+ replaceAssetPlaceholders(
2453
+ readFileSync(path.join(forgewpDir, headFile), 'utf8'),
2454
+ ),
926
2455
  'utf8',
927
2456
  );
928
2457
  }
@@ -933,21 +2462,59 @@ get_footer();
933
2462
  .split('-')
934
2463
  .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
935
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
+
936
2506
  const phpContent = `<?php
937
2507
  /**
938
2508
  * Template Name: ${templateName}
939
2509
  *
940
2510
  * @package ${config.textDomain}
941
2511
  */
2512
+ ${redirectPhp}
2513
+ ${headerCall}
942
2514
 
943
- get_header();
944
-
945
- $markup_file = get_template_directory() . '/forgewp-static/${file}';
946
- if (file_exists($markup_file)) {
947
- include $markup_file;
948
- }
2515
+ ${buildGeneratedPageTemplateContentPhp(`forgewp-static/${file}`)}
949
2516
 
950
- get_footer();
2517
+ ${footerCall}
951
2518
  `;
952
2519
  writeFileSync(
953
2520
  path.join(outDir, `page-${slug.replace('template-', '')}.php`),
@@ -994,6 +2561,29 @@ get_footer();
994
2561
  ...themeJson.settings.color,
995
2562
  ...config.settings.color,
996
2563
  };
2564
+
2565
+ // Smartly extract background and text colors from palette to style the WP editor canvas
2566
+ if (
2567
+ config.settings.color.palette &&
2568
+ Array.isArray(config.settings.color.palette)
2569
+ ) {
2570
+ if (!themeJson.styles) themeJson.styles = {};
2571
+ if (!themeJson.styles.color) themeJson.styles.color = {};
2572
+
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
+ );
2579
+
2580
+ if (bgPreset && !themeJson.styles.color.background) {
2581
+ themeJson.styles.color.background = bgPreset.color;
2582
+ }
2583
+ if (textPreset && !themeJson.styles.color.text) {
2584
+ themeJson.styles.color.text = textPreset.color;
2585
+ }
2586
+ }
997
2587
  }
998
2588
 
999
2589
  // Typography (fontSizes, fontFamilies)
@@ -1011,6 +2601,12 @@ get_footer();
1011
2601
  'utf8',
1012
2602
  );
1013
2603
 
2604
+ writeFileSync(
2605
+ path.join(outDir, 'auth-manifest.json'),
2606
+ JSON.stringify(authManifest, null, 2),
2607
+ 'utf8',
2608
+ );
2609
+
1014
2610
  const screenshot = path.join(themeRoot, 'cms', 'screenshot.png');
1015
2611
  if (existsSync(screenshot)) {
1016
2612
  copyFileSync(screenshot, path.join(outDir, 'screenshot.png'));
@@ -1032,10 +2628,10 @@ function extractUseWpQueryArgs(fileContent) {
1032
2628
  let endIdx = startIdx;
1033
2629
  let inString = false;
1034
2630
  let stringChar = null;
1035
-
2631
+
1036
2632
  for (let i = startIdx; i < fileContent.length; i++) {
1037
2633
  const char = fileContent[i];
1038
-
2634
+
1039
2635
  if (inString) {
1040
2636
  if (char === stringChar && fileContent[i - 1] !== '\\') {
1041
2637
  inString = false;
@@ -1047,7 +2643,7 @@ function extractUseWpQueryArgs(fileContent) {
1047
2643
  stringChar = char;
1048
2644
  continue;
1049
2645
  }
1050
-
2646
+
1051
2647
  if (char === '(') parenCount++;
1052
2648
  if (char === ')') {
1053
2649
  parenCount--;
@@ -1057,7 +2653,7 @@ function extractUseWpQueryArgs(fileContent) {
1057
2653
  }
1058
2654
  }
1059
2655
  }
1060
-
2656
+
1061
2657
  if (endIdx > startIdx) {
1062
2658
  const argText = fileContent.slice(startIdx, endIdx).trim();
1063
2659
  queries.push(argText);
@@ -1072,17 +2668,29 @@ function safeEvalObject(objText) {
1072
2668
  return null;
1073
2669
  }
1074
2670
  try {
1075
- const sandbox = new Proxy({}, {
1076
- has() { return true; },
1077
- get(target, prop) {
1078
- if (prop === 'Symbol(Symbol.toPrimitive)') return undefined;
1079
- return `__DYNAMIC_${String(prop)}__`;
1080
- }
1081
- });
1082
- 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
+ );
1083
2687
  return fn(sandbox);
1084
2688
  } catch (e) {
1085
- 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
+ );
1086
2694
  return null;
1087
2695
  }
1088
2696
  }
@@ -1114,7 +2722,9 @@ function scanForQueries(themeRoot) {
1114
2722
  if (!parsed.queryId) {
1115
2723
  const baseName = path.basename(file, path.extname(file));
1116
2724
  const postTypePart = String(parsed.postType).toLowerCase();
1117
- const cleanBase = baseName.toLowerCase().replace(/[^a-z0-9]+/g, '-');
2725
+ const cleanBase = baseName
2726
+ .toLowerCase()
2727
+ .replace(/[^a-z0-9]+/g, '-');
1118
2728
  parsed.queryId = cleanBase + '-' + postTypePart;
1119
2729
  }
1120
2730
  queries.push(parsed);
@@ -1130,7 +2740,10 @@ function scanForQueries(themeRoot) {
1130
2740
  const uniqueQueries = [];
1131
2741
  const seenIds = new Set();
1132
2742
  for (const q of queries) {
1133
- 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, '');
1134
2747
  if (!seenIds.has(cleanId)) {
1135
2748
  seenIds.add(cleanId);
1136
2749
  uniqueQueries.push(q);
@@ -1138,3 +2751,163 @@ function scanForQueries(themeRoot) {
1138
2751
  }
1139
2752
  return uniqueQueries;
1140
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
+ }