@forgewp/compiler 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +70 -3
  2. package/bin/add.js +30 -15
  3. package/bin/analyze.js +66 -1
  4. package/bin/cli.js +149 -70
  5. package/bin/doctor.js +21 -12
  6. package/bin/export.js +69 -20
  7. package/bin/fresh.js +6 -1
  8. package/bin/i18n-extract.js +3 -10
  9. package/bin/i18n-translate.js +15 -24
  10. package/bin/make-block.js +24 -0
  11. package/bin/make-editable.js +166 -0
  12. package/bin/make-form.js +131 -0
  13. package/bin/make-island.js +11 -0
  14. package/bin/make-loop.js +147 -0
  15. package/bin/make-mail.js +27 -0
  16. package/bin/make-page.js +83 -0
  17. package/bin/make-post-type.js +68 -29
  18. package/bin/make-sandbox.js +609 -0
  19. package/bin/make-section.js +221 -0
  20. package/bin/make-shell.js +375 -0
  21. package/bin/repair.js +14 -26
  22. package/bin/seed.js +119 -0
  23. package/bin/sync-routes.js +107 -85
  24. package/lib/adapters/html-adapter.js +13 -3
  25. package/lib/adapters/stub-adapter.js +10 -2
  26. package/lib/add-component.js +153 -92
  27. package/lib/asset-loader.js +333 -1
  28. package/lib/assets/asset-graph.js +432 -0
  29. package/lib/assets/asset-pipeline.js +125 -0
  30. package/lib/assets/diagnostics-report.js +345 -0
  31. package/lib/assets/external-fetcher.js +173 -0
  32. package/lib/assets/font-orchestrator.js +348 -0
  33. package/lib/assets/font-usage-scanner.js +242 -0
  34. package/lib/assets/image-optimizer.js +229 -0
  35. package/lib/assets/index.js +51 -0
  36. package/lib/assets/preload-generator.js +70 -0
  37. package/lib/assets/public-url.js +153 -0
  38. package/lib/block-authoring-help.js +11 -0
  39. package/lib/blocks/ast-parser.js +67 -0
  40. package/lib/blocks/discover-blocks.js +146 -0
  41. package/lib/blocks/editor-scope.js +733 -0
  42. package/lib/blocks/editor-transpiler.js +1229 -0
  43. package/lib/blocks/index.js +2838 -0
  44. package/lib/blocks/php-transpiler.js +4928 -0
  45. package/lib/blocks/scanner.js +1487 -0
  46. package/lib/blocks/shared-utils.js +290 -0
  47. package/lib/blocks/source-sanitize.js +1449 -0
  48. package/lib/blueprints.js +77 -5
  49. package/lib/build-assets.js +38 -33
  50. package/lib/collect-page-template-routes.js +102 -0
  51. package/lib/collect-static-routes.js +175 -0
  52. package/lib/diagnostics.js +58 -33
  53. package/lib/export-theme.js +84 -5
  54. package/lib/extract-template-content.js +90 -0
  55. package/lib/forms-preview.js +42 -0
  56. package/lib/functions/cpt-routing.js +69 -0
  57. package/lib/functions/forms.js +2461 -0
  58. package/lib/functions/hydration-enqueuer.js +400 -0
  59. package/lib/functions/index.js +1623 -0
  60. package/lib/functions/load-menus.js +112 -0
  61. package/lib/functions/load-translations.js +148 -0
  62. package/lib/functions/rest-endpoints.js +2923 -0
  63. package/lib/functions/routing.js +765 -0
  64. package/lib/functions/seed-mock-data.js +392 -0
  65. package/lib/functions/seed-products.js +481 -0
  66. package/lib/functions/settings-page.js +273 -0
  67. package/lib/functions/theme-setup.js +494 -0
  68. package/lib/generate-theme.js +2076 -303
  69. package/lib/hydration/editable-schemas.js +332 -0
  70. package/lib/hydration/enter-hidden-initial.js +65 -0
  71. package/lib/hydration/form-schemas.js +227 -0
  72. package/lib/hydration/index.js +12 -0
  73. package/lib/hydration/is-interactive.js +951 -0
  74. package/lib/hydration/island-split.js +1231 -0
  75. package/lib/hydration/islands-scanner.js +599 -0
  76. package/lib/hydration/resolve-island-chunk.js +103 -0
  77. package/lib/hydration/resolve-island-component.js +52 -0
  78. package/lib/hydration/rollup-inputs.js +81 -0
  79. package/lib/hydration/root-class-extractor.js +220 -0
  80. package/lib/hydration/scan-app-providers.js +154 -0
  81. package/lib/hydration/static-lint.js +382 -0
  82. package/lib/hydration/transform.js +257 -0
  83. package/lib/hydration/uses-block-area.js +49 -0
  84. package/lib/hydration/utils.js +119 -0
  85. package/lib/i18n/translation-cache.js +141 -0
  86. package/lib/icon-registry.js +72 -0
  87. package/lib/index.d.ts +324 -8
  88. package/lib/index.js +3 -2
  89. package/lib/load-config.js +338 -144
  90. package/lib/mail-templates.js +37 -0
  91. package/lib/markup-processor.js +483 -92
  92. package/lib/node-runtime.js +7 -0
  93. package/lib/page-config-plugin.js +84 -0
  94. package/lib/php-builders.js +383 -42
  95. package/lib/react-adapter.js +1053 -246
  96. package/lib/registration-metadata.js +11 -0
  97. package/lib/render-theme.mts +1410 -543
  98. package/lib/route-layout.js +76 -0
  99. package/lib/template-discovery.js +58 -0
  100. package/lib/theme-compatibility.js +32 -0
  101. package/lib/validate-export.js +51 -2
  102. package/lib/validate.js +27 -5
  103. package/lib/virtual-plugin.js +319 -0
  104. package/lib/walkthrough.md +26 -0
  105. package/package.json +17 -5
  106. package/templates/PresetsStyle.tsx +1 -1
  107. package/templates/auth/cms/email-logs.json +9 -0
  108. package/templates/auth/cms/menus.json +11 -0
  109. package/templates/auth/cms/mock-data.json +123 -0
  110. package/templates/auth/cms/roles.json +7 -0
  111. package/templates/auth/cms/sessions.json +1 -0
  112. package/templates/auth/cms/site-settings.json +28 -0
  113. package/templates/auth/cms/translations.json +4 -0
  114. package/templates/auth/cms/users.json +46 -0
  115. package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
  116. package/templates/auth/components/forgot-password-form-wrapper.tsx +141 -0
  117. package/templates/auth/components/login-form-wrapper.tsx +300 -0
  118. package/templates/auth/components/reset-password-form-wrapper.tsx +190 -0
  119. package/templates/auth/components/signup-form-wrapper.tsx +257 -0
  120. package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
  121. package/templates/auth/pages/DashboardPage.tsx +12 -0
  122. package/templates/auth/pages/ForgotPasswordPage.tsx +11 -0
  123. package/templates/auth/pages/LoginPage.tsx +11 -0
  124. package/templates/auth/pages/ResetPasswordPage.tsx +11 -0
  125. package/templates/auth/pages/SignUpPage.tsx +11 -0
  126. package/templates/auth/pages/VerifyEmailPage.tsx +11 -0
  127. package/templates/auth/ui/button.tsx +57 -0
  128. package/templates/auth/ui/card.tsx +76 -0
  129. package/templates/auth/ui/field.tsx +242 -0
  130. package/templates/auth/ui/input.tsx +22 -0
  131. package/templates/auth/ui/label.tsx +24 -0
  132. package/templates/auth/ui/separator.tsx +31 -0
  133. package/templates/forgewp-config.ts +70 -3
  134. package/templates/menus.json +12 -10
  135. package/templates/mock-data.json +122 -433
  136. package/templates/products.json +5 -0
  137. package/templates/roles.json +7 -0
  138. package/templates/sessions.json +1 -0
  139. package/templates/users.json +38 -0
  140. package/templates/wordpress.tsx +1835 -1297
  141. package/bin/make-template.js +0 -145
  142. package/lib/block-compiler.js +0 -552
  143. package/lib/functions-builder.js +0 -2044
  144. package/lib/hydration-scanner.js +0 -821
@@ -1,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,31 +1109,179 @@ ${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 onMakeTemplate(themeRoot, { pascalCase, postType, customFields, automaticallySeeded, pc }) {
803
- const templatesDir = path.join(themeRoot, 'src', 'templates');
804
- if (!existsSync(templatesDir)) {
805
- mkdirSync(templatesDir, { recursive: true });
1259
+ export function onMakeLoop(
1260
+ themeRoot,
1261
+ { pascalCase, postType, customFields, automaticallySeeded, pc },
1262
+ ) {
1263
+ const loopsDir = path.join(themeRoot, 'src', 'loops');
1264
+ if (!existsSync(loopsDir)) {
1265
+ mkdirSync(loopsDir, { recursive: true });
806
1266
  }
807
1267
 
808
- const targetFile = path.join(templatesDir, `${pascalCase}.tsx`);
1268
+ const targetFile = path.join(loopsDir, `${pascalCase}.tsx`);
809
1269
  if (existsSync(targetFile)) {
810
- console.error(pc.red(`\n❌ Error: Template "${pascalCase}.tsx" already exists at src/templates/\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,12 +1292,12 @@ export function onMakeTemplate(themeRoot, { pascalCase, postType, customFields,
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 templateTemplate = `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
- * ⚡ ForgeWP Custom Post Type Template — "${pascalCase}"
1298
+ * ⚡ ForgeWP Custom Post Type Loop — "${pascalCase}"
835
1299
  *
836
- * This loop template dynamically queries and renders records of the "${postType}" post type.
1300
+ * This loop dynamically queries and renders records of the "${postType}" post type.
837
1301
  * In local development, the post data and custom fields are fetched dynamically from
838
1302
  * your local JSON database file at: \`cms/mock-data.json\`.
839
1303
  */
@@ -844,13 +1308,13 @@ export default function ${pascalCase}() {
844
1308
  {/* Header Banner */}
845
1309
  <div className="mb-12 border border-slate-100 bg-white p-8 shadow-xl shadow-slate-100/50">
846
1310
  <span className="inline-block bg-primary/5 text-primary border border-primary/10 text-xs font-mono font-bold uppercase tracking-wider px-3 py-1 mb-4">
847
- Loop Template
1311
+ Post Loop
848
1312
  </span>
849
1313
  <h1 className="text-4xl md:text-5xl font-black uppercase tracking-tight text-slate-900">
850
1314
  Latest ${postType.charAt(0).toUpperCase() + postType.slice(1)} Feed
851
1315
  </h1>
852
1316
  <p className="text-sm font-mono font-medium text-slate-500 mt-2">
853
- Dynamic Post-Type Template &bull; Querying: "${postType}"
1317
+ Dynamic Post-Type Loop &bull; Querying: "${postType}"
854
1318
  </p>
855
1319
  </div>
856
1320
 
@@ -886,26 +1350,31 @@ export default function ${pascalCase}() {
886
1350
  }
887
1351
  `;
888
1352
 
889
- writeFileSync(targetFile, templateTemplate, 'utf8');
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
- console.log(pc.green(`\n⚡ Loop Template "${pascalCase}" successfully created!`));
897
- console.log(` Location: ${pc.cyan(`src/templates/${pascalCase}.tsx`)}`);
1366
+ console.log(pc.green(`\n⚡ Post Loop "${pascalCase}" successfully created!`));
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 "@/templates/${pascalCase}";`)}\n`);
904
- }
905
-
906
- // Backward compatible proxy forwarding make:component parameters straight to onMakeTemplate
907
- export function onMakeComponent(themeRoot, options) {
908
- return onMakeTemplate(themeRoot, options);
1375
+ console.log(
1376
+ ` ${pc.cyan(`import ${pascalCase} from "@/loops/${pascalCase}";`)}\n`,
1377
+ );
909
1378
  }
910
1379
 
911
1380
  export function onMakeIsland(themeRoot, { pascalCase, pc }) {
@@ -916,88 +1385,344 @@ export function onMakeIsland(themeRoot, { pascalCase, pc }) {
916
1385
 
917
1386
  const targetFile = path.join(componentsDir, `${pascalCase}.tsx`);
918
1387
  if (existsSync(targetFile)) {
919
- 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
+ );
920
1393
  process.exit(1);
921
1394
  }
922
1395
 
923
- const islandTemplate = `import { useState, useEffect } from "react";
1396
+ const islandTemplate = `import { useState } from "react";
924
1397
 
925
1398
  /**
926
1399
  * ⚡ ForgeWP Selective Hydration Island Component — "${pascalCase}"
927
- *
928
- * IMPORTANT FOR INTERACTIVITY:
929
- * This component runs client-side React state hooks (useState, useEffect). To enable
930
- * interactivity on the WordPress frontend, you MUST wrap this component in the `<Hydrate>`
931
- * controller when rendering it in your page layout.
932
- *
933
- * 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:
934
1408
  * import ${pascalCase} from "@/components/${pascalCase}";
935
1409
  * import { Hydrate } from "@forgewp/react";
936
- *
937
- * <Hydrate trigger="visible" preload="near-visible">
1410
+ *
1411
+ * <Hydrate trigger="click">
938
1412
  * <${pascalCase} />
939
1413
  * </Hydrate>
940
1414
  */
941
- export interface ${pascalCase}Props {
942
- label?: string;
1415
+ export interface ${pascalCase}Props {}
1416
+
1417
+ export default function ${pascalCase}(_props: ${pascalCase}Props) {
1418
+ const [value, setValue] = useState(0);
1419
+
1420
+ return (
1421
+ <div>
1422
+ <span>{value}</span>
1423
+ <button onClick={() => setValue((v) => v + 1)}>Update</button>
1424
+ </div>
1425
+ );
943
1426
  }
1427
+ `;
1428
+
1429
+ writeFileSync(targetFile, islandTemplate, 'utf8');
1430
+
1431
+ console.log(
1432
+ pc.green(
1433
+ `\n⚡ Selective Hydration Island "${pascalCase}" successfully created!`,
1434
+ ),
1435
+ );
1436
+ console.log(` Location: ${pc.cyan(`src/components/${pascalCase}.tsx`)}`);
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
+ );
1447
+ }
1448
+
1449
+ export function onMakePage(themeRoot, { pascalCase, pc }) {
1450
+ const pagesDir = path.join(themeRoot, 'src', 'app', 'pages');
1451
+ if (!existsSync(pagesDir)) {
1452
+ mkdirSync(pagesDir, { recursive: true });
1453
+ }
1454
+
1455
+ const targetFile = path.join(pagesDir, `${pascalCase}.tsx`);
1456
+ if (existsSync(targetFile)) {
1457
+ console.error(
1458
+ pc.red(
1459
+ `\n❌ Error: Page Template "${pascalCase}.tsx" already exists at src/app/pages/\n`,
1460
+ ),
1461
+ );
1462
+ process.exit(1);
1463
+ }
944
1464
 
945
- export default function ${pascalCase}({ label = "React State Island (${pascalCase})" }: ${pascalCase}Props) {
946
- const [count, setCount] = useState(0);
947
- const [isHydrated, setIsHydrated] = useState(false);
1465
+ const pageTemplate = `import { WpHead, useWpTitle, useWpExcerpt } from "@forgewp/react";
948
1466
 
949
- useEffect(() => {
950
- setIsHydrated(true);
951
- }, []);
1467
+ export const pageConfig = { layout: "default" };
952
1468
 
1469
+ /**
1470
+ * ⚡ ForgeWP Custom Page Template — "${pascalCase}"
1471
+ *
1472
+ * This file compiles into a standalone WordPress Custom Page Template.
1473
+ * You can select it in the WordPress page editor dropdown as "Template: ${pascalCase}".
1474
+ */
1475
+ export function ${pascalCase}() {
953
1476
  return (
954
- <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">
955
- <div className="flex items-center justify-between gap-4 mb-4 border-b border-slate-100 pb-2">
956
- <span className="block text-sm font-bold uppercase tracking-wider">
957
- {label}
958
- </span>
959
- <span
960
- className={\`text-[10px] font-bold px-2 py-0.5 uppercase tracking-widest border transition-all duration-300 \${
961
- isHydrated
962
- ? "bg-emerald-50 text-emerald-700 border-emerald-200 font-black"
963
- : "bg-amber-50 text-amber-700 border-amber-200 font-black animate-pulse"
964
- }\`}
965
- >
966
- {isHydrated ? "● Hydrated" : "○ Static (SSR)"}
1477
+ <main className="container mx-auto px-6 py-12 font-sans text-slate-900">
1478
+ <WpHead
1479
+ title="${pascalCase}"
1480
+ description="Dynamic WordPress Custom Page Template ${pascalCase} compiled with ForgeWP."
1481
+ />
1482
+
1483
+ {/* Hero Header Area */}
1484
+ <header className="border-b border-slate-100 pb-6 mb-12">
1485
+ <span className="inline-block bg-primary/5 text-primary border border-primary/10 text-xs font-mono font-bold uppercase tracking-wider px-3 py-1 mb-4">
1486
+ Page Template
967
1487
  </span>
1488
+ <h1 className="text-5xl font-black tracking-tight uppercase text-slate-900">
1489
+ {useWpTitle() || "${pascalCase}"}
1490
+ </h1>
1491
+ <p className="text-slate-500 mt-2 text-sm leading-relaxed">
1492
+ {useWpExcerpt() || "Custom page layout designed dynamically."}
1493
+ </p>
1494
+ </header>
1495
+
1496
+ {/* Page Content layout */}
1497
+ <div className="bg-white border border-slate-100 p-8 shadow-lg max-w-none prose prose-slate">
1498
+ <p className="text-slate-600 leading-relaxed">
1499
+ Welcome to your new custom page template! You can design anything here in React, using standard HTML/JSX tags and Tailwind classes.
1500
+ </p>
968
1501
  </div>
969
-
970
- <div className="flex items-center gap-4 mt-2">
971
- <span className="text-2xl font-black text-slate-800">Counter: {count}</span>
1502
+ </main>
1503
+ );
1504
+ }
1505
+ `;
1506
+
1507
+ writeFileSync(targetFile, pageTemplate, 'utf8');
1508
+
1509
+ console.log(
1510
+ pc.green(`\n⚡ Custom Page Template "${pascalCase}" successfully created!`),
1511
+ );
1512
+ console.log(` Location: ${pc.cyan(`src/app/pages/${pascalCase}.tsx`)}`);
1513
+ console.log(` WordPress Template Name: ${pc.yellow(pascalCase)}`);
1514
+ console.log(`\n🎉 To link it in your application routing:`);
1515
+ console.log(` Add it inside your ${pc.cyan('src/app/routes.tsx')} file.\n`);
1516
+ }
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>
972
1671
  <button
973
- onClick={() => setCount((c) => c + 1)}
974
- 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"
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"
975
1674
  >
976
- Increment Value
1675
+ Send another message
977
1676
  </button>
978
1677
  </div>
979
- </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>
980
1699
  );
981
1700
  }
982
1701
  `;
983
1702
 
984
- writeFileSync(targetFile, islandTemplate, 'utf8');
1703
+ writeFileSync(componentFile, componentTemplate, 'utf8');
985
1704
 
986
- console.log(pc.green(`\n⚡ Selective Hydration Island "${pascalCase}" successfully created!`));
987
- console.log(` Location: ${pc.cyan(`src/components/${pascalCase}.tsx`)}`);
988
- console.log(`\n🎉 To render this island with selective hydration triggers:`);
989
- console.log(` Inside any page, wrap it with:`);
990
- console.log(` ${pc.cyan(`<Hydrate trigger="visible" preload="near-visible">\n <${pascalCase} />\n </Hydrate>`)}\n`);
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
+ );
991
1714
  }
992
1715
 
993
1716
  export function onSyncRoutes(themeRoot, { routesToScaffold, isForce, pc }) {
994
1717
  function toPascalCase(str) {
995
- return str
996
- .replace(/[^a-zA-Z0-9]/g, ' ')
997
- .trim()
998
- .split(/\s+/)
999
- .map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
1000
- .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
+ );
1001
1726
  }
1002
1727
 
1003
1728
  const pagesDir = path.join(themeRoot, 'src', 'app', 'pages');
@@ -1021,9 +1746,13 @@ export function onSyncRoutes(themeRoot, { routesToScaffold, isForce, pc }) {
1021
1746
  *
1022
1747
  * To force reset this page back to boilerplate defaults, run:
1023
1748
  * 'pnpm forgewp sync:routes --force'
1749
+ *
1750
+ * This file compiles into a standalone WordPress Custom Page Template.
1751
+ * You can select it in the WordPress page editor dropdown as "Template: ${componentName}".
1024
1752
  */
1025
- import { WpHead } from "../../.forgewp/wordpress";
1026
- 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" };
1027
1756
 
1028
1757
  export function ${componentName}() {
1029
1758
  return (
@@ -1076,33 +1805,77 @@ export function ${componentName}() {
1076
1805
  `;
1077
1806
 
1078
1807
  if (existsSync(componentPath) && !isForce) {
1079
- 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
+ );
1080
1811
  skippedCount++;
1081
1812
  } else {
1082
1813
  writeFileSync(componentPath, componentContent, 'utf8');
1083
- 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
+ );
1084
1817
  scaffoldedCount++;
1085
1818
  }
1086
1819
  }
1087
1820
 
1088
- // Discover Custom Post Types (CPTs) from cms/mock-data.json
1089
- 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');
1090
1823
  let cpts = [];
1091
- if (existsSync(mockDataPath)) {
1092
- try {
1093
- const mockData = JSON.parse(readFileSync(mockDataPath, 'utf8'));
1094
- for (const [key, value] of Object.entries(mockData)) {
1095
- if (
1096
- Array.isArray(value) &&
1097
- !key.startsWith('_') &&
1098
- !['post', 'page', 'menu', 'primary', 'utility'].includes(key)
1099
- ) {
1100
- cpts.push(key);
1101
- }
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 {}
1102
1871
  }
1103
- } catch (e) {
1104
- console.log(pc.yellow(` ⚠️ Warning: Failed to parse cms/mock-data.json for CPT auto-discovery.`));
1105
1872
  }
1873
+ } catch (e) {
1874
+ console.log(
1875
+ pc.yellow(
1876
+ ` ⚠️ Warning: Failed to read cms/ directory for CPT auto-discovery.`,
1877
+ ),
1878
+ );
1106
1879
  }
1107
1880
 
1108
1881
  let cptScaffoldedCount = 0;
@@ -1110,18 +1883,20 @@ export function ${componentName}() {
1110
1883
 
1111
1884
  for (const cpt of cpts) {
1112
1885
  const pascalCpt = cpt.charAt(0).toUpperCase() + cpt.slice(1);
1113
-
1886
+
1114
1887
  // 1. Scaffold thin wrapper src/app/single-${cpt}.tsx
1115
1888
  const wrapperPath = path.join(themeRoot, 'src', 'app', `single-${cpt}.tsx`);
1116
1889
  const wrapperContent = `import { Single${pascalCpt}Page } from "./pages/Single${pascalCpt}Page";
1117
1890
  export default Single${pascalCpt}Page;
1118
1891
  `;
1119
-
1892
+
1120
1893
  if (existsSync(wrapperPath) && !isForce) {
1121
1894
  // Skip wrapper
1122
1895
  } else {
1123
1896
  writeFileSync(wrapperPath, wrapperContent, 'utf8');
1124
- 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
+ );
1125
1900
  }
1126
1901
 
1127
1902
  // 2. Scaffold page component src/app/pages/Single${pascalCpt}Page.tsx
@@ -1136,15 +1911,15 @@ export default Single${pascalCpt}Page;
1136
1911
  * To force reset this page back to boilerplate defaults, run:
1137
1912
  * 'pnpm forgewp sync:routes --force'
1138
1913
  */
1139
- import { useRoute } from "wouter";
1140
1914
  import {
1915
+ useRoute,
1141
1916
  WpHead,
1142
1917
  WpLink,
1143
1918
  useWpQuery,
1144
1919
  useWpTitle,
1145
1920
  useWpContent,
1146
1921
  useWpFeaturedImage
1147
- } from "../../.forgewp/wordpress";
1922
+ } from "@forgewp/react";
1148
1923
  import { ArrowLeft } from "lucide-react";
1149
1924
 
1150
1925
  export function Single${pascalCpt}Page() {
@@ -1154,7 +1929,7 @@ export function Single${pascalCpt}Page() {
1154
1929
  // In production, forgeWpHydration.post.id holds the real WP numeric ID
1155
1930
  const hydrationId =
1156
1931
  typeof window !== 'undefined'
1157
- ? (window as any).forgeWpHydration?.post?.id || 0
1932
+ ? window.forgeWpHydration?.post?.id || 0
1158
1933
  : 0;
1159
1934
  const id = hydrationId || routeParam;
1160
1935
 
@@ -1174,8 +1949,8 @@ export function Single${pascalCpt}Page() {
1174
1949
  useWpContent() || devPost?.content || "<p>Loading details...</p>";
1175
1950
  const rawImage = useWpFeaturedImage();
1176
1951
  const hydrationImage =
1177
- typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime
1178
- ? (window as any).forgeWpHydration?.currentFeaturedImage || ""
1952
+ typeof window !== 'undefined' && !window._forgeWpCompileTime
1953
+ ? window.forgeWpHydration?.currentFeaturedImage || ""
1179
1954
  : "";
1180
1955
  const restImage =
1181
1956
  typeof devPost?.featuredImage === "object" && devPost?.featuredImage !== null
@@ -1227,11 +2002,15 @@ export function Single${pascalCpt}Page() {
1227
2002
  `;
1228
2003
 
1229
2004
  if (existsSync(cptPagePath) && !isForce) {
1230
- 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
+ );
1231
2008
  cptSkippedCount++;
1232
2009
  } else {
1233
2010
  writeFileSync(cptPagePath, cptPageContent, 'utf8');
1234
- 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
+ );
1235
2014
  cptScaffoldedCount++;
1236
2015
  }
1237
2016
  }
@@ -1244,9 +2023,13 @@ export function Single${pascalCpt}Page() {
1244
2023
  for (const route of routesToScaffold) {
1245
2024
  const componentName = toPascalCase(route.title);
1246
2025
 
1247
- 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
+ );
1248
2029
  if (!importRegex.test(routesContent)) {
1249
- const defaultExportIndex = routesContent.indexOf('export default function');
2030
+ const defaultExportIndex = routesContent.indexOf(
2031
+ 'export default function',
2032
+ );
1250
2033
  if (defaultExportIndex !== -1) {
1251
2034
  routesContent =
1252
2035
  routesContent.slice(0, defaultExportIndex) +
@@ -1258,12 +2041,17 @@ export function Single${pascalCpt}Page() {
1258
2041
 
1259
2042
  const routeRegex = new RegExp(`path\\s*=\\s*["']${route.path}["']`);
1260
2043
  if (!routeRegex.test(routesContent)) {
2044
+ const hasWithLayout = routesContent.includes('withLayout');
2045
+ const compTarget = hasWithLayout
2046
+ ? `withLayout(${componentName})`
2047
+ : componentName;
2048
+
1261
2049
  const fallbackMarker = '{/* Fallback route */}';
1262
2050
  const fallbackIndex = routesContent.indexOf(fallbackMarker);
1263
2051
  if (fallbackIndex !== -1) {
1264
2052
  routesContent =
1265
2053
  routesContent.slice(0, fallbackIndex) +
1266
- `<Route path="${route.path}" component={${componentName}} />\n\n ` +
2054
+ `<Route path="${route.path}" component={${compTarget}} />\n\n ` +
1267
2055
  routesContent.slice(fallbackIndex);
1268
2056
  modified = true;
1269
2057
  } else {
@@ -1271,7 +2059,7 @@ export function Single${pascalCpt}Page() {
1271
2059
  if (switchCloseIndex !== -1) {
1272
2060
  routesContent =
1273
2061
  routesContent.slice(0, switchCloseIndex) +
1274
- ` <Route path="${route.path}" component={${componentName}} />\n ` +
2062
+ ` <Route path="${route.path}" component={${compTarget}} />\n ` +
1275
2063
  routesContent.slice(switchCloseIndex);
1276
2064
  modified = true;
1277
2065
  }
@@ -1284,9 +2072,13 @@ export function Single${pascalCpt}Page() {
1284
2072
  const pascalCpt = cpt.charAt(0).toUpperCase() + cpt.slice(1);
1285
2073
  const componentName = `Single${pascalCpt}Page`;
1286
2074
 
1287
- 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
+ );
1288
2078
  if (!importRegex.test(routesContent)) {
1289
- const defaultExportIndex = routesContent.indexOf('export default function');
2079
+ const defaultExportIndex = routesContent.indexOf(
2080
+ 'export default function',
2081
+ );
1290
2082
  if (defaultExportIndex !== -1) {
1291
2083
  routesContent =
1292
2084
  routesContent.slice(0, defaultExportIndex) +
@@ -1298,12 +2090,17 @@ export function Single${pascalCpt}Page() {
1298
2090
 
1299
2091
  const routeRegex = new RegExp(`path\\s*=\\s*["']/${cpt}/:id["']`);
1300
2092
  if (!routeRegex.test(routesContent)) {
2093
+ const hasWithLayout = routesContent.includes('withLayout');
2094
+ const compTarget = hasWithLayout
2095
+ ? `withLayout(${componentName})`
2096
+ : componentName;
2097
+
1301
2098
  const fallbackMarker = '{/* Fallback route */}';
1302
2099
  const fallbackIndex = routesContent.indexOf(fallbackMarker);
1303
2100
  if (fallbackIndex !== -1) {
1304
2101
  routesContent =
1305
2102
  routesContent.slice(0, fallbackIndex) +
1306
- `<Route path="/${cpt}/:id" component={${componentName}} />\n\n ` +
2103
+ `<Route path="/${cpt}/:id" component={${compTarget}} />\n\n ` +
1307
2104
  routesContent.slice(fallbackIndex);
1308
2105
  modified = true;
1309
2106
  } else {
@@ -1311,7 +2108,7 @@ export function Single${pascalCpt}Page() {
1311
2108
  if (switchCloseIndex !== -1) {
1312
2109
  routesContent =
1313
2110
  routesContent.slice(0, switchCloseIndex) +
1314
- ` <Route path="/${cpt}/:id" component={${componentName}} />\n ` +
2111
+ ` <Route path="/${cpt}/:id" component={${compTarget}} />\n ` +
1315
2112
  routesContent.slice(switchCloseIndex);
1316
2113
  modified = true;
1317
2114
  }
@@ -1321,16 +2118,26 @@ export function Single${pascalCpt}Page() {
1321
2118
 
1322
2119
  if (modified) {
1323
2120
  writeFileSync(routesFilePath, routesContent, 'utf8');
1324
- 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
+ );
1325
2124
  } else {
1326
- 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
+ );
1327
2128
  }
1328
2129
  } else {
1329
- 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
+ );
1330
2133
  }
1331
2134
 
1332
2135
  console.log('\n' + '─'.repeat(60));
1333
- 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
+ );
1334
2141
  }
1335
2142
 
1336
2143
  export { scanForHydrationIslands, findComponentPath, getHydrationRollupInputs };