@forgewp/compiler 0.4.3 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +59 -0
  2. package/bin/add.js +20 -14
  3. package/bin/cli.js +145 -70
  4. package/bin/doctor.js +21 -12
  5. package/bin/export.js +69 -20
  6. package/bin/fresh.js +5 -0
  7. package/bin/i18n-extract.js +3 -10
  8. package/bin/i18n-translate.js +15 -24
  9. package/bin/make-block.js +13 -0
  10. package/bin/make-editable.js +166 -0
  11. package/bin/make-form.js +131 -0
  12. package/bin/make-loop.js +40 -43
  13. package/bin/make-mail.js +27 -0
  14. package/bin/make-post-type.js +57 -29
  15. package/bin/make-sandbox.js +62 -11
  16. package/bin/make-section.js +221 -0
  17. package/bin/make-shell.js +375 -0
  18. package/bin/repair.js +14 -26
  19. package/bin/seed.js +119 -0
  20. package/bin/sync-routes.js +107 -85
  21. package/lib/adapters/html-adapter.js +5 -0
  22. package/lib/adapters/stub-adapter.js +4 -0
  23. package/lib/add-component.js +153 -92
  24. package/lib/asset-loader.js +313 -3
  25. package/lib/assets/asset-graph.js +432 -0
  26. package/lib/assets/asset-pipeline.js +125 -0
  27. package/lib/assets/diagnostics-report.js +345 -0
  28. package/lib/assets/external-fetcher.js +173 -0
  29. package/lib/assets/font-orchestrator.js +348 -0
  30. package/lib/assets/font-usage-scanner.js +242 -0
  31. package/lib/assets/image-optimizer.js +229 -0
  32. package/lib/assets/index.js +51 -0
  33. package/lib/assets/preload-generator.js +70 -0
  34. package/lib/assets/public-url.js +153 -0
  35. package/lib/block-authoring-help.js +11 -0
  36. package/lib/blocks/ast-parser.js +67 -0
  37. package/lib/blocks/discover-blocks.js +146 -0
  38. package/lib/blocks/editor-scope.js +733 -0
  39. package/lib/blocks/editor-transpiler.js +1229 -0
  40. package/lib/blocks/index.js +2838 -0
  41. package/lib/blocks/php-transpiler.js +4928 -0
  42. package/lib/blocks/scanner.js +1487 -0
  43. package/lib/blocks/shared-utils.js +290 -0
  44. package/lib/blocks/source-sanitize.js +1449 -0
  45. package/lib/blueprints.js +31 -91
  46. package/lib/build-assets.js +38 -33
  47. package/lib/collect-page-template-routes.js +102 -0
  48. package/lib/collect-static-routes.js +175 -0
  49. package/lib/diagnostics.js +58 -33
  50. package/lib/export-theme.js +84 -5
  51. package/lib/extract-template-content.js +90 -0
  52. package/lib/forms-preview.js +42 -0
  53. package/lib/functions/cpt-routing.js +69 -0
  54. package/lib/functions/forms.js +2461 -0
  55. package/lib/functions/hydration-enqueuer.js +400 -0
  56. package/lib/functions/index.js +1623 -0
  57. package/lib/functions/load-menus.js +112 -0
  58. package/lib/functions/load-translations.js +148 -0
  59. package/lib/functions/rest-endpoints.js +2923 -0
  60. package/lib/functions/routing.js +765 -0
  61. package/lib/functions/seed-mock-data.js +392 -0
  62. package/lib/functions/seed-products.js +481 -0
  63. package/lib/functions/settings-page.js +273 -0
  64. package/lib/functions/theme-setup.js +494 -0
  65. package/lib/generate-theme.js +1916 -339
  66. package/lib/hydration/editable-schemas.js +332 -0
  67. package/lib/hydration/enter-hidden-initial.js +65 -0
  68. package/lib/hydration/form-schemas.js +227 -0
  69. package/lib/hydration/index.js +12 -0
  70. package/lib/hydration/is-interactive.js +951 -0
  71. package/lib/hydration/island-split.js +1231 -0
  72. package/lib/hydration/islands-scanner.js +599 -0
  73. package/lib/hydration/resolve-island-chunk.js +103 -0
  74. package/lib/hydration/resolve-island-component.js +52 -0
  75. package/lib/hydration/rollup-inputs.js +81 -0
  76. package/lib/hydration/root-class-extractor.js +220 -0
  77. package/lib/hydration/scan-app-providers.js +154 -0
  78. package/lib/hydration/static-lint.js +382 -0
  79. package/lib/hydration/transform.js +257 -0
  80. package/lib/hydration/uses-block-area.js +49 -0
  81. package/lib/hydration/utils.js +119 -0
  82. package/lib/i18n/translation-cache.js +141 -0
  83. package/lib/icon-registry.js +72 -0
  84. package/lib/index.d.ts +287 -8
  85. package/lib/index.js +2 -1
  86. package/lib/load-config.js +338 -242
  87. package/lib/mail-templates.js +37 -0
  88. package/lib/markup-processor.js +388 -102
  89. package/lib/node-runtime.js +7 -0
  90. package/lib/page-config-plugin.js +64 -20
  91. package/lib/php-builders.js +383 -44
  92. package/lib/react-adapter.js +983 -235
  93. package/lib/registration-metadata.js +11 -0
  94. package/lib/render-theme.mts +1410 -616
  95. package/lib/route-layout.js +76 -0
  96. package/lib/template-discovery.js +58 -0
  97. package/lib/theme-compatibility.js +32 -0
  98. package/lib/validate-export.js +2 -2
  99. package/lib/validate.js +27 -5
  100. package/lib/virtual-plugin.js +319 -0
  101. package/lib/walkthrough.md +26 -0
  102. package/package.json +16 -5
  103. package/templates/auth/cms/email-logs.json +9 -0
  104. package/templates/auth/cms/menus.json +11 -0
  105. package/templates/auth/cms/mock-data.json +123 -0
  106. package/templates/auth/cms/roles.json +7 -0
  107. package/templates/auth/cms/sessions.json +1 -0
  108. package/templates/auth/cms/site-settings.json +28 -0
  109. package/templates/auth/cms/translations.json +4 -0
  110. package/templates/auth/cms/users.json +46 -0
  111. package/templates/auth/components/forgot-password-form-wrapper.tsx +10 -2
  112. package/templates/auth/components/login-form-wrapper.tsx +118 -21
  113. package/templates/auth/components/reset-password-form-wrapper.tsx +10 -2
  114. package/templates/auth/components/signup-form-wrapper.tsx +2 -2
  115. package/templates/auth/components/verify-email-view-wrapper.tsx +5 -5
  116. package/templates/auth/pages/DashboardPage.tsx +1 -4
  117. package/templates/auth/pages/ForgotPasswordPage.tsx +1 -4
  118. package/templates/auth/pages/LoginPage.tsx +1 -4
  119. package/templates/auth/pages/ResetPasswordPage.tsx +1 -4
  120. package/templates/auth/pages/SignUpPage.tsx +1 -4
  121. package/templates/auth/pages/VerifyEmailPage.tsx +1 -4
  122. package/templates/auth/ui/button.tsx +57 -0
  123. package/templates/auth/ui/card.tsx +76 -0
  124. package/templates/auth/ui/field.tsx +242 -0
  125. package/templates/auth/ui/input.tsx +22 -0
  126. package/templates/auth/ui/label.tsx +24 -0
  127. package/templates/auth/ui/separator.tsx +31 -0
  128. package/templates/menus.json +12 -10
  129. package/templates/users.json +8 -4
  130. package/templates/wordpress.tsx +690 -245
  131. package/lib/block-compiler.js +0 -552
  132. package/lib/functions-builder.js +0 -2970
  133. package/lib/hydration-scanner.js +0 -833
@@ -1,14 +1,23 @@
1
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
1
+ import {
2
+ existsSync,
3
+ readFileSync,
4
+ writeFileSync,
5
+ mkdirSync,
6
+ readdirSync,
7
+ } from 'node:fs';
2
8
  import path from 'node:path';
3
9
  import { fileURLToPath } from 'node:url';
4
10
  import { spawnSync } from 'node:child_process';
5
11
  import { createRequire } from 'node:module';
6
12
  import pc from 'picocolors';
13
+ import { loadMockData } from './functions/seed-mock-data.js';
7
14
  import {
8
15
  scanForHydrationIslands,
9
16
  findComponentPath,
10
17
  getHydrationRollupInputs,
11
- } from './hydration-scanner.js';
18
+ resolveIslandChunk,
19
+ scanAppProviders,
20
+ } from './hydration/index.js';
12
21
 
13
22
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
23
  const require = createRequire(import.meta.url);
@@ -123,6 +132,13 @@ export function generateHydrationRuntime(
123
132
  );
124
133
  }
125
134
 
135
+ const layoutProviders = scanAppProviders(themeRoot);
136
+ for (const provider of layoutProviders) {
137
+ if (!hydrationIslands.includes(provider.kebab)) {
138
+ hydrationIslands = hydrationIslands.concat(provider.kebab);
139
+ }
140
+ }
141
+
126
142
  const mapping = {};
127
143
  let mainJsFile = '';
128
144
  const entryChunk =
@@ -133,28 +149,7 @@ export function generateHydrationRuntime(
133
149
  }
134
150
 
135
151
  for (const island of hydrationIslands) {
136
- const pascalName = island
137
- .split('-')
138
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
139
- .join('');
140
-
141
- let resolvedChunk = null;
142
- for (const [key, value] of Object.entries(viteManifest)) {
143
- const fileBasename = path.basename(value.file || '');
144
- const cleanName = fileBasename.replace(/-[A-Za-z0-9_-]+\.js$/, '');
145
- if (
146
- key.endsWith(`/${pascalName}.tsx`) ||
147
- key.endsWith(`/${pascalName}.ts`) ||
148
- key.endsWith(`/${island}.tsx`) ||
149
- key.endsWith(`/${island}.ts`) ||
150
- cleanName === island ||
151
- cleanName === pascalName.toLowerCase()
152
- ) {
153
- resolvedChunk = value.file;
154
- break;
155
- }
156
- }
157
-
152
+ const resolvedChunk = resolveIslandChunk(viteManifest, island);
158
153
  if (resolvedChunk) {
159
154
  mapping[island] = resolvedChunk;
160
155
  }
@@ -163,8 +158,8 @@ export function generateHydrationRuntime(
163
158
  if (!mainJsFile) {
164
159
  throw new Error(
165
160
  `\n[ForgeWP Compiler Error] Hydration generation failed: could not resolve the React runtime entry chunk.\n` +
166
- `This usually happens if Vite failed to compile the entry file (e.g. src/main.tsx) or did not emit a manifest.json.\n` +
167
- `Ensure that you have run 'pnpm run build' inside your theme directory and that 'dist/.vite/manifest.json' exists.\n`
161
+ `This usually happens if Vite failed to compile the entry file (e.g. src/main.tsx) or did not emit a manifest.json.\n` +
162
+ `Ensure that you have run 'pnpm run build' inside your theme directory and that 'dist/.vite/manifest.json' exists.\n`,
168
163
  );
169
164
  }
170
165
 
@@ -172,28 +167,141 @@ export function generateHydrationRuntime(
172
167
  (island) => !(island in mapping),
173
168
  );
174
169
  if (missingIslands.length > 0) {
175
- const formattedComponents = missingIslands.map(island => {
176
- return island.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('') + '.tsx';
177
- }).join(', ');
170
+ const formattedComponents = missingIslands
171
+ .map((island) => {
172
+ return (
173
+ island
174
+ .split('-')
175
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
176
+ .join('') + '.tsx'
177
+ );
178
+ })
179
+ .join(', ');
178
180
  throw new Error(
179
181
  `\n[ForgeWP Compiler Error] Hydration generation failed: missing compiled chunk for island(s): ${missingIslands.join(', ')}.\n` +
180
- `Vite was unable to locate these hydration islands in its compilation manifest.\n` +
181
- `Verification Steps:\n` +
182
- ` 1. Ensure the React component(s) exist under 'src/components/' (e.g., ${formattedComponents}).\n` +
183
- ` 2. Ensure they are correctly exported and referenced via <Hydrate island="..."> in your page layout/components.\n` +
184
- ` 3. Check for syntax or import errors in these files that might have caused Vite compilation to skip or fail.\n`
182
+ `Vite was unable to locate these hydration islands in its compilation manifest.\n` +
183
+ `Verification Steps:\n` +
184
+ ` 1. Ensure the React component(s) exist under 'src/components/' (e.g., ${formattedComponents}).\n` +
185
+ ` 2. Ensure they are correctly exported and referenced via <Hydrate island="..."> in your page layout/components.\n` +
186
+ ` 3. Check for syntax or import errors in these files that might have caused Vite compilation to skip or fail.\n`,
185
187
  );
186
188
  }
187
189
 
190
+ const providerIdsJson = JSON.stringify(layoutProviders.map((p) => p.kebab));
188
191
  const hydratorScript = `(function () {
189
192
  const config = window.forgeWpHydration || { themeUri: "", manifest: {} };
190
- const islands = document.querySelectorAll("[data-forgewp-hydrate]");
193
+ if (!config.providers) config.providers = ${providerIdsJson};
194
+ window.ForgeWP = window.ForgeWP || {};
195
+ window.ForgeWP.hydratedIslands = window.ForgeWP.hydratedIslands || new Set();
196
+ window.ForgeWP.onHydrated = function(callback) {
197
+ if (typeof callback !== "function") return;
198
+ window.addEventListener("forgewp:hydrated", function(e) {
199
+ callback(e.detail);
200
+ });
201
+ };
202
+
203
+ // Cross-island DOM resolution bridge: guarantees that DOM queries captured
204
+ // prior to asynchronous child island hydration resolve seamlessly to live elements.
205
+ if (typeof Element !== "undefined" && !Element.prototype.__forgewpBound) {
206
+ Element.prototype.__forgewpBound = true;
207
+ const origGetBoundingClientRect = Element.prototype.getBoundingClientRect;
208
+ Element.prototype.getBoundingClientRect = function () {
209
+ if (!this.isConnected) {
210
+ if (this.id) {
211
+ const live = document.getElementById(this.id);
212
+ if (live && live !== this && live.isConnected) return origGetBoundingClientRect.call(live);
213
+ }
214
+ if (this.className && typeof this.className === "string") {
215
+ const classes = this.className.trim().split(/\\s+/).filter(Boolean);
216
+ for (let i = 0; i < classes.length; i++) {
217
+ const cls = classes[i];
218
+ if (!cls.startsWith("bg-") && !cls.startsWith("text-") && !cls.startsWith("p-") && !cls.startsWith("m-") && !cls.startsWith("flex") && !cls.startsWith("grid") && !cls.startsWith("w-") && !cls.startsWith("h-") && !cls.startsWith("border")) {
219
+ try {
220
+ const live = document.querySelector("." + (CSS.escape ? CSS.escape(cls) : cls));
221
+ if (live && live !== this && live.isConnected) return origGetBoundingClientRect.call(live);
222
+ } catch (e) {}
223
+ }
224
+ }
225
+ }
226
+ if (this.tagName) {
227
+ try {
228
+ const live = document.querySelector(this.tagName.toLowerCase());
229
+ if (live && live !== this && live.isConnected) return origGetBoundingClientRect.call(live);
230
+ } catch (e) {}
231
+ }
232
+ }
233
+ return origGetBoundingClientRect.call(this);
234
+ };
235
+
236
+ if (typeof IntersectionObserver !== "undefined") {
237
+ const origObserve = IntersectionObserver.prototype.observe;
238
+ IntersectionObserver.prototype.observe = function (target) {
239
+ if (!target) return;
240
+ origObserve.call(this, target);
241
+ const observer = this;
242
+ window.ForgeWP.onHydrated(function () {
243
+ if (!target.isConnected) {
244
+ let live = null;
245
+ if (target.id) live = document.getElementById(target.id);
246
+ if (!live && target.className && typeof target.className === "string") {
247
+ const classes = target.className.trim().split(/\\s+/).filter(Boolean);
248
+ for (let i = 0; i < classes.length; i++) {
249
+ const cls = classes[i];
250
+ if (!cls.startsWith("bg-") && !cls.startsWith("text-") && !cls.startsWith("p-") && !cls.startsWith("m-") && !cls.startsWith("flex") && !cls.startsWith("grid") && !cls.startsWith("w-") && !cls.startsWith("h-") && !cls.startsWith("border")) {
251
+ try {
252
+ live = document.querySelector("." + (CSS.escape ? CSS.escape(cls) : cls));
253
+ if (live && live.isConnected) break;
254
+ } catch (e) {}
255
+ }
256
+ }
257
+ }
258
+ if (live && live.isConnected) {
259
+ try { observer.unobserve(target); } catch (e) {}
260
+ try { origObserve.call(observer, live); } catch (e) {}
261
+ }
262
+ }
263
+ });
264
+ };
265
+ }
266
+ }
267
+
268
+ const allIslands = Array.from(document.querySelectorAll("[data-forgewp-hydrate]"));
269
+ const islands = allIslands.filter((el) => {
270
+ let parent = el.parentElement;
271
+ while (parent) {
272
+ if (parent.hasAttribute && parent.hasAttribute("data-forgewp-hydrate")) {
273
+ return false;
274
+ }
275
+ parent = parent.parentElement;
276
+ }
277
+ return true;
278
+ });
279
+
280
+ function firstObservableBox(el) {
281
+ if (!el || el.nodeType !== 1) return null;
282
+ try {
283
+ const display = window.getComputedStyle(el).display;
284
+ if (display !== "contents") return el;
285
+ } catch (e) {
286
+ return el;
287
+ }
288
+ for (let i = 0; i < el.children.length; i++) {
289
+ const found = firstObservableBox(el.children[i]);
290
+ if (found) return found;
291
+ }
292
+ return null;
293
+ }
191
294
 
192
295
  const observer = new IntersectionObserver((entries) => {
193
296
  entries.forEach((entry) => {
194
297
  if (entry.isIntersecting) {
195
- const hydrate = entry.target.__forgewpHydrate;
196
- if (typeof hydrate === "function") hydrate();
298
+ let node = entry.target;
299
+ while (node && typeof node.__forgewpHydrate !== "function") {
300
+ node = node.parentElement;
301
+ }
302
+ if (node && typeof node.__forgewpHydrate === "function") {
303
+ node.__forgewpHydrate();
304
+ }
197
305
  observer.unobserve(entry.target);
198
306
  }
199
307
  });
@@ -210,20 +318,6 @@ export function generateHydrationRuntime(
210
318
  });
211
319
  }, { rootMargin: "600px" });
212
320
 
213
- // Helper: checks if an element's bounding box overlaps the extended viewport (with rootMargin).
214
- // Used as an immediate fallback for IntersectionObserver's async nature.
215
- function isNearViewport(el, margin) {
216
- var rect = el.getBoundingClientRect();
217
- var vw = window.innerWidth || document.documentElement.clientWidth;
218
- var vh = window.innerHeight || document.documentElement.clientHeight;
219
- return (
220
- rect.bottom >= -margin &&
221
- rect.right >= -margin &&
222
- rect.top <= vh + margin &&
223
- rect.left <= vw + margin
224
- );
225
- }
226
-
227
321
  const StrategyRegistry = {
228
322
  load: (el, hydrate) => {
229
323
  if (document.readyState === "complete") {
@@ -233,14 +327,20 @@ export function generateHydrationRuntime(
233
327
  }
234
328
  },
235
329
  visible: (el, hydrate) => {
236
- // Immediate check: if already in/near viewport, hydrate right away.
237
- // IO fires asynchronously so this prevents missed hydrations on page load.
238
- if (isNearViewport(el, 200)) {
330
+ el.__forgewpHydrate = hydrate;
331
+ const target = firstObservableBox(el);
332
+ if (!target || (target === el && window.getComputedStyle(el).display === "contents")) {
239
333
  hydrate();
240
334
  return;
241
335
  }
242
- el.__forgewpHydrate = hydrate;
243
- observer.observe(el);
336
+ const rect = target.getBoundingClientRect();
337
+ const vw = window.innerWidth || document.documentElement.clientWidth;
338
+ const vh = window.innerHeight || document.documentElement.clientHeight;
339
+ if (rect.bottom >= -200 && rect.right >= -200 && rect.top <= vh + 200 && rect.left <= vw + 200) {
340
+ hydrate();
341
+ return;
342
+ }
343
+ observer.observe(target);
244
344
  },
245
345
  interaction: (el, hydrate) => {
246
346
  const run = () => {
@@ -335,6 +435,22 @@ export function generateHydrationRuntime(
335
435
  }
336
436
  });
337
437
 
438
+ // Native scroll-reveal observer for static layout animations (preserves 100% CSS grid/flex layout)
439
+ if (typeof IntersectionObserver !== "undefined") {
440
+ const revealObserver = new IntersectionObserver((entries) => {
441
+ entries.forEach((entry) => {
442
+ if (entry.isIntersecting) {
443
+ entry.target.classList.add("forgewp-in-view");
444
+ revealObserver.unobserve(entry.target);
445
+ }
446
+ });
447
+ }, { threshold: 0.12 });
448
+
449
+ document.querySelectorAll("[data-forgewp-reveal]").forEach((el) => {
450
+ revealObserver.observe(el);
451
+ });
452
+ }
453
+
338
454
  function preloadElement(el) {
339
455
  const islandName = el.getAttribute("data-forgewp-hydrate");
340
456
  const chunkPath = config.manifest?.[islandName];
@@ -355,6 +471,8 @@ export function generateHydrationRuntime(
355
471
  console.error("[ForgeWP Hydrator] Missing data-forgewp-hydrate attribute on hydration boundary.");
356
472
  return;
357
473
  }
474
+ if (el.__forgewpHydrated) return;
475
+ el.__forgewpHydrated = true;
358
476
 
359
477
  const rawProps = el.getAttribute("data-forgewp-props") || "{}";
360
478
  let props = {};
@@ -378,17 +496,11 @@ export function generateHydrationRuntime(
378
496
 
379
497
  import(scriptUrl)
380
498
  .then((module) => {
381
- let Component = module.default;
382
- if (!Component) {
383
- Component = Object.values(module).find((val) => typeof val === "function");
384
- if (!Component) {
385
- Component = Object.values(module)[0];
386
- }
387
- }
388
- if (typeof Component !== "function") {
499
+ const Component = resolveExport(module, islandName);
500
+ if (!isReactComponentType(Component)) {
389
501
  const exportsList = Object.keys(module).join(", ");
390
502
  console.error(
391
- "[ForgeWP Hydrator] Chunk for " + islandName + " does not export a valid React component. " +
503
+ "[ForgeWP Hydrator] Chunk for " + islandName + " does not export a valid React component type. " +
392
504
  "Available exports: " + exportsList
393
505
  );
394
506
  return;
@@ -403,8 +515,41 @@ export function generateHydrationRuntime(
403
515
  const React = window.React;
404
516
 
405
517
  if (ReactDOM && React) {
406
- const root = ReactDOM.createRoot(el);
407
- root.render(React.createElement(Component, props));
518
+ const backup = el.innerHTML;
519
+ const needsProviders = el.getAttribute("data-forgewp-needs-providers") === "true";
520
+ const providerReady = needsProviders ? loadProviderComponents() : Promise.resolve([]);
521
+ providerReady.then(function (providerComponents) {
522
+ const nextProps = Object.assign({}, props);
523
+ if (el.getAttribute("data-forgewp-slot-children") === "true") {
524
+ const ssrHtml = el.innerHTML;
525
+ if (ssrHtml && String(ssrHtml).trim()) {
526
+ nextProps.children = React.createElement("span", {
527
+ style: { display: "contents" },
528
+ dangerouslySetInnerHTML: { __html: ssrHtml },
529
+ });
530
+ }
531
+ }
532
+ let tree = React.createElement(Component, nextProps);
533
+ for (let i = providerComponents.length - 1; i >= 0; i--) {
534
+ tree = React.createElement(providerComponents[i], null, tree);
535
+ }
536
+ try {
537
+ const root = ReactDOM.createRoot(el);
538
+ root.render(tree);
539
+ if (window.ForgeWP && window.ForgeWP.hydratedIslands) {
540
+ window.ForgeWP.hydratedIslands.add(islandName);
541
+ }
542
+ const eventDetail = { island: islandName, element: el };
543
+ window.dispatchEvent(new CustomEvent("forgewp:hydrated", { detail: eventDetail }));
544
+ window.dispatchEvent(new CustomEvent("forgewp:island-ready", { detail: eventDetail }));
545
+ } catch (err) {
546
+ el.innerHTML = backup;
547
+ console.error("[ForgeWP Hydrator] Render failed for " + islandName + ", restored SSR HTML:", err);
548
+ }
549
+ }).catch(function (err) {
550
+ el.innerHTML = backup;
551
+ console.error("[ForgeWP Hydrator] Provider wrap failed for " + islandName + ":", err);
552
+ });
408
553
  } else {
409
554
  console.error("[ForgeWP Hydration Error] React or ReactDOM not found on window. Ensure main.tsx exposes window.React and window.ReactDOM.");
410
555
  }
@@ -413,6 +558,96 @@ export function generateHydrationRuntime(
413
558
  console.error("[ForgeWP Hydrator] Failed to load chunk for " + islandName + ":", err);
414
559
  });
415
560
  }
561
+
562
+ function isReactComponentType(value) {
563
+ if (typeof value === "function" || typeof value === "string") return true;
564
+ if (!value || typeof value !== "object") return false;
565
+ const type = value.$$typeof;
566
+ return type === Symbol.for("react.forward_ref") ||
567
+ type === Symbol.for("react.memo") ||
568
+ type === Symbol.for("react.lazy") ||
569
+ type === Symbol.for("react.provider") ||
570
+ type === Symbol.for("react.context");
571
+ }
572
+
573
+ function resolveExport(module, islandName) {
574
+ if (!module || typeof module !== "object") return undefined;
575
+ const pascalName = islandName
576
+ .split("-")
577
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
578
+ .join("");
579
+ const camelName = pascalName.charAt(0).toLowerCase() + pascalName.slice(1);
580
+
581
+ if (isReactComponentType(module[pascalName])) return module[pascalName];
582
+ if (isReactComponentType(module[camelName])) return module[camelName];
583
+ if (isReactComponentType(module.default)) return module.default;
584
+
585
+ const keys = Object.keys(module);
586
+ for (let i = 0; i < keys.length; i++) {
587
+ const val = module[keys[i]];
588
+ if (isReactComponentType(val)) {
589
+ const componentName = val.displayName || val.name || (val.render && val.render.name);
590
+ if (componentName === pascalName || componentName === camelName) return val;
591
+ }
592
+ }
593
+
594
+ const cleanIsland = islandName.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
595
+ for (let i = 0; i < keys.length; i++) {
596
+ const k = keys[i];
597
+ if (k.toLowerCase() === cleanIsland && isReactComponentType(module[k])) {
598
+ return module[k];
599
+ }
600
+ }
601
+
602
+ const componentKeys = keys.filter(function (k) {
603
+ return isReactComponentType(module[k]);
604
+ });
605
+ if (componentKeys.length === 1) return module[componentKeys[0]];
606
+
607
+ const nonHooks = componentKeys.filter(function (k) {
608
+ const component = module[k];
609
+ const componentName = component.displayName || component.name || (component.render && component.render.name) || k;
610
+ return !/^use[A-Z]/.test(componentName);
611
+ });
612
+ if (nonHooks.length === 1) return module[nonHooks[0]];
613
+
614
+ if (islandName.endsWith("-provider") || islandName.includes("provider")) {
615
+ const provMatch = componentKeys.find(function (k) {
616
+ const component = module[k];
617
+ const componentName = component.displayName || component.name || (component.render && component.render.name) || k;
618
+ return /Provider$/i.test(componentName);
619
+ });
620
+ if (provMatch) return module[provMatch];
621
+ }
622
+
623
+ if (nonHooks.length > 0) return module[nonHooks[0]];
624
+ if (componentKeys.length > 0) return module[componentKeys[0]];
625
+ return undefined;
626
+ }
627
+
628
+ let providerComponentsPromise = null;
629
+ function loadProviderComponents() {
630
+ if (providerComponentsPromise) return providerComponentsPromise;
631
+ const ids = config.providers || [];
632
+ if (!ids.length) {
633
+ providerComponentsPromise = Promise.resolve([]);
634
+ return providerComponentsPromise;
635
+ }
636
+ providerComponentsPromise = Promise.all(ids.map(function (id) {
637
+ const chunkPath = config.manifest && config.manifest[id];
638
+ if (!chunkPath) return Promise.resolve(null);
639
+ const scriptUrl = config.themeUri + "/assets/" + chunkPath.replace("assets/", "").replace("assets\\\\", "");
640
+ return import(scriptUrl).then(function (module) {
641
+ return resolveExport(module, id);
642
+ }).catch(function (err) {
643
+ console.error("[ForgeWP Hydrator] Failed to load provider " + id + ":", err);
644
+ return null;
645
+ });
646
+ })).then(function (list) {
647
+ return list.filter(function (component) { return isReactComponentType(component); });
648
+ });
649
+ return providerComponentsPromise;
650
+ }
416
651
  })();`;
417
652
 
418
653
  writeFileSync(
@@ -434,10 +669,69 @@ export async function onFresh(themeRoot) {
434
669
  const routesPath = path.join(themeRoot, 'src', 'app', 'routes.tsx');
435
670
  const pagePath = path.join(themeRoot, 'src', 'app', 'page.tsx');
436
671
 
437
- const routesContent = `import { Route, Switch } from "wouter";
438
- import HomePage from "./page";
439
- import QuerySandbox from "./query-sandbox";
440
- import WpEditablePage from "./wp-editable";
672
+ const routesContent = `import type { ComponentType, ReactNode } from "react";
673
+ import { Route, Switch } from "@forgewp/react";
674
+ import * as HomePage from "./page";
675
+ import * as QuerySandbox from "./query-sandbox";
676
+ import * as WpEditablePage from "./wp-editable";
677
+
678
+ /**
679
+ * Automatically discover all layouts in src/app/layouts via Vite eager glob.
680
+ * Any layout file created (e.g. dashboard.tsx, auth.tsx, blank.tsx) is instantly
681
+ * available without needing manual imports or registration.
682
+ */
683
+ const layoutModules = import.meta.glob<Record<string, any>>("./layouts/*.{tsx,jsx,ts,js}", { eager: true });
684
+ const layouts: Record<string, ComponentType<{ children: ReactNode }>> = {};
685
+
686
+ for (const filePath in layoutModules) {
687
+ const match = filePath.match(/\\/([^/]+)\\.(tsx|jsx|ts|js)$/);
688
+ if (match) {
689
+ const layoutName = match[1];
690
+ const mod = layoutModules[filePath];
691
+ const comp = mod.default || Object.values(mod).find((v) => typeof v === "function");
692
+ if (comp) {
693
+ layouts[layoutName] = comp as ComponentType<{ children: ReactNode }>;
694
+ }
695
+ }
696
+ }
697
+
698
+ /**
699
+ * Layout-aware wrapper for local React dev routing.
700
+ * Resolves layout dynamically from \`export const pageConfig = { layout: '...' }\`
701
+ */
702
+ function withLayout(componentOrModule: any, customConfig?: any) {
703
+ return function PageWithLayout(props: any) {
704
+ const Component =
705
+ typeof componentOrModule === "function"
706
+ ? componentOrModule
707
+ : componentOrModule?.default || (() => null);
708
+
709
+ const config =
710
+ customConfig ||
711
+ componentOrModule?.pageConfig ||
712
+ (Component as any)?.pageConfig ||
713
+ {};
714
+
715
+ const layoutKey = config.layout ?? "default";
716
+
717
+ if (layoutKey === false || layoutKey === "blank") {
718
+ const BlankLayout = layouts["blank"] || (({ children }: any) => <>{children}</>);
719
+ return (
720
+ <BlankLayout>
721
+ <Component {...props} />
722
+ </BlankLayout>
723
+ );
724
+ }
725
+
726
+ const Layout = layouts[layoutKey] || layouts["default"] || (({ children }: any) => <>{children}</>);
727
+
728
+ return (
729
+ <Layout>
730
+ <Component {...props} />
731
+ </Layout>
732
+ );
733
+ };
734
+ }
441
735
 
442
736
  /**
443
737
  * Local Developer Routes — ForgeWP.
@@ -446,39 +740,41 @@ import WpEditablePage from "./wp-editable";
446
740
  *
447
741
  * @example
448
742
  * // 1. Create a component in src/app/about.tsx
449
- * // 2. Import it here: import AboutPage from "./about";
450
- * // 3. Add the Route: <Route path="/about" component={AboutPage} />
743
+ * // 2. Import it here: import * as AboutPage from "./about";
744
+ * // 3. Add the Route: <Route path="/about" component={withLayout(AboutPage)} />
451
745
  */
452
746
  export default function AppRoutes() {
453
747
  return (
454
748
  <Switch>
455
749
  {/* Home preview */}
456
- <Route path="/" component={HomePage} />
750
+ <Route path="/" component={withLayout(HomePage)} />
457
751
 
458
752
  {/* Relational Query Engine Sandbox — verifies taxQuery, metaQuery, pagination */}
459
- <Route path="/query-sandbox" component={QuerySandbox} />
753
+ <Route path="/query-sandbox" component={withLayout(QuerySandbox)} />
460
754
 
461
755
  {/* WpEditable Block Canvas Preview — verifies inline editing primitive */}
462
- <Route path="/wp-editable" component={WpEditablePage} />
756
+ <Route path="/wp-editable" component={withLayout(WpEditablePage)} />
463
757
 
464
758
  {/* Fallback route */}
465
759
  <Route>
466
- <div className="flex min-h-[60vh] flex-col items-center justify-center text-center p-6">
467
- <h1 className="text-4xl font-bold font-serif text-zinc-950">404</h1>
468
- <p className="mt-2 text-zinc-600">Page not found locally.</p>
469
- <div className="mt-4 flex flex-col items-center gap-2 text-sm">
470
- <a href="/" className="text-brand font-semibold hover:underline">← Go back home</a>
471
- <a href="/query-sandbox" className="text-zinc-500 font-mono hover:underline text-xs">→ Query Engine Sandbox</a>
472
- <a href="/wp-editable" className="text-zinc-500 font-mono hover:underline text-xs">→ WpEditable Canvas</a>
760
+ {withLayout(() => (
761
+ <div className="flex min-h-[60vh] flex-col items-center justify-center text-center p-6">
762
+ <h1 className="text-4xl font-bold font-serif text-zinc-950">404</h1>
763
+ <p className="mt-2 text-zinc-600">Page not found locally.</p>
764
+ <div className="mt-4 flex flex-col items-center gap-2 text-sm">
765
+ <a href="/" className="text-brand font-semibold hover:underline">← Go back home</a>
766
+ <a href="/query-sandbox" className="text-zinc-500 font-mono hover:underline text-xs">→ Query Engine Sandbox</a>
767
+ <a href="/wp-editable" className="text-zinc-500 font-mono hover:underline text-xs">→ WpEditable Canvas</a>
768
+ </div>
473
769
  </div>
474
- </div>
770
+ ))()}
475
771
  </Route>
476
772
  </Switch>
477
773
  );
478
774
  }
479
775
  `;
480
776
 
481
- const pageContent = `import { WpHead } from "../.forgewp/wordpress";
777
+ const pageContent = `import { WpHead } from "@forgewp/react";
482
778
  import { BookOpen, Github, ChevronRight, Database, Code2 } from "lucide-react";
483
779
 
484
780
  export default function HomePage() {
@@ -622,16 +918,22 @@ export default function HomePage() {
622
918
 
623
919
  try {
624
920
  writeFileSync(routesPath, routesContent, 'utf8');
625
- console.log(` ${pc.green('✅ Reset routes definition')}: src/app/routes.tsx`);
921
+ console.log(
922
+ ` ${pc.green('✅ Reset routes definition')}: src/app/routes.tsx`,
923
+ );
626
924
  } catch (err) {
627
- console.log(pc.red(` ❌ Failed to reset src/app/routes.tsx: ${err.message}`));
925
+ console.log(
926
+ pc.red(` ❌ Failed to reset src/app/routes.tsx: ${err.message}`),
927
+ );
628
928
  }
629
929
 
630
930
  try {
631
931
  writeFileSync(pagePath, pageContent, 'utf8');
632
932
  console.log(` ${pc.green('✅ Reset core template')}: src/app/page.tsx`);
633
933
  } catch (err) {
634
- console.log(pc.red(` ❌ Failed to reset src/app/page.tsx: ${err.message}`));
934
+ console.log(
935
+ pc.red(` ❌ Failed to reset src/app/page.tsx: ${err.message}`),
936
+ );
635
937
  }
636
938
 
637
939
  // Ensure shadcn's components.json is present so `forgewp add` works
@@ -639,39 +941,55 @@ export default function HomePage() {
639
941
  const componentsJsonPath = path.join(themeRoot, 'components.json');
640
942
  if (!existsSync(componentsJsonPath)) {
641
943
  const defaultComponentsJson = {
642
- "$schema": "https://ui.shadcn.com/schema.json",
643
- "style": "new-york",
644
- "rsc": false,
645
- "tsx": true,
646
- "tailwind": {
647
- "config": "tailwind.config.js",
648
- "css": "src/app/globals.css",
649
- "baseColor": "zinc",
650
- "cssVariables": true,
651
- "prefix": ""
944
+ $schema: 'https://ui.shadcn.com/schema.json',
945
+ style: 'new-york',
946
+ rsc: false,
947
+ tsx: true,
948
+ tailwind: {
949
+ config: 'tailwind.config.js',
950
+ css: 'src/app/globals.css',
951
+ baseColor: 'zinc',
952
+ cssVariables: true,
953
+ prefix: '',
652
954
  },
653
- "aliases": {
654
- "components": "@/components",
655
- "utils": "@/lib/utils",
656
- "ui": "@/components/ui",
657
- "lib": "@/lib",
658
- "hooks": "@/hooks"
955
+ aliases: {
956
+ components: '@/components',
957
+ utils: '@/lib/utils',
958
+ ui: '@/components/ui',
959
+ lib: '@/lib',
960
+ hooks: '@/hooks',
659
961
  },
660
- "iconLibrary": "lucide"
962
+ iconLibrary: 'lucide',
661
963
  };
662
964
  try {
663
- writeFileSync(componentsJsonPath, JSON.stringify(defaultComponentsJson, null, 2), 'utf8');
965
+ writeFileSync(
966
+ componentsJsonPath,
967
+ JSON.stringify(defaultComponentsJson, null, 2),
968
+ 'utf8',
969
+ );
664
970
  console.log(` ${pc.green('✅ Created shadcn config')}: components.json`);
665
971
  } catch (err) {
666
- console.log(pc.yellow(` ⚠️ Could not create components.json: ${err.message}`));
972
+ console.log(
973
+ pc.yellow(` ⚠️ Could not create components.json: ${err.message}`),
974
+ );
667
975
  }
668
976
  } else {
669
977
  console.log(` ${pc.dim('↳ components.json already present')}`);
670
978
  }
671
979
  }
672
980
 
673
-
674
- export function onMakeBlock(themeRoot, { pascalCase, readableTitle, attributesList, pc }) {
981
+ export function onMakeBlock(
982
+ themeRoot,
983
+ { pascalCase, readableTitle, attributesList, pc },
984
+ ) {
985
+ if (!/^[A-Za-z][A-Za-z0-9]*$/.test(pascalCase)) {
986
+ throw new Error('Block names must start with a letter and produce a valid component name.');
987
+ }
988
+ if (!Array.isArray(attributesList) || !attributesList.length || attributesList.some((name) =>
989
+ typeof name !== 'string' || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) || name === '__proto__'
990
+ ) || new Set(attributesList).size !== attributesList.length) {
991
+ throw new Error('Attribute names must be unique JavaScript property identifiers, such as title or cta_label. make:block creates string attributes; edit their types in source.');
992
+ }
675
993
  const blocksDir = path.join(themeRoot, 'src', 'blocks');
676
994
  if (!existsSync(blocksDir)) {
677
995
  mkdirSync(blocksDir, { recursive: true });
@@ -679,22 +997,28 @@ export function onMakeBlock(themeRoot, { pascalCase, readableTitle, attributesLi
679
997
 
680
998
  const targetFile = path.join(blocksDir, `${pascalCase}.tsx`);
681
999
  if (existsSync(targetFile)) {
682
- console.error(pc.red(`\n❌ Error: Block "${pascalCase}.tsx" already exists at src/blocks/\n`));
1000
+ console.error(
1001
+ pc.red(
1002
+ `\n❌ Error: Block "${pascalCase}.tsx" already exists at src/blocks/\n`,
1003
+ ),
1004
+ );
683
1005
  process.exit(1);
684
1006
  }
685
1007
 
686
- const nameSlug = pascalCase.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
1008
+ const nameSlug = pascalCase
1009
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
1010
+ .toLowerCase();
687
1011
 
688
1012
  const attributesRegistry = attributesList
689
- .map(a => ` ${a}: { type: "string", default: "Customize ${a} here" }`)
1013
+ .map((a) => ` ${a}: { type: "string", default: "Customize ${a} here" }`)
690
1014
  .join(',\n');
691
1015
 
692
1016
  const editFields = attributesList
693
- .map(a => {
1017
+ .map((a) => {
694
1018
  const cleanLabel = a
695
1019
  .replace(/_/g, ' ')
696
- .replace(/(?:^\w|[A-Z]|\b\w)/g, word => word.toUpperCase());
697
-
1020
+ .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => word.toUpperCase());
1021
+
698
1022
  if (a === 'content' || a === 'description' || a === 'body') {
699
1023
  return `<div className="border border-slate-100 p-4 bg-slate-50/30 rounded-none">
700
1024
  <label className="block text-xs font-mono font-bold uppercase text-slate-700 mb-1">${cleanLabel}</label>
@@ -745,18 +1069,10 @@ export function onMakeBlock(themeRoot, { pascalCase, readableTitle, attributesLi
745
1069
  /**
746
1070
  * ⚡ ForgeWP Custom Gutenberg Block — "Sharp ${readableTitle}"
747
1071
  *
748
- * HOW TO PREVIEW LOCALLY INSIDE REACT:
749
- * This block is defined using standard React structures. You can import this block and
750
- * preview its visitor/frontend layout locally in any React page or component without running
751
- * WordPress, by invoking its `.save()` component with mock attributes:
752
- *
753
- * \`\`\`tsx
754
- * import ${pascalCase} from "@/blocks/${pascalCase}";
755
- *
756
- * <${pascalCase}.save attributes={{
757
- * ${attributesList.map((a, i) => `${a}: "Mock Value ${i + 1}"`).join(',\n ')}
758
- * }} />
759
- * \`\`\`
1072
+ * LOCAL PREVIEW: Import this definition and pass it in BlockArea.previewBlocks.
1073
+ * Use the map key forgewp/${nameSlug}. The current mock post's serialized content
1074
+ * selects block instances, their order, and saved attributes.
1075
+ * This generated TSX is editable source; export creates WordPress block assets.
760
1076
  */
761
1077
  export default defineBlock({
762
1078
  name: "${nameSlug}",
@@ -793,13 +1109,157 @@ ${attributesRegistry}
793
1109
 
794
1110
  writeFileSync(targetFile, blockTemplate, 'utf8');
795
1111
 
796
- console.log(pc.green(`\n⚡ Modern Block "${pascalCase}" successfully created!`));
1112
+ console.log(
1113
+ pc.green(`\n⚡ Modern Block "${pascalCase}" successfully created!`),
1114
+ );
797
1115
  console.log(` Location: ${pc.cyan(`src/blocks/${pascalCase}.tsx`)}`);
798
1116
  console.log(` Gutenberg Title: ${pc.yellow(`Sharp ${readableTitle}`)}`);
799
- console.log(`\n🎉 Run ${pc.cyan('pnpm export')} to automatically register it inside your WordPress theme!\n`);
1117
+ console.log(' Edit this source file; export generates block.json, render.php, and editor assets.');
1118
+ console.log(
1119
+ `\n🎉 Run ${pc.cyan('pnpm export')} to automatically register it inside your WordPress theme!\n`,
1120
+ );
1121
+ }
1122
+
1123
+ /**
1124
+ * Scaffold a parent shell block (layout + InnerBlocks). No content attributes.
1125
+ * @param {string} themeRoot
1126
+ * @param {object} opts
1127
+ */
1128
+ export function onMakeShell(
1129
+ themeRoot,
1130
+ {
1131
+ pascalCase,
1132
+ nameSlug,
1133
+ readableTitle,
1134
+ childrenSlugs = [],
1135
+ shell = {},
1136
+ innerBlocks = {},
1137
+ category = 'theme',
1138
+ icon = 'columns',
1139
+ description = '',
1140
+ pc: colors,
1141
+ },
1142
+ ) {
1143
+ const log = colors || pc;
1144
+ const blocksDir = path.join(themeRoot, 'src', 'blocks');
1145
+ if (!existsSync(blocksDir)) {
1146
+ mkdirSync(blocksDir, { recursive: true });
1147
+ }
1148
+
1149
+ const targetFile = path.join(blocksDir, `${pascalCase}.tsx`);
1150
+ if (existsSync(targetFile)) {
1151
+ console.error(
1152
+ log.red(
1153
+ `\n❌ Error: Block "${pascalCase}.tsx" already exists at src/blocks/\n`,
1154
+ ),
1155
+ );
1156
+ process.exit(1);
1157
+ }
1158
+
1159
+ const slug =
1160
+ nameSlug ||
1161
+ pascalCase
1162
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
1163
+ .toLowerCase()
1164
+ .replace(/[^a-z0-9]+/g, '-');
1165
+
1166
+ const title = readableTitle || pascalCase.replace(/([A-Z])/g, ' $1').trim();
1167
+ const className =
1168
+ shell.className || 'max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16';
1169
+ const gridClassName =
1170
+ shell.gridClassName ||
1171
+ 'grid grid-cols-1 lg:grid-cols-2 gap-12 items-center';
1172
+
1173
+ const allowed = Array.isArray(innerBlocks.allowedBlocks)
1174
+ ? innerBlocks.allowedBlocks
1175
+ : childrenSlugs;
1176
+ const template = Array.isArray(innerBlocks.template)
1177
+ ? innerBlocks.template
1178
+ : allowed.map((s) => [s]);
1179
+ const templateLock =
1180
+ innerBlocks.templateLock === undefined ? false : innerBlocks.templateLock;
1181
+ const orientation = innerBlocks.orientation || 'horizontal';
1182
+
1183
+ const allowedLit = allowed.length
1184
+ ? `[\n${allowed.map((s) => ` ${JSON.stringify(s)},`).join('\n')}\n ]`
1185
+ : 'undefined';
1186
+ const templateLit = template.length
1187
+ ? `[\n${template
1188
+ .map((row) => {
1189
+ const name = Array.isArray(row) ? row[0] : row;
1190
+ return ` ${JSON.stringify(Array.isArray(row) ? row : [name])},`;
1191
+ })
1192
+ .join('\n')}\n ]`
1193
+ : 'undefined';
1194
+
1195
+ const lockLit =
1196
+ templateLock === false
1197
+ ? 'false'
1198
+ : templateLock === true
1199
+ ? 'true'
1200
+ : JSON.stringify(templateLock);
1201
+
1202
+ const descLit = JSON.stringify(
1203
+ description ||
1204
+ `Layout shell for ${title}${allowed.length ? ` (${allowed.join(' + ')})` : ''}`,
1205
+ );
1206
+
1207
+ const shellTemplate = `import { defineBlock } from '@forgewp/react';
1208
+
1209
+ /**
1210
+ * Parent shell — layout only (InnerBlocks).
1211
+ *
1212
+ * Children are normal ForgeWP blocks. This shell provides the outer chrome +
1213
+ * grid; the compiler generates the editor UI and PHP wrapper from
1214
+ * \`innerBlocks\` + \`shell\`.
1215
+ *
1216
+ * Scaffolded by: pnpm forgewp make:shell
1217
+ */
1218
+ export default defineBlock({
1219
+ name: '${slug}',
1220
+ title: ${JSON.stringify(title)},
1221
+ category: ${JSON.stringify(category)},
1222
+ icon: ${JSON.stringify(icon)},
1223
+ description: ${descLit},
1224
+ // No content attributes — children own their fields.
1225
+ attributes: {},
1226
+ innerBlocks: {
1227
+ allowedBlocks: ${allowedLit},
1228
+ template: ${templateLit},
1229
+ templateLock: ${lockLit},
1230
+ orientation: ${JSON.stringify(orientation)},
1231
+ },
1232
+ shell: {
1233
+ className: ${JSON.stringify(className)},
1234
+ gridClassName: ${JSON.stringify(gridClassName)},
1235
+ },
1236
+ // Compiler generates the real editor UI from innerBlocks + shell.
1237
+ edit: () => null,
1238
+ });
1239
+ `;
1240
+
1241
+ writeFileSync(targetFile, shellTemplate, 'utf8');
1242
+
1243
+ console.log(log.green(`\n⚡ Parent shell "${pascalCase}" created!`));
1244
+ console.log(` Location: ${log.cyan(`src/blocks/${pascalCase}.tsx`)}`);
1245
+ console.log(` Block name: ${log.yellow(`forgewp/${slug}`)}`);
1246
+ if (allowed.length) {
1247
+ console.log(` Children: ${log.cyan(allowed.join(', '))}`);
1248
+ } else {
1249
+ console.log(
1250
+ ` Children: ${log.dim('(none — open shell; any allowed at runtime)')}`,
1251
+ );
1252
+ }
1253
+ console.log(` Layout: ${log.dim(gridClassName)}`);
1254
+ console.log(
1255
+ `\n🎉 Run ${log.cyan('pnpm forgewp export')} (or sync-to-wp) to register it in WordPress.\n`,
1256
+ );
800
1257
  }
801
1258
 
802
- export function onMakeLoop(themeRoot, { pascalCase, postType, customFields, automaticallySeeded, pc }) {
1259
+ export function onMakeLoop(
1260
+ themeRoot,
1261
+ { pascalCase, postType, customFields, automaticallySeeded, pc },
1262
+ ) {
803
1263
  const loopsDir = path.join(themeRoot, 'src', 'loops');
804
1264
  if (!existsSync(loopsDir)) {
805
1265
  mkdirSync(loopsDir, { recursive: true });
@@ -807,17 +1267,21 @@ export function onMakeLoop(themeRoot, { pascalCase, postType, customFields, auto
807
1267
 
808
1268
  const targetFile = path.join(loopsDir, `${pascalCase}.tsx`);
809
1269
  if (existsSync(targetFile)) {
810
- console.error(pc.red(`\n❌ Error: Loop "${pascalCase}.tsx" already exists at src/loops/\n`));
1270
+ console.error(
1271
+ pc.red(
1272
+ `\n❌ Error: Loop "${pascalCase}.tsx" already exists at src/loops/\n`,
1273
+ ),
1274
+ );
811
1275
  process.exit(1);
812
1276
  }
813
1277
 
814
1278
  let customFieldsMarkup = '';
815
1279
  if (customFields.length > 0) {
816
1280
  customFieldsMarkup = customFields
817
- .map(f => {
1281
+ .map((f) => {
818
1282
  const cleanLabel = f
819
1283
  .replace(/_/g, ' ')
820
- .replace(/(?:^\w|[A-Z]|\b\w)/g, word => word.toUpperCase());
1284
+ .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => word.toUpperCase());
821
1285
  return `<div className="flex justify-between border-t border-slate-100 pt-2 text-xs font-mono text-slate-500">
822
1286
  <span>${cleanLabel}:</span>
823
1287
  <span className="font-bold text-slate-800">{useWpCustomField("${f}")}</span>
@@ -828,7 +1292,7 @@ export function onMakeLoop(themeRoot, { pascalCase, postType, customFields, auto
828
1292
  customFieldsMarkup = `{/* No custom fields registered in mock-data.json. Add fields by running forgewp make:post-type */}\n <p className="text-xs text-zinc-500 font-mono italic">No custom fields configured for post type: ${postType}</p>`;
829
1293
  }
830
1294
 
831
- const loopTemplate = `import { WpQueryLoop, useWpTitle, useWpFeaturedImage, useWpExcerpt, useWpPermalink, useWpCustomField } from "@/.forgewp/wordpress";
1295
+ const loopTemplate = `import { WpQueryLoop, useWpTitle, useWpFeaturedImage, useWpExcerpt, useWpPermalink, useWpCustomField } from "@forgewp/react";
832
1296
 
833
1297
  /**
834
1298
  * ⚡ ForgeWP Custom Post Type Loop — "${pascalCase}"
@@ -889,18 +1353,28 @@ export default function ${pascalCase}() {
889
1353
  writeFileSync(targetFile, loopTemplate, 'utf8');
890
1354
 
891
1355
  if (automaticallySeeded) {
892
- console.log(pc.yellow(`\n⚠️ Post type "${postType}" was missing from local database (mock-data.json).`));
893
- console.log(` We have automatically registered it and seeded default custom fields for you!`);
1356
+ console.log(
1357
+ pc.yellow(
1358
+ `\n⚠️ Post type "${postType}" was missing from local database (mock-data.json).`,
1359
+ ),
1360
+ );
1361
+ console.log(
1362
+ ` We have automatically registered it and seeded default custom fields for you!`,
1363
+ );
894
1364
  }
895
1365
 
896
1366
  console.log(pc.green(`\n⚡ Post Loop "${pascalCase}" successfully created!`));
897
1367
  console.log(` Location: ${pc.cyan(`src/loops/${pascalCase}.tsx`)}`);
898
1368
  console.log(` Target Post Type: ${pc.yellow(postType)}`);
899
1369
  if (customFields.length > 0) {
900
- console.log(` Seeded Custom Fields: ${pc.yellow(customFields.join(', '))}`);
1370
+ console.log(
1371
+ ` Seeded Custom Fields: ${pc.yellow(customFields.join(', '))}`,
1372
+ );
901
1373
  }
902
1374
  console.log(`\n🎉 You can now import it directly inside your pages:`);
903
- console.log(` ${pc.cyan(`import ${pascalCase} from "@/loops/${pascalCase}";`)}\n`);
1375
+ console.log(
1376
+ ` ${pc.cyan(`import ${pascalCase} from "@/loops/${pascalCase}";`)}\n`,
1377
+ );
904
1378
  }
905
1379
 
906
1380
  export function onMakeIsland(themeRoot, { pascalCase, pc }) {
@@ -911,66 +1385,42 @@ export function onMakeIsland(themeRoot, { pascalCase, pc }) {
911
1385
 
912
1386
  const targetFile = path.join(componentsDir, `${pascalCase}.tsx`);
913
1387
  if (existsSync(targetFile)) {
914
- console.error(pc.red(`\n❌ Error: Island "${pascalCase}.tsx" already exists at src/components/\n`));
1388
+ console.error(
1389
+ pc.red(
1390
+ `\n❌ Error: Island "${pascalCase}.tsx" already exists at src/components/\n`,
1391
+ ),
1392
+ );
915
1393
  process.exit(1);
916
1394
  }
917
1395
 
918
- const islandTemplate = `import { useState, useEffect } from "react";
1396
+ const islandTemplate = `import { useState } from "react";
919
1397
 
920
1398
  /**
921
1399
  * ⚡ ForgeWP Selective Hydration Island Component — "${pascalCase}"
922
- *
923
- * IMPORTANT FOR INTERACTIVITY:
924
- * This component runs client-side React state hooks (useState, useEffect). To enable
925
- * interactivity on the WordPress frontend, you MUST wrap this component in the `<Hydrate>`
926
- * controller when rendering it in your page layout.
927
- *
928
- * Example:
1400
+ *
1401
+ * NOTE: ForgeWP automatically detects that this component is interactive (using React hooks/state)
1402
+ * and wraps it in a \`<Hydrate>\` wrapper during theme compilation with the default 'visible' trigger.
1403
+ *
1404
+ * You do NOT need to manually wrap it unless you want to customize the trigger
1405
+ * (e.g., to load on 'click', 'hover', 'interaction', or 'idle').
1406
+ *
1407
+ * Example of custom trigger overrides:
929
1408
  * import ${pascalCase} from "@/components/${pascalCase}";
930
1409
  * import { Hydrate } from "@forgewp/react";
931
- *
932
- * <Hydrate trigger="visible" preload="near-visible">
1410
+ *
1411
+ * <Hydrate trigger="click">
933
1412
  * <${pascalCase} />
934
1413
  * </Hydrate>
935
1414
  */
936
- export interface ${pascalCase}Props {
937
- label?: string;
938
- }
939
-
940
- export default function ${pascalCase}({ label = "React State Island (${pascalCase})" }: ${pascalCase}Props) {
941
- const [count, setCount] = useState(0);
942
- const [isHydrated, setIsHydrated] = useState(false);
1415
+ export interface ${pascalCase}Props {}
943
1416
 
944
- useEffect(() => {
945
- setIsHydrated(true);
946
- }, []);
1417
+ export default function ${pascalCase}(_props: ${pascalCase}Props) {
1418
+ const [value, setValue] = useState(0);
947
1419
 
948
1420
  return (
949
- <div className="p-6 border border-slate-100 bg-white font-sans text-slate-900 shadow-xl shadow-slate-100/50 hover:-translate-y-0.5 transition-all duration-300 rounded-none">
950
- <div className="flex items-center justify-between gap-4 mb-4 border-b border-slate-100 pb-2">
951
- <span className="block text-sm font-bold uppercase tracking-wider">
952
- {label}
953
- </span>
954
- <span
955
- className={\`text-[10px] font-bold px-2 py-0.5 uppercase tracking-widest border transition-all duration-300 \${
956
- isHydrated
957
- ? "bg-emerald-50 text-emerald-700 border-emerald-200 font-black"
958
- : "bg-amber-50 text-amber-700 border-amber-200 font-black animate-pulse"
959
- }\`}
960
- >
961
- {isHydrated ? "● Hydrated" : "○ Static (SSR)"}
962
- </span>
963
- </div>
964
-
965
- <div className="flex items-center gap-4 mt-2">
966
- <span className="text-2xl font-black text-slate-800">Counter: {count}</span>
967
- <button
968
- onClick={() => setCount((c) => c + 1)}
969
- className="border border-primary bg-primary text-white px-4 py-2 font-bold text-xs uppercase tracking-widest hover:bg-transparent hover:text-primary transition-all duration-300 shadow-sm cursor-pointer"
970
- >
971
- Increment Value
972
- </button>
973
- </div>
1421
+ <div>
1422
+ <span>{value}</span>
1423
+ <button onClick={() => setValue((v) => v + 1)}>Update</button>
974
1424
  </div>
975
1425
  );
976
1426
  }
@@ -978,11 +1428,22 @@ export default function ${pascalCase}({ label = "React State Island (${pascalCas
978
1428
 
979
1429
  writeFileSync(targetFile, islandTemplate, 'utf8');
980
1430
 
981
- console.log(pc.green(`\n⚡ Selective Hydration Island "${pascalCase}" successfully created!`));
1431
+ console.log(
1432
+ pc.green(
1433
+ `\n⚡ Selective Hydration Island "${pascalCase}" successfully created!`,
1434
+ ),
1435
+ );
982
1436
  console.log(` Location: ${pc.cyan(`src/components/${pascalCase}.tsx`)}`);
983
- console.log(`\n🎉 To render this island with selective hydration triggers:`);
984
- console.log(` Inside any page, wrap it with:`);
985
- console.log(` ${pc.cyan(`<Hydrate trigger="visible" preload="near-visible">\n <${pascalCase} />\n </Hydrate>`)}\n`);
1437
+ console.log(
1438
+ `\n🎉 ForgeWP automatically detects and hydrates this component on compile!`,
1439
+ );
1440
+ console.log(
1441
+ ` If you want to customize the trigger (e.g. hydrate on click):`,
1442
+ );
1443
+ console.log(` Wrap it with:`);
1444
+ console.log(
1445
+ ` ${pc.cyan(`<Hydrate trigger="click">\n <${pascalCase} />\n </Hydrate>`)}\n`,
1446
+ );
986
1447
  }
987
1448
 
988
1449
  export function onMakePage(themeRoot, { pascalCase, pc }) {
@@ -993,11 +1454,17 @@ export function onMakePage(themeRoot, { pascalCase, pc }) {
993
1454
 
994
1455
  const targetFile = path.join(pagesDir, `${pascalCase}.tsx`);
995
1456
  if (existsSync(targetFile)) {
996
- console.error(pc.red(`\n❌ Error: Page Template "${pascalCase}.tsx" already exists at src/app/pages/\n`));
1457
+ console.error(
1458
+ pc.red(
1459
+ `\n❌ Error: Page Template "${pascalCase}.tsx" already exists at src/app/pages/\n`,
1460
+ ),
1461
+ );
997
1462
  process.exit(1);
998
1463
  }
999
1464
 
1000
- const pageTemplate = `import { WpHead, useWpTitle, useWpExcerpt } from "../../.forgewp/wordpress";
1465
+ const pageTemplate = `import { WpHead, useWpTitle, useWpExcerpt } from "@forgewp/react";
1466
+
1467
+ export const pageConfig = { layout: "default" };
1001
1468
 
1002
1469
  /**
1003
1470
  * ⚡ ForgeWP Custom Page Template — "${pascalCase}"
@@ -1039,21 +1506,223 @@ export function ${pascalCase}() {
1039
1506
 
1040
1507
  writeFileSync(targetFile, pageTemplate, 'utf8');
1041
1508
 
1042
- console.log(pc.green(`\n⚡ Custom Page Template "${pascalCase}" successfully created!`));
1509
+ console.log(
1510
+ pc.green(`\n⚡ Custom Page Template "${pascalCase}" successfully created!`),
1511
+ );
1043
1512
  console.log(` Location: ${pc.cyan(`src/app/pages/${pascalCase}.tsx`)}`);
1044
1513
  console.log(` WordPress Template Name: ${pc.yellow(pascalCase)}`);
1045
1514
  console.log(`\n🎉 To link it in your application routing:`);
1046
1515
  console.log(` Add it inside your ${pc.cyan('src/app/routes.tsx')} file.\n`);
1047
1516
  }
1048
1517
 
1518
+ export function onMakeForm(
1519
+ themeRoot,
1520
+ { slug, pascalCase, fields, mailTo, pc },
1521
+ ) {
1522
+ const formsDir = path.join(themeRoot, 'cms', 'forms');
1523
+ if (!existsSync(formsDir)) {
1524
+ mkdirSync(formsDir, { recursive: true });
1525
+ }
1526
+ const formConfigFile = path.join(formsDir, `${slug}.ts`);
1527
+ if (existsSync(formConfigFile)) {
1528
+ console.error(
1529
+ pc.red(`\n❌ Error: Form "${slug}.ts" already exists at cms/forms/\n`),
1530
+ );
1531
+ process.exit(1);
1532
+ }
1533
+
1534
+ const componentsDir = path.join(themeRoot, 'src', 'components', 'forms');
1535
+ if (!existsSync(componentsDir)) {
1536
+ mkdirSync(componentsDir, { recursive: true });
1537
+ }
1538
+ const componentName = `${pascalCase}Form`;
1539
+ const componentFile = path.join(componentsDir, `${componentName}.tsx`);
1540
+ if (existsSync(componentFile)) {
1541
+ console.error(
1542
+ pc.red(
1543
+ `\n❌ Error: Form component "${componentName}.tsx" already exists at src/components/forms/\n`,
1544
+ ),
1545
+ );
1546
+ process.exit(1);
1547
+ }
1548
+
1549
+ const toLabel = (name) =>
1550
+ name
1551
+ .replace(/[_-]+/g, ' ')
1552
+ .split(' ')
1553
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
1554
+ .join(' ');
1555
+
1556
+ // ── cms/forms/{slug}.ts ──────────────────────────────────────────────
1557
+ const fieldsConfigPhp = fields
1558
+ .map(({ name, type }) => {
1559
+ const label = toLabel(name);
1560
+ if (type === 'select') {
1561
+ return ` ${name}: { type: 'select', label: '${label}', required: true, options: ['Option 1', 'Option 2'] },`;
1562
+ }
1563
+ return ` ${name}: { type: '${type}', label: '${label}', required: true },`;
1564
+ })
1565
+ .join('\n');
1566
+
1567
+ const formConfigTemplate = `/**
1568
+ * ${toLabel(slug)} form — server-side contract for submitWpForm('${slug}', ...).
1569
+ *
1570
+ * Source of truth for:
1571
+ * - REST endpoint (/forgewp/v1/forms/${slug}/submit)
1572
+ * - mail delivery + optional submission storage (wp-admin > Forms Submissions)
1573
+ *
1574
+ * Discovered automatically from this file — nothing else needs to reference
1575
+ * it. See ${componentName}.tsx (src/components/forms/) for the matching UI.
1576
+ *
1577
+ * Want client-editable fields (added/removed later in wp-admin, without a
1578
+ * redeploy)? Add a \`clientFields\` key here and render it with
1579
+ * <WpFormFields form="${slug}" render={...} /> — see forgewp_forms_spec.md.
1580
+ */
1581
+ import { defineWpForm } from '@forgewp/react/config';
1582
+
1583
+ export const form = defineWpForm({
1584
+ mailTo: '${mailTo}',
1585
+ subject: 'New ${toLabel(slug)} submission',
1586
+ fields: {
1587
+ ${fieldsConfigPhp}
1588
+ },
1589
+ storeSubmissions: true,
1590
+ });
1591
+ `;
1592
+
1593
+ writeFileSync(formConfigFile, formConfigTemplate, 'utf8');
1594
+
1595
+ // ── src/components/forms/{Name}Form.tsx ─────────────────────────────
1596
+ const inputClassName =
1597
+ 'w-full border border-slate-200 rounded-lg px-4 py-2.5 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary/40 transition-all';
1598
+
1599
+ const fieldMarkup = fields
1600
+ .map(({ name, type }) => {
1601
+ const label = toLabel(name);
1602
+ let control;
1603
+ if (type === 'textarea') {
1604
+ control = `<textarea
1605
+ name="${name}"
1606
+ required
1607
+ rows={5}
1608
+ className="${inputClassName} resize-none"
1609
+ />`;
1610
+ } else if (type === 'select') {
1611
+ control = `<select name="${name}" required className="${inputClassName} bg-white">
1612
+ <option value="">Please choose…</option>
1613
+ <option value="Option 1">Option 1</option>
1614
+ <option value="Option 2">Option 2</option>
1615
+ </select>`;
1616
+ } else if (type === 'checkbox') {
1617
+ control = `<input type="checkbox" name="${name}" required />`;
1618
+ } else {
1619
+ control = `<input
1620
+ type="${type}"
1621
+ name="${name}"
1622
+ required
1623
+ className="${inputClassName}"
1624
+ />`;
1625
+ }
1626
+ return ` <div>
1627
+ <label className="block text-xs font-semibold uppercase tracking-wide text-slate-500 mb-1.5">
1628
+ ${label}
1629
+ </label>
1630
+ ${control}
1631
+ </div>`;
1632
+ })
1633
+ .join('\n');
1634
+
1635
+ const componentTemplate = `import * as React from "react";
1636
+ import { submitWpForm } from "@forgewp/react";
1637
+
1638
+ /**
1639
+ * ⚡ ForgeWP Form — "${componentName}"
1640
+ *
1641
+ * Submits to the "${slug}" form declared in cms/forms/${slug}.ts. ForgeWP
1642
+ * auto-detects this component as interactive (uses React state) and
1643
+ * hydrates it in the browser so onSubmit fires instead of a native form
1644
+ * GET submit.
1645
+ */
1646
+ export default function ${componentName}() {
1647
+ const [status, setStatus] = React.useState<"idle" | "sending" | "success" | "error">("idle");
1648
+ const [errorMsg, setErrorMsg] = React.useState("");
1649
+
1650
+ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
1651
+ e.preventDefault();
1652
+ setStatus("sending");
1653
+ setErrorMsg("");
1654
+
1655
+ const result = await submitWpForm("${slug}", new FormData(e.currentTarget));
1656
+
1657
+ if (result.ok) {
1658
+ setStatus("success");
1659
+ e.currentTarget.reset();
1660
+ } else {
1661
+ setErrorMsg(result.message || "Something went wrong. Please try again.");
1662
+ setStatus("error");
1663
+ }
1664
+ };
1665
+
1666
+ if (status === "success") {
1667
+ return (
1668
+ <div className="bg-white border border-slate-100 rounded-2xl shadow-xs p-8 text-center">
1669
+ <h2 className="text-lg font-bold text-slate-900 mb-2">Thanks — message sent!</h2>
1670
+ <p className="text-slate-500 text-sm">We'll get back to you soon.</p>
1671
+ <button
1672
+ onClick={() => setStatus("idle")}
1673
+ className="mt-6 bg-primary text-white text-xs font-bold uppercase tracking-wider px-6 py-3 rounded-xl cursor-pointer hover:bg-primary/90 transition-all"
1674
+ >
1675
+ Send another message
1676
+ </button>
1677
+ </div>
1678
+ );
1679
+ }
1680
+
1681
+ return (
1682
+ <form onSubmit={handleSubmit} className="bg-white border border-slate-100 rounded-2xl shadow-xs p-8 space-y-5">
1683
+ ${fieldMarkup}
1684
+
1685
+ {status === "error" && (
1686
+ <div className="bg-red-50 border border-red-200 text-red-700 text-xs font-semibold rounded-xl px-4 py-3">
1687
+ {errorMsg}
1688
+ </div>
1689
+ )}
1690
+
1691
+ <button
1692
+ type="submit"
1693
+ disabled={status === "sending"}
1694
+ className="w-full bg-primary hover:bg-primary/90 disabled:opacity-60 disabled:cursor-not-allowed text-white font-bold text-xs uppercase tracking-wider px-6 py-3.5 rounded-xl transition-all cursor-pointer"
1695
+ >
1696
+ {status === "sending" ? "Sending…" : "Send"}
1697
+ </button>
1698
+ </form>
1699
+ );
1700
+ }
1701
+ `;
1702
+
1703
+ writeFileSync(componentFile, componentTemplate, 'utf8');
1704
+
1705
+ console.log(pc.green(`\n⚡ Form "${slug}" successfully created!`));
1706
+ console.log(` Config: ${pc.cyan(`cms/forms/${slug}.ts`)}`);
1707
+ console.log(
1708
+ ` Component: ${pc.cyan(`src/components/forms/${componentName}.tsx`)}`,
1709
+ );
1710
+ console.log(`\n🎉 Use it in a page:`);
1711
+ console.log(
1712
+ ` ${pc.yellow(`import ${componentName} from "@/components/forms/${componentName}";`)}\n`,
1713
+ );
1714
+ }
1715
+
1049
1716
  export function onSyncRoutes(themeRoot, { routesToScaffold, isForce, pc }) {
1050
1717
  function toPascalCase(str) {
1051
- return str
1052
- .replace(/[^a-zA-Z0-9]/g, ' ')
1053
- .trim()
1054
- .split(/\s+/)
1055
- .map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
1056
- .join('') + 'Page';
1718
+ return (
1719
+ str
1720
+ .replace(/[^a-zA-Z0-9]/g, ' ')
1721
+ .trim()
1722
+ .split(/\s+/)
1723
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
1724
+ .join('') + 'Page'
1725
+ );
1057
1726
  }
1058
1727
 
1059
1728
  const pagesDir = path.join(themeRoot, 'src', 'app', 'pages');
@@ -1081,8 +1750,9 @@ export function onSyncRoutes(themeRoot, { routesToScaffold, isForce, pc }) {
1081
1750
  * This file compiles into a standalone WordPress Custom Page Template.
1082
1751
  * You can select it in the WordPress page editor dropdown as "Template: ${componentName}".
1083
1752
  */
1084
- import { WpHead } from "../../.forgewp/wordpress";
1085
- import { WpQueryLoop, useWpTitle, useWpExcerpt, useWpFeaturedImage } from "../../.forgewp/wordpress";
1753
+ import { WpHead, WpQueryLoop, useWpTitle, useWpExcerpt, useWpFeaturedImage } from "@forgewp/react";
1754
+
1755
+ export const pageConfig = { layout: "default" };
1086
1756
 
1087
1757
  export function ${componentName}() {
1088
1758
  return (
@@ -1135,33 +1805,77 @@ export function ${componentName}() {
1135
1805
  `;
1136
1806
 
1137
1807
  if (existsSync(componentPath) && !isForce) {
1138
- console.log(` ${pc.gray('ℹ️ [Skip] Component already exists:')} src/app/pages/${componentName}.tsx`);
1808
+ console.log(
1809
+ ` ${pc.gray('ℹ️ [Skip] Component already exists:')} src/app/pages/${componentName}.tsx`,
1810
+ );
1139
1811
  skippedCount++;
1140
1812
  } else {
1141
1813
  writeFileSync(componentPath, componentContent, 'utf8');
1142
- console.log(` ${pc.green('✅ Scaffolded component')}: src/app/pages/${componentName}.tsx`);
1814
+ console.log(
1815
+ ` ${pc.green('✅ Scaffolded component')}: src/app/pages/${componentName}.tsx`,
1816
+ );
1143
1817
  scaffoldedCount++;
1144
1818
  }
1145
1819
  }
1146
1820
 
1147
- // Discover Custom Post Types (CPTs) from cms/mock-data.json
1148
- const mockDataPath = path.join(themeRoot, 'cms', 'mock-data.json');
1821
+ // Discover Custom Post Types from cms/mock-data.ts (preferred) plus leftover cms/*.json
1822
+ const cmsDir = path.join(themeRoot, 'cms');
1149
1823
  let cpts = [];
1150
- if (existsSync(mockDataPath)) {
1151
- try {
1152
- const mockData = JSON.parse(readFileSync(mockDataPath, 'utf8'));
1153
- for (const [key, value] of Object.entries(mockData)) {
1154
- if (
1155
- Array.isArray(value) &&
1156
- !key.startsWith('_') &&
1157
- !['post', 'page', 'menu', 'primary', 'utility'].includes(key)
1158
- ) {
1159
- cpts.push(key);
1160
- }
1824
+ const skipCptKeys = new Set([
1825
+ 'post',
1826
+ 'posts',
1827
+ 'page',
1828
+ 'pages',
1829
+ 'menu',
1830
+ 'menus',
1831
+ 'primary',
1832
+ 'utility',
1833
+ 'attachment',
1834
+ ]);
1835
+ const ingestCptMap = (fileContent) => {
1836
+ if (
1837
+ !fileContent ||
1838
+ typeof fileContent !== 'object' ||
1839
+ Array.isArray(fileContent)
1840
+ )
1841
+ return;
1842
+ for (const [key, value] of Object.entries(fileContent)) {
1843
+ if (
1844
+ Array.isArray(value) &&
1845
+ !key.startsWith('_') &&
1846
+ !skipCptKeys.has(key) &&
1847
+ !cpts.includes(key)
1848
+ ) {
1849
+ cpts.push(key);
1850
+ }
1851
+ }
1852
+ };
1853
+ try {
1854
+ ingestCptMap(loadMockData(themeRoot));
1855
+ if (existsSync(cmsDir)) {
1856
+ const skipJson = new Set([
1857
+ 'menus.json',
1858
+ 'users.json',
1859
+ 'roles.json',
1860
+ 'sessions.json',
1861
+ 'translations.json',
1862
+ 'mock-data.json',
1863
+ ]);
1864
+ const jsonFiles = readdirSync(cmsDir).filter(
1865
+ (f) => f.endsWith('.json') && !skipJson.has(f),
1866
+ );
1867
+ for (const f of jsonFiles) {
1868
+ try {
1869
+ ingestCptMap(JSON.parse(readFileSync(path.join(cmsDir, f), 'utf8')));
1870
+ } catch {}
1161
1871
  }
1162
- } catch (e) {
1163
- console.log(pc.yellow(` ⚠️ Warning: Failed to parse cms/mock-data.json for CPT auto-discovery.`));
1164
1872
  }
1873
+ } catch (e) {
1874
+ console.log(
1875
+ pc.yellow(
1876
+ ` ⚠️ Warning: Failed to read cms/ directory for CPT auto-discovery.`,
1877
+ ),
1878
+ );
1165
1879
  }
1166
1880
 
1167
1881
  let cptScaffoldedCount = 0;
@@ -1169,18 +1883,20 @@ export function ${componentName}() {
1169
1883
 
1170
1884
  for (const cpt of cpts) {
1171
1885
  const pascalCpt = cpt.charAt(0).toUpperCase() + cpt.slice(1);
1172
-
1886
+
1173
1887
  // 1. Scaffold thin wrapper src/app/single-${cpt}.tsx
1174
1888
  const wrapperPath = path.join(themeRoot, 'src', 'app', `single-${cpt}.tsx`);
1175
1889
  const wrapperContent = `import { Single${pascalCpt}Page } from "./pages/Single${pascalCpt}Page";
1176
1890
  export default Single${pascalCpt}Page;
1177
1891
  `;
1178
-
1892
+
1179
1893
  if (existsSync(wrapperPath) && !isForce) {
1180
1894
  // Skip wrapper
1181
1895
  } else {
1182
1896
  writeFileSync(wrapperPath, wrapperContent, 'utf8');
1183
- console.log(` ${pc.green('✅ Scaffolded thin CPT wrapper')}: src/app/single-${cpt}.tsx`);
1897
+ console.log(
1898
+ ` ${pc.green('✅ Scaffolded thin CPT wrapper')}: src/app/single-${cpt}.tsx`,
1899
+ );
1184
1900
  }
1185
1901
 
1186
1902
  // 2. Scaffold page component src/app/pages/Single${pascalCpt}Page.tsx
@@ -1195,15 +1911,15 @@ export default Single${pascalCpt}Page;
1195
1911
  * To force reset this page back to boilerplate defaults, run:
1196
1912
  * 'pnpm forgewp sync:routes --force'
1197
1913
  */
1198
- import { useRoute } from "wouter";
1199
1914
  import {
1915
+ useRoute,
1200
1916
  WpHead,
1201
1917
  WpLink,
1202
1918
  useWpQuery,
1203
1919
  useWpTitle,
1204
1920
  useWpContent,
1205
1921
  useWpFeaturedImage
1206
- } from "../../.forgewp/wordpress";
1922
+ } from "@forgewp/react";
1207
1923
  import { ArrowLeft } from "lucide-react";
1208
1924
 
1209
1925
  export function Single${pascalCpt}Page() {
@@ -1286,11 +2002,15 @@ export function Single${pascalCpt}Page() {
1286
2002
  `;
1287
2003
 
1288
2004
  if (existsSync(cptPagePath) && !isForce) {
1289
- console.log(` ${pc.gray('ℹ️ [Skip] CPT Page Component already exists:')} src/app/pages/Single${pascalCpt}Page.tsx`);
2005
+ console.log(
2006
+ ` ${pc.gray('ℹ️ [Skip] CPT Page Component already exists:')} src/app/pages/Single${pascalCpt}Page.tsx`,
2007
+ );
1290
2008
  cptSkippedCount++;
1291
2009
  } else {
1292
2010
  writeFileSync(cptPagePath, cptPageContent, 'utf8');
1293
- console.log(` ${pc.green('✅ Scaffolded CPT Page Component')}: src/app/pages/Single${pascalCpt}Page.tsx`);
2011
+ console.log(
2012
+ ` ${pc.green('✅ Scaffolded CPT Page Component')}: src/app/pages/Single${pascalCpt}Page.tsx`,
2013
+ );
1294
2014
  cptScaffoldedCount++;
1295
2015
  }
1296
2016
  }
@@ -1303,9 +2023,13 @@ export function Single${pascalCpt}Page() {
1303
2023
  for (const route of routesToScaffold) {
1304
2024
  const componentName = toPascalCase(route.title);
1305
2025
 
1306
- const importRegex = new RegExp(`import\\s+\\{\\s*${componentName}\\s*\\}\\s+from\\s+["']\\./pages/${componentName}["']`);
2026
+ const importRegex = new RegExp(
2027
+ `import\\s+\\{\\s*${componentName}\\s*\\}\\s+from\\s+["']\\./pages/${componentName}["']`,
2028
+ );
1307
2029
  if (!importRegex.test(routesContent)) {
1308
- const defaultExportIndex = routesContent.indexOf('export default function');
2030
+ const defaultExportIndex = routesContent.indexOf(
2031
+ 'export default function',
2032
+ );
1309
2033
  if (defaultExportIndex !== -1) {
1310
2034
  routesContent =
1311
2035
  routesContent.slice(0, defaultExportIndex) +
@@ -1317,12 +2041,17 @@ export function Single${pascalCpt}Page() {
1317
2041
 
1318
2042
  const routeRegex = new RegExp(`path\\s*=\\s*["']${route.path}["']`);
1319
2043
  if (!routeRegex.test(routesContent)) {
2044
+ const hasWithLayout = routesContent.includes('withLayout');
2045
+ const compTarget = hasWithLayout
2046
+ ? `withLayout(${componentName})`
2047
+ : componentName;
2048
+
1320
2049
  const fallbackMarker = '{/* Fallback route */}';
1321
2050
  const fallbackIndex = routesContent.indexOf(fallbackMarker);
1322
2051
  if (fallbackIndex !== -1) {
1323
2052
  routesContent =
1324
2053
  routesContent.slice(0, fallbackIndex) +
1325
- `<Route path="${route.path}" component={${componentName}} />\n\n ` +
2054
+ `<Route path="${route.path}" component={${compTarget}} />\n\n ` +
1326
2055
  routesContent.slice(fallbackIndex);
1327
2056
  modified = true;
1328
2057
  } else {
@@ -1330,7 +2059,7 @@ export function Single${pascalCpt}Page() {
1330
2059
  if (switchCloseIndex !== -1) {
1331
2060
  routesContent =
1332
2061
  routesContent.slice(0, switchCloseIndex) +
1333
- ` <Route path="${route.path}" component={${componentName}} />\n ` +
2062
+ ` <Route path="${route.path}" component={${compTarget}} />\n ` +
1334
2063
  routesContent.slice(switchCloseIndex);
1335
2064
  modified = true;
1336
2065
  }
@@ -1343,9 +2072,13 @@ export function Single${pascalCpt}Page() {
1343
2072
  const pascalCpt = cpt.charAt(0).toUpperCase() + cpt.slice(1);
1344
2073
  const componentName = `Single${pascalCpt}Page`;
1345
2074
 
1346
- const importRegex = new RegExp(`import\\s+\\{\\s*${componentName}\\s*\\}\\s+from\\s+["']\\./pages/${componentName}["']`);
2075
+ const importRegex = new RegExp(
2076
+ `import\\s+\\{\\s*${componentName}\\s*\\}\\s+from\\s+["']\\./pages/${componentName}["']`,
2077
+ );
1347
2078
  if (!importRegex.test(routesContent)) {
1348
- const defaultExportIndex = routesContent.indexOf('export default function');
2079
+ const defaultExportIndex = routesContent.indexOf(
2080
+ 'export default function',
2081
+ );
1349
2082
  if (defaultExportIndex !== -1) {
1350
2083
  routesContent =
1351
2084
  routesContent.slice(0, defaultExportIndex) +
@@ -1357,12 +2090,17 @@ export function Single${pascalCpt}Page() {
1357
2090
 
1358
2091
  const routeRegex = new RegExp(`path\\s*=\\s*["']/${cpt}/:id["']`);
1359
2092
  if (!routeRegex.test(routesContent)) {
2093
+ const hasWithLayout = routesContent.includes('withLayout');
2094
+ const compTarget = hasWithLayout
2095
+ ? `withLayout(${componentName})`
2096
+ : componentName;
2097
+
1360
2098
  const fallbackMarker = '{/* Fallback route */}';
1361
2099
  const fallbackIndex = routesContent.indexOf(fallbackMarker);
1362
2100
  if (fallbackIndex !== -1) {
1363
2101
  routesContent =
1364
2102
  routesContent.slice(0, fallbackIndex) +
1365
- `<Route path="/${cpt}/:id" component={${componentName}} />\n\n ` +
2103
+ `<Route path="/${cpt}/:id" component={${compTarget}} />\n\n ` +
1366
2104
  routesContent.slice(fallbackIndex);
1367
2105
  modified = true;
1368
2106
  } else {
@@ -1370,7 +2108,7 @@ export function Single${pascalCpt}Page() {
1370
2108
  if (switchCloseIndex !== -1) {
1371
2109
  routesContent =
1372
2110
  routesContent.slice(0, switchCloseIndex) +
1373
- ` <Route path="/${cpt}/:id" component={${componentName}} />\n ` +
2111
+ ` <Route path="/${cpt}/:id" component={${compTarget}} />\n ` +
1374
2112
  routesContent.slice(switchCloseIndex);
1375
2113
  modified = true;
1376
2114
  }
@@ -1380,16 +2118,26 @@ export function Single${pascalCpt}Page() {
1380
2118
 
1381
2119
  if (modified) {
1382
2120
  writeFileSync(routesFilePath, routesContent, 'utf8');
1383
- console.log(` ${pc.green('✅ Synced routing paths in')}: src/app/routes.tsx`);
2121
+ console.log(
2122
+ ` ${pc.green('✅ Synced routing paths in')}: src/app/routes.tsx`,
2123
+ );
1384
2124
  } else {
1385
- console.log(` ${pc.gray('ℹ️ Routes are already fully up to date in')}: src/app/routes.tsx`);
2125
+ console.log(
2126
+ ` ${pc.gray('ℹ️ Routes are already fully up to date in')}: src/app/routes.tsx`,
2127
+ );
1386
2128
  }
1387
2129
  } else {
1388
- console.log(pc.yellow(` ⚠️ Warning: routes.tsx not found. Skipped route linking.`));
2130
+ console.log(
2131
+ pc.yellow(` ⚠️ Warning: routes.tsx not found. Skipped route linking.`),
2132
+ );
1389
2133
  }
1390
2134
 
1391
2135
  console.log('\n' + '─'.repeat(60));
1392
- console.log(pc.green(`\n🎉 ${pc.bold('SITEMAP SYNC COMPLETE:')} Generated ${scaffoldedCount} sitemap pages, ${cptScaffoldedCount} custom post-type templates (skipped ${skippedCount} pages, ${cptSkippedCount} templates).\n`));
2136
+ console.log(
2137
+ pc.green(
2138
+ `\n🎉 ${pc.bold('SITEMAP SYNC COMPLETE:')} Generated ${scaffoldedCount} sitemap pages, ${cptScaffoldedCount} custom post-type templates (skipped ${skippedCount} pages, ${cptSkippedCount} templates).\n`,
2139
+ ),
2140
+ );
1393
2141
  }
1394
2142
 
1395
2143
  export { scanForHydrationIslands, findComponentPath, getHydrationRollupInputs };