@forgewp/compiler 0.3.0 → 0.4.2

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 (52) hide show
  1. package/README.md +24 -5
  2. package/bin/analyze.js +158 -0
  3. package/bin/cli.js +33 -4
  4. package/bin/doctor.js +125 -11
  5. package/bin/export.js +20 -0
  6. package/bin/fresh.js +32 -343
  7. package/bin/i18n-extract.js +121 -0
  8. package/bin/i18n-translate.js +112 -0
  9. package/bin/make-block.js +27 -60
  10. package/bin/make-island.js +72 -0
  11. package/bin/make-post-type.js +6 -6
  12. package/bin/make-template.js +145 -0
  13. package/bin/repair.js +2 -2
  14. package/bin/sync-hooks.js +221 -0
  15. package/bin/sync-routes.js +28 -158
  16. package/define-config.d.ts +1 -0
  17. package/define-config.js +1 -0
  18. package/lib/adapters/html-adapter.js +65 -0
  19. package/lib/adapters/stub-adapter.js +49 -0
  20. package/lib/add-component.js +282 -183
  21. package/lib/asset-loader.js +27 -0
  22. package/lib/block-compiler.js +552 -0
  23. package/lib/blueprints.js +15 -501
  24. package/lib/define-config.d.ts +3 -0
  25. package/lib/define-config.js +8 -0
  26. package/lib/diagnostics.js +798 -0
  27. package/lib/export-theme.js +81 -18
  28. package/lib/framework-adapter.js +34 -0
  29. package/lib/functions-builder.js +2044 -0
  30. package/lib/generate-theme.js +1140 -1352
  31. package/lib/hydration-scanner.js +663 -21
  32. package/lib/i18n/extractor.js +60 -0
  33. package/lib/i18n/providers.js +165 -0
  34. package/lib/index.d.ts +115 -3
  35. package/lib/index.js +19 -5
  36. package/lib/load-config.js +122 -6
  37. package/lib/markup-processor.js +589 -0
  38. package/lib/php-builders.js +381 -0
  39. package/lib/react-adapter.js +1336 -0
  40. package/lib/render-static.js +9 -82
  41. package/lib/render-theme.mts +543 -232
  42. package/lib/screenshot-fallback.png +0 -0
  43. package/lib/types.js +1 -0
  44. package/lib/validate-export.js +183 -0
  45. package/package.json +15 -3
  46. package/templates/PresetsStyle.tsx +74 -0
  47. package/templates/SEO.tsx +109 -0
  48. package/templates/forgewp-config.ts +43 -0
  49. package/templates/menus.json +11 -0
  50. package/templates/mock-data.json +434 -0
  51. package/templates/wordpress.tsx +1297 -0
  52. package/bin/make-component.js +0 -200
@@ -0,0 +1,1336 @@
1
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { createRequire } from 'node:module';
6
+ import pc from 'picocolors';
7
+ import {
8
+ scanForHydrationIslands,
9
+ findComponentPath,
10
+ getHydrationRollupInputs,
11
+ } from './hydration-scanner.js';
12
+
13
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
+ const require = createRequire(import.meta.url);
15
+
16
+ /**
17
+ * Server-render the theme App to static HTML.
18
+ * @param {string} themeRoot
19
+ */
20
+ export async function renderStaticMarkup(themeRoot) {
21
+ const renderScript = path.join(__dirname, 'render-theme.mts');
22
+ const tsconfig = path.join(themeRoot, 'tsconfig.json');
23
+
24
+ let tsxCli = 'tsx';
25
+ try {
26
+ tsxCli = require.resolve('tsx/cli');
27
+ } catch {
28
+ // fallback to PATH
29
+ }
30
+
31
+ const args = [tsxCli];
32
+ if (existsSync(tsconfig)) {
33
+ args.push('--tsconfig', tsconfig);
34
+ }
35
+ args.push(renderScript, themeRoot);
36
+
37
+ const result = spawnSync(process.execPath, args, {
38
+ cwd: themeRoot,
39
+ env: {
40
+ ...process.env,
41
+ INIT_CWD: themeRoot,
42
+ },
43
+ encoding: 'utf8',
44
+ shell: false,
45
+ });
46
+
47
+ if (result.status !== 0) {
48
+ const detail =
49
+ result.stderr?.trim() || result.stdout?.trim() || 'Unknown error';
50
+ throw new Error(`Static render failed:\n${detail}`);
51
+ }
52
+
53
+ if (result.stderr) {
54
+ console.warn(result.stderr);
55
+ }
56
+
57
+ const outDir = result.stdout?.trim() || path.join(themeRoot, '.forgewp');
58
+ const appHtmlPath = path.join(outDir, 'app.html');
59
+
60
+ if (!existsSync(appHtmlPath)) {
61
+ throw new Error(`Render output not found: ${appHtmlPath}`);
62
+ }
63
+
64
+ const headerHtmlPath = path.join(outDir, 'header.html');
65
+ const footerHtmlPath = path.join(outDir, 'footer.html');
66
+ const headHtmlPath = path.join(outDir, 'head.html');
67
+ const singleHtmlPath = path.join(outDir, 'single.html');
68
+ const singleHeadHtmlPath = path.join(outDir, 'single-head.html');
69
+ const notFoundHtmlPath = path.join(outDir, '404.html');
70
+ const archiveHtmlPath = path.join(outDir, 'archive.html');
71
+
72
+ return {
73
+ appHtml: readFileSync(appHtmlPath, 'utf8'),
74
+ headerHtml: existsSync(headerHtmlPath)
75
+ ? readFileSync(headerHtmlPath, 'utf8')
76
+ : '',
77
+ footerHtml: existsSync(footerHtmlPath)
78
+ ? readFileSync(footerHtmlPath, 'utf8')
79
+ : '',
80
+ headHtml: existsSync(headHtmlPath)
81
+ ? readFileSync(headHtmlPath, 'utf8')
82
+ : '',
83
+ singleHtml: existsSync(singleHtmlPath)
84
+ ? readFileSync(singleHtmlPath, 'utf8')
85
+ : '',
86
+ singleHeadHtml: existsSync(singleHeadHtmlPath)
87
+ ? readFileSync(singleHeadHtmlPath, 'utf8')
88
+ : '',
89
+ notFoundHtml: existsSync(notFoundHtmlPath)
90
+ ? readFileSync(notFoundHtmlPath, 'utf8')
91
+ : '',
92
+ archiveHtml: existsSync(archiveHtmlPath)
93
+ ? readFileSync(archiveHtmlPath, 'utf8')
94
+ : '',
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Generate the hydration runtime loader and manifest mappings for React hydration islands.
100
+ * @param {string} themeRoot
101
+ * @param {string} assetsOut
102
+ * @param {string} distAssets
103
+ * @param {string[]} hydrationIslands
104
+ * @returns {string}
105
+ */
106
+ export function generateHydrationRuntime(
107
+ themeRoot,
108
+ assetsOut,
109
+ distAssets,
110
+ hydrationIslands,
111
+ ) {
112
+ const manifestPath = path.join(themeRoot, 'dist', '.vite', 'manifest.json');
113
+ let viteManifest = {};
114
+ if (existsSync(manifestPath)) {
115
+ try {
116
+ viteManifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
117
+ } catch (e) {
118
+ console.warn('Failed to parse Vite manifest.json:', e.message);
119
+ }
120
+ } else {
121
+ console.warn(
122
+ 'Hydration manifest not found at dist/.vite/manifest.json. Hydration asset generation may be incomplete.',
123
+ );
124
+ }
125
+
126
+ const mapping = {};
127
+ let mainJsFile = '';
128
+ const entryChunk =
129
+ viteManifest['index.html'] ||
130
+ Object.values(viteManifest).find((c) => c.isEntry);
131
+ if (entryChunk) {
132
+ mainJsFile = entryChunk.file;
133
+ }
134
+
135
+ 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
+
158
+ if (resolvedChunk) {
159
+ mapping[island] = resolvedChunk;
160
+ }
161
+ }
162
+
163
+ if (!mainJsFile) {
164
+ throw new Error(
165
+ `\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`
168
+ );
169
+ }
170
+
171
+ const missingIslands = hydrationIslands.filter(
172
+ (island) => !(island in mapping),
173
+ );
174
+ 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(', ');
178
+ throw new Error(
179
+ `\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`
185
+ );
186
+ }
187
+
188
+ const hydratorScript = `(function () {
189
+ const config = window.forgeWpHydration || { themeUri: "", manifest: {} };
190
+ const islands = document.querySelectorAll("[data-forgewp-hydrate]");
191
+
192
+ const observer = new IntersectionObserver((entries) => {
193
+ entries.forEach((entry) => {
194
+ if (entry.isIntersecting) {
195
+ const hydrate = entry.target.__forgewpHydrate;
196
+ if (typeof hydrate === "function") hydrate();
197
+ observer.unobserve(entry.target);
198
+ }
199
+ });
200
+ }, { rootMargin: "200px" });
201
+
202
+ // Predictive preloading observer with larger viewport margin (600px)
203
+ const preloadObserver = new IntersectionObserver((entries) => {
204
+ entries.forEach((entry) => {
205
+ if (entry.isIntersecting) {
206
+ const el = entry.target;
207
+ preloadElement(el);
208
+ preloadObserver.unobserve(el);
209
+ }
210
+ });
211
+ }, { rootMargin: "600px" });
212
+
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
+ const StrategyRegistry = {
228
+ load: (el, hydrate) => {
229
+ if (document.readyState === "complete") {
230
+ hydrate();
231
+ } else {
232
+ window.addEventListener("load", hydrate);
233
+ }
234
+ },
235
+ 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)) {
239
+ hydrate();
240
+ return;
241
+ }
242
+ el.__forgewpHydrate = hydrate;
243
+ observer.observe(el);
244
+ },
245
+ interaction: (el, hydrate) => {
246
+ const run = () => {
247
+ hydrate();
248
+ el.removeEventListener("click", run);
249
+ el.removeEventListener("mouseenter", run);
250
+ el.removeEventListener("focusin", run);
251
+ };
252
+ el.addEventListener("click", run);
253
+ el.addEventListener("mouseenter", run);
254
+ el.addEventListener("focusin", run);
255
+ },
256
+ click: (el, hydrate) => {
257
+ const run = () => {
258
+ hydrate();
259
+ el.removeEventListener("click", run);
260
+ };
261
+ el.addEventListener("click", run);
262
+ },
263
+ hover: (el, hydrate) => {
264
+ const run = () => {
265
+ hydrate();
266
+ el.removeEventListener("mouseenter", run);
267
+ };
268
+ el.addEventListener("mouseenter", run);
269
+ },
270
+ idle: (el, hydrate) => {
271
+ if ("requestIdleCallback" in window) {
272
+ window.requestIdleCallback(hydrate);
273
+ } else {
274
+ setTimeout(hydrate, 200);
275
+ }
276
+ }
277
+ };
278
+
279
+ islands.forEach((el) => {
280
+ const islandName = el.getAttribute("data-forgewp-hydrate");
281
+
282
+ // 1. Network-Aware Check: Restrict/skip hydration on slow 2G/3G connections if requested
283
+ const connection = el.getAttribute("data-forgewp-connection");
284
+ if (connection === "fast") {
285
+ const conn = navigator.connection;
286
+ if (conn && (conn.saveData || /2g|3g/.test(conn.effectiveType))) {
287
+ console.warn("[ForgeWP Hydrator] Deferring hydration of island '" + islandName + "' due to slow 2G/3G network conditions.");
288
+ return;
289
+ }
290
+ }
291
+
292
+ // 2. Predictive Preloading Setup
293
+ const preload = el.getAttribute("data-forgewp-preload");
294
+ if (preload === "near-visible") {
295
+ preloadObserver.observe(el);
296
+ }
297
+
298
+ const runHydration = () => hydrateElement(el);
299
+
300
+ // 3. Media-Query Check: Gated by target device dimensions
301
+ const media = el.getAttribute("data-forgewp-media");
302
+ if (media) {
303
+ const mql = window.matchMedia(media);
304
+ const setupMediaHydration = () => {
305
+ const trigger = el.getAttribute("data-forgewp-trigger") || "visible";
306
+ const strategy = StrategyRegistry[trigger];
307
+ if (strategy) {
308
+ strategy(el, runHydration);
309
+ } else {
310
+ StrategyRegistry.visible(el, runHydration);
311
+ }
312
+ };
313
+
314
+ if (mql.matches) {
315
+ setupMediaHydration();
316
+ } else {
317
+ const listener = (e) => {
318
+ if (e.matches) {
319
+ setupMediaHydration();
320
+ mql.removeEventListener("change", listener);
321
+ }
322
+ };
323
+ mql.addEventListener("change", listener);
324
+ }
325
+ return;
326
+ }
327
+
328
+ // Standard trigger registration
329
+ const trigger = el.getAttribute("data-forgewp-trigger") || "visible";
330
+ const strategy = StrategyRegistry[trigger];
331
+ if (strategy) {
332
+ strategy(el, runHydration);
333
+ } else {
334
+ StrategyRegistry.visible(el, runHydration);
335
+ }
336
+ });
337
+
338
+ function preloadElement(el) {
339
+ const islandName = el.getAttribute("data-forgewp-hydrate");
340
+ const chunkPath = config.manifest?.[islandName];
341
+ if (!chunkPath) return;
342
+ const scriptUrl = config.themeUri + "/assets/" + chunkPath.replace("assets/", "").replace("assets\\\\", "");
343
+
344
+ // Inject link[rel=modulepreload]
345
+ if (document.querySelector("link[href='" + scriptUrl + "']")) return;
346
+ const link = document.createElement("link");
347
+ link.rel = "modulepreload";
348
+ link.href = scriptUrl;
349
+ document.head.appendChild(link);
350
+ }
351
+
352
+ function hydrateElement(el) {
353
+ const islandName = el.getAttribute("data-forgewp-hydrate");
354
+ if (!islandName) {
355
+ console.error("[ForgeWP Hydrator] Missing data-forgewp-hydrate attribute on hydration boundary.");
356
+ return;
357
+ }
358
+
359
+ const rawProps = el.getAttribute("data-forgewp-props") || "{}";
360
+ let props = {};
361
+ try {
362
+ props = JSON.parse(rawProps);
363
+ } catch (err) {
364
+ console.error("[ForgeWP Hydrator] Failed to parse props for island " + islandName + ":", err);
365
+ }
366
+
367
+ const chunkPath = config.manifest?.[islandName];
368
+ if (!chunkPath) {
369
+ const available = config.manifest ? Object.keys(config.manifest).join(", ") : "<none>";
370
+ console.error(
371
+ "[ForgeWP Hydrator] Could not find compiled chunk for island " + islandName + ". " +
372
+ "Available manifest keys: " + available
373
+ );
374
+ return;
375
+ }
376
+
377
+ const scriptUrl = config.themeUri + "/assets/" + chunkPath.replace("assets/", "").replace("assets\\\\", "");
378
+
379
+ import(scriptUrl)
380
+ .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") {
389
+ const exportsList = Object.keys(module).join(", ");
390
+ console.error(
391
+ "[ForgeWP Hydrator] Chunk for " + islandName + " does not export a valid React component. " +
392
+ "Available exports: " + exportsList
393
+ );
394
+ return;
395
+ }
396
+
397
+ // Resolve ReactDOM/React — prefer window globals set by main.tsx.
398
+ // Always use createRoot (not hydrateRoot): island chunks bundle their
399
+ // own React via Vite code-splitting, so hydrateRoot from window.ReactDOM
400
+ // (a different instance) causes a silent Fiber reconciler failure.
401
+ // createRoot takes full ownership of the container, bypassing this issue.
402
+ const ReactDOM = window.ReactDOM;
403
+ const React = window.React;
404
+
405
+ if (ReactDOM && React) {
406
+ const root = ReactDOM.createRoot(el);
407
+ root.render(React.createElement(Component, props));
408
+ } else {
409
+ console.error("[ForgeWP Hydration Error] React or ReactDOM not found on window. Ensure main.tsx exposes window.React and window.ReactDOM.");
410
+ }
411
+ })
412
+ .catch((err) => {
413
+ console.error("[ForgeWP Hydrator] Failed to load chunk for " + islandName + ":", err);
414
+ });
415
+ }
416
+ })();`;
417
+
418
+ writeFileSync(
419
+ path.join(assetsOut, 'forgewp-hydrator.js'),
420
+ hydratorScript,
421
+ 'utf8',
422
+ );
423
+ return JSON.stringify({
424
+ mainJsFile,
425
+ mapping,
426
+ });
427
+ }
428
+
429
+ export function getCriticalFiles(themeRoot) {
430
+ return ['src/main.tsx'];
431
+ }
432
+
433
+ export async function onFresh(themeRoot) {
434
+ const routesPath = path.join(themeRoot, 'src', 'app', 'routes.tsx');
435
+ const pagePath = path.join(themeRoot, 'src', 'app', 'page.tsx');
436
+
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";
441
+
442
+ /**
443
+ * Local Developer Routes — ForgeWP.
444
+ *
445
+ * Edit this file to add new routes/components for your local Vite preview server.
446
+ *
447
+ * @example
448
+ * // 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} />
451
+ */
452
+ export default function AppRoutes() {
453
+ return (
454
+ <Switch>
455
+ {/* Home preview */}
456
+ <Route path="/" component={HomePage} />
457
+
458
+ {/* Relational Query Engine Sandbox — verifies taxQuery, metaQuery, pagination */}
459
+ <Route path="/query-sandbox" component={QuerySandbox} />
460
+
461
+ {/* WpEditable Block Canvas Preview — verifies inline editing primitive */}
462
+ <Route path="/wp-editable" component={WpEditablePage} />
463
+
464
+ {/* Fallback route */}
465
+ <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>
473
+ </div>
474
+ </div>
475
+ </Route>
476
+ </Switch>
477
+ );
478
+ }
479
+ `;
480
+
481
+ const pageContent = `import { WpHead } from "../.forgewp/wordpress";
482
+ import { BookOpen, Github, ChevronRight, Database, Code2 } from "lucide-react";
483
+
484
+ export default function HomePage() {
485
+ return (
486
+ <div className="min-h-screen lg:h-screen w-full bg-[#fafafa] selection:bg-primary selection:text-white flex flex-col items-center justify-center p-6 md:p-8 lg:p-12 relative overflow-x-hidden lg:overflow-hidden font-sans">
487
+ <WpHead
488
+ title="ForgeWP — React & Tailwind Compiler for WordPress"
489
+ description="A premium developer framework for creating modern Gutenberg block-themes using React."
490
+ ogType="website"
491
+ />
492
+
493
+ {/* ── BACKGROUND: Glowing Magma Blob ── */}
494
+ <div className="absolute -left-48 -top-48 w-[600px] h-[600px] bg-[radial-gradient(circle,oklch(0.61_0.22_42.5/_0.12)_0%,transparent_70%)] blur-3xl pointer-events-none z-0"></div>
495
+
496
+ {/* ── HEADER: Centered Text Logo ── */}
497
+ <header className="relative w-full flex justify-center pb-4 lg:pb-6 z-10 shrink-0">
498
+ <h1 className="font-heading font-black text-3xl tracking-tight bg-linear-to-r from-primary to-amber-500 bg-clip-text text-transparent select-none">
499
+ ForgeWP
500
+ </h1>
501
+ </header>
502
+
503
+ {/* ── COMPACT CARD CONTAINER wrapping the Two-Column Grid ── */}
504
+ <main className="relative w-full max-w-5xl bg-white border border-slate-100/80 shadow-xl shadow-slate-100/50 p-6 md:p-8 lg:py-8 lg:px-10 lg:min-h-[430px] z-10 rounded-none flex items-center justify-center">
505
+ <div className="grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-16 w-full items-center">
506
+
507
+ {/* Left Layout: Hero Header, Text, and Two CTAs */}
508
+ <div className="lg:col-span-6 flex flex-col justify-center text-left">
509
+ <h2 className="text-3xl md:text-4xl font-heading font-black tracking-tight leading-[1.1] text-slate-900 mb-4 uppercase">
510
+ React Structure.
511
+ <br />
512
+ Tailwind Speed.
513
+ <br />
514
+ WordPress Power.
515
+ </h2>
516
+
517
+ <p className="text-slate-500 text-xs md:text-sm leading-relaxed font-normal max-w-xl mb-6">
518
+ Welcome to ForgeWP. Build your layout dynamically using standard
519
+ React components, mock hooks, and modern utilities. The compiler
520
+ transpiles your isomorphic components directly into
521
+ production-grade, standard classic WordPress block themes
522
+ automatically.
523
+ </p>
524
+
525
+ {/* Two CTAs: Docs and GitHub */}
526
+ <div className="flex flex-wrap gap-4">
527
+ <a
528
+ href="https://forgewp.dev/docs"
529
+ target="_blank"
530
+ rel="noreferrer"
531
+ className="group relative inline-flex items-center justify-center bg-transparent text-primary hover:text-white border border-primary font-mono font-bold text-[10px] uppercase tracking-widest px-6 py-3.5 transition-colors duration-500 rounded-none overflow-hidden select-none cursor-pointer shadow-sm shadow-primary/5 hover:shadow-md hover:shadow-primary/10"
532
+ >
533
+ {/* Fill effect helper layer */}
534
+ <div className="absolute inset-y-0 left-0 bg-primary w-0 group-hover:w-full transition-all duration-600 ease-out z-0"></div>
535
+
536
+ {/* Text Content */}
537
+ <span className="relative z-10 flex items-center justify-center">
538
+ <BookOpen className="w-3.5 h-3.5 mr-2" />
539
+ Read Framework Docs
540
+ </span>
541
+ </a>
542
+ <a
543
+ href="https://github.com/forgewp/forgewp"
544
+ target="_blank"
545
+ rel="noreferrer"
546
+ className="group inline-flex items-center justify-center bg-white text-slate-900 border border-slate-200 font-mono font-bold text-[10px] uppercase tracking-widest px-6 py-3.5 shadow-sm hover:bg-slate-50 hover:border-slate-300 transition-all duration-200 rounded-none select-none cursor-pointer"
547
+ >
548
+ <Github className="w-3.5 h-3.5 mr-2" />
549
+ View on GitHub
550
+ </a>
551
+ </div>
552
+ </div>
553
+
554
+ {/* Right Layout: Two Stacked Compact Cards */}
555
+ <div className="lg:col-span-6 flex flex-col gap-4 w-full">
556
+
557
+ {/* Card 1: Query Sandbox */}
558
+ <a
559
+ href="/query-sandbox"
560
+ className="group bg-white border border-transparent p-4 lg:p-5 shadow-md shadow-slate-100/30 hover:shadow-[0_0_15px_oklch(0.61_0.22_42.5/_0.08)] transition-all duration-500 rounded-none relative overflow-hidden flex flex-col justify-center"
561
+ >
562
+ {/* Top border progress bar on hover */}
563
+ <div className="absolute top-0 left-0 h-[2px] bg-linear-to-r from-primary to-amber-500 w-0 group-hover:w-full transition-all duration-1000 ease-out"></div>
564
+
565
+ <div className="flex items-start gap-4">
566
+ <div className="bg-amber-500/5 p-2.5 rounded-full border border-amber-500/10 shrink-0">
567
+ <Database className="w-5 h-5 text-amber-500" />
568
+ </div>
569
+
570
+ <div className="flex-1 pr-6">
571
+ <h3 className="font-heading font-black text-lg text-slate-900 tracking-tight mb-2 uppercase">
572
+ Relational Query Sandbox
573
+ </h3>
574
+ <p className="text-slate-500 text-xs leading-relaxed font-sans font-medium">
575
+ Test and inspect ForgeWP's mock data loop systems, custom tax
576
+ queries, meta mappings, and server pagination.
577
+ </p>
578
+ </div>
579
+
580
+ <div className="absolute right-6 top-1/2 -translate-y-1/2">
581
+ <ChevronRight className="w-5 h-5 text-amber-500 opacity-40 group-hover:opacity-100 group-hover:translate-x-1 transition-all duration-500" />
582
+ </div>
583
+ </div>
584
+ </a>
585
+
586
+ {/* Card 2: wp-editable */}
587
+ <a
588
+ href="/wp-editable"
589
+ className="group bg-white border border-transparent p-4 lg:p-5 shadow-md shadow-slate-100/30 hover:shadow-[0_0_15px_oklch(0.61_0.22_42.5/_0.08)] transition-all duration-500 rounded-none relative overflow-hidden flex flex-col justify-center"
590
+ >
591
+ {/* Top border progress bar on hover */}
592
+ <div className="absolute top-0 left-0 h-[2px] bg-linear-to-r from-primary to-amber-500 w-0 group-hover:w-full transition-all duration-1000 ease-out"></div>
593
+
594
+ <div className="flex items-start gap-4">
595
+ <div className="bg-primary/5 p-2.5 rounded-full border border-primary/10 shrink-0">
596
+ <Code2 className="w-5 h-5 text-primary" />
597
+ </div>
598
+
599
+ <div className="flex-1 pr-6">
600
+ <h3 className="font-heading font-black text-lg text-slate-900 tracking-tight mb-2 uppercase">
601
+ WpEditable Block Canvas
602
+ </h3>
603
+ <p className="text-slate-500 text-xs leading-relaxed font-sans font-medium">
604
+ Test visual inline editing primitives. Build custom content
605
+ editors directly inside the Gutenberg admin dashboard.
606
+ </p>
607
+ </div>
608
+
609
+ <div className="absolute right-6 top-1/2 -translate-y-1/2">
610
+ <ChevronRight className="w-5 h-5 text-primary opacity-40 group-hover:opacity-100 group-hover:translate-x-1 transition-all duration-500" />
611
+ </div>
612
+ </div>
613
+ </a>
614
+
615
+ </div>
616
+ </div>
617
+ </main>
618
+ </div>
619
+ );
620
+ }
621
+ `;
622
+
623
+ try {
624
+ writeFileSync(routesPath, routesContent, 'utf8');
625
+ console.log(` ${pc.green('✅ Reset routes definition')}: src/app/routes.tsx`);
626
+ } catch (err) {
627
+ console.log(pc.red(` ❌ Failed to reset src/app/routes.tsx: ${err.message}`));
628
+ }
629
+
630
+ try {
631
+ writeFileSync(pagePath, pageContent, 'utf8');
632
+ console.log(` ${pc.green('✅ Reset core template')}: src/app/page.tsx`);
633
+ } catch (err) {
634
+ console.log(pc.red(` ❌ Failed to reset src/app/page.tsx: ${err.message}`));
635
+ }
636
+
637
+ // Ensure shadcn's components.json is present so `forgewp add` works
638
+ // immediately after a fresh without requiring a manual `shadcn init`.
639
+ const componentsJsonPath = path.join(themeRoot, 'components.json');
640
+ if (!existsSync(componentsJsonPath)) {
641
+ 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": ""
652
+ },
653
+ "aliases": {
654
+ "components": "@/components",
655
+ "utils": "@/lib/utils",
656
+ "ui": "@/components/ui",
657
+ "lib": "@/lib",
658
+ "hooks": "@/hooks"
659
+ },
660
+ "iconLibrary": "lucide"
661
+ };
662
+ try {
663
+ writeFileSync(componentsJsonPath, JSON.stringify(defaultComponentsJson, null, 2), 'utf8');
664
+ console.log(` ${pc.green('✅ Created shadcn config')}: components.json`);
665
+ } catch (err) {
666
+ console.log(pc.yellow(` ⚠️ Could not create components.json: ${err.message}`));
667
+ }
668
+ } else {
669
+ console.log(` ${pc.dim('↳ components.json already present')}`);
670
+ }
671
+ }
672
+
673
+
674
+ export function onMakeBlock(themeRoot, { pascalCase, readableTitle, attributesList, pc }) {
675
+ const blocksDir = path.join(themeRoot, 'src', 'blocks');
676
+ if (!existsSync(blocksDir)) {
677
+ mkdirSync(blocksDir, { recursive: true });
678
+ }
679
+
680
+ const targetFile = path.join(blocksDir, `${pascalCase}.tsx`);
681
+ if (existsSync(targetFile)) {
682
+ console.error(pc.red(`\n❌ Error: Block "${pascalCase}.tsx" already exists at src/blocks/\n`));
683
+ process.exit(1);
684
+ }
685
+
686
+ const nameSlug = pascalCase.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
687
+
688
+ const attributesRegistry = attributesList
689
+ .map(a => ` ${a}: { type: "string", default: "Customize ${a} here" }`)
690
+ .join(',\n');
691
+
692
+ const editFields = attributesList
693
+ .map(a => {
694
+ const cleanLabel = a
695
+ .replace(/_/g, ' ')
696
+ .replace(/(?:^\w|[A-Z]|\b\w)/g, word => word.toUpperCase());
697
+
698
+ if (a === 'content' || a === 'description' || a === 'body') {
699
+ return `<div className="border border-slate-100 p-4 bg-slate-50/30 rounded-none">
700
+ <label className="block text-xs font-mono font-bold uppercase text-slate-700 mb-1">${cleanLabel}</label>
701
+ <textarea
702
+ value={attributes.${a}}
703
+ onChange={(e) => setAttributes({ ${a}: e.target.value })}
704
+ className="w-full p-2 border border-slate-200 bg-white font-sans text-xs focus:ring-0 focus:outline-none focus:border-primary rounded-none shadow-sm"
705
+ rows={3}
706
+ placeholder="Enter ${cleanLabel} content..."
707
+ />
708
+ </div>`;
709
+ }
710
+ return `<div className="border border-slate-100 p-4 bg-slate-50/30 rounded-none">
711
+ <label className="block text-xs font-mono font-bold uppercase text-slate-700 mb-1">${cleanLabel}</label>
712
+ <input
713
+ type="text"
714
+ value={attributes.${a}}
715
+ onChange={(e) => setAttributes({ ${a}: e.target.value })}
716
+ className="w-full p-2 border border-slate-200 bg-white font-sans text-xs focus:ring-0 focus:outline-none focus:border-primary rounded-none shadow-sm"
717
+ placeholder="Enter ${cleanLabel}..."
718
+ />
719
+ </div>`;
720
+ })
721
+ .join('\n ');
722
+
723
+ const saveLayout = attributesList
724
+ .map((attr, index) => {
725
+ if (index === 0) {
726
+ return `<h3 className="text-2xl font-black text-slate-900 uppercase tracking-tight leading-none mb-3">
727
+ {attributes.${attr}}
728
+ </h3>`;
729
+ }
730
+ if (
731
+ attr.toLowerCase().includes('image') ||
732
+ attr.toLowerCase().includes('pic') ||
733
+ attr.toLowerCase().includes('img')
734
+ ) {
735
+ return `<img src={attributes.${attr}} alt="Block Media" className="w-full border border-slate-100 shadow-md mb-3" />`;
736
+ }
737
+ return `<p className="text-sm text-slate-600 font-medium font-sans leading-relaxed mb-3">
738
+ {attributes.${attr}}
739
+ </p>`;
740
+ })
741
+ .join('\n ');
742
+
743
+ const blockTemplate = `import { defineBlock } from "@forgewp/react";
744
+
745
+ /**
746
+ * ⚡ ForgeWP Custom Gutenberg Block — "Sharp ${readableTitle}"
747
+ *
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
+ * \`\`\`
760
+ */
761
+ export default defineBlock({
762
+ name: "${nameSlug}",
763
+ title: "Sharp ${readableTitle}",
764
+ category: "design",
765
+ icon: "admin-post", // Choose icons from: https://developer.wordpress.org/resource/dashicons/
766
+ attributes: {
767
+ ${attributesRegistry}
768
+ },
769
+ edit: ({ attributes, setAttributes }) => {
770
+ return (
771
+ <div className="p-8 bg-white border border-slate-100 shadow-xl shadow-slate-100/50 rounded-none my-6 selection:bg-brand selection:text-white">
772
+ <span className="inline-block bg-primary/5 text-primary border border-primary/10 text-xs font-mono font-bold uppercase tracking-wider px-2.5 py-1 mb-4">
773
+ Gutenberg Custom Block (Edit Mode)
774
+ </span>
775
+ <div className="space-y-4">
776
+ ${editFields}
777
+ </div>
778
+ </div>
779
+ );
780
+ },
781
+ save: ({ attributes }) => {
782
+ return (
783
+ <div className="p-8 bg-white border border-slate-100 shadow-xl shadow-slate-100/50 rounded-none my-6 selection:bg-brand selection:text-white">
784
+ <span className="inline-block bg-primary/5 text-primary border border-primary/10 text-xs font-mono font-bold uppercase tracking-wider px-2.5 py-1 mb-3">
785
+ Gutenberg Custom Block
786
+ </span>
787
+ ${saveLayout}
788
+ </div>
789
+ );
790
+ }
791
+ });
792
+ `;
793
+
794
+ writeFileSync(targetFile, blockTemplate, 'utf8');
795
+
796
+ console.log(pc.green(`\n⚡ Modern Block "${pascalCase}" successfully created!`));
797
+ console.log(` Location: ${pc.cyan(`src/blocks/${pascalCase}.tsx`)}`);
798
+ 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`);
800
+ }
801
+
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 });
806
+ }
807
+
808
+ const targetFile = path.join(templatesDir, `${pascalCase}.tsx`);
809
+ if (existsSync(targetFile)) {
810
+ console.error(pc.red(`\n❌ Error: Template "${pascalCase}.tsx" already exists at src/templates/\n`));
811
+ process.exit(1);
812
+ }
813
+
814
+ let customFieldsMarkup = '';
815
+ if (customFields.length > 0) {
816
+ customFieldsMarkup = customFields
817
+ .map(f => {
818
+ const cleanLabel = f
819
+ .replace(/_/g, ' ')
820
+ .replace(/(?:^\w|[A-Z]|\b\w)/g, word => word.toUpperCase());
821
+ return `<div className="flex justify-between border-t border-slate-100 pt-2 text-xs font-mono text-slate-500">
822
+ <span>${cleanLabel}:</span>
823
+ <span className="font-bold text-slate-800">{useWpCustomField("${f}")}</span>
824
+ </div>`;
825
+ })
826
+ .join('\n ');
827
+ } else {
828
+ 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
+ }
830
+
831
+ const templateTemplate = `import { WpQueryLoop, useWpTitle, useWpFeaturedImage, useWpExcerpt, useWpPermalink, useWpCustomField } from "@/.forgewp/wordpress";
832
+
833
+ /**
834
+ * ⚡ ForgeWP Custom Post Type Template — "${pascalCase}"
835
+ *
836
+ * This loop template dynamically queries and renders records of the "${postType}" post type.
837
+ * In local development, the post data and custom fields are fetched dynamically from
838
+ * your local JSON database file at: \`cms/mock-data.json\`.
839
+ */
840
+ export default function ${pascalCase}() {
841
+ return (
842
+ <div className="min-h-screen bg-slate-50 selection:bg-primary selection:text-white py-12">
843
+ <div className="max-w-6xl mx-auto px-4">
844
+ {/* Header Banner */}
845
+ <div className="mb-12 border border-slate-100 bg-white p-8 shadow-xl shadow-slate-100/50">
846
+ <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
848
+ </span>
849
+ <h1 className="text-4xl md:text-5xl font-black uppercase tracking-tight text-slate-900">
850
+ Latest ${postType.charAt(0).toUpperCase() + postType.slice(1)} Feed
851
+ </h1>
852
+ <p className="text-sm font-mono font-medium text-slate-500 mt-2">
853
+ Dynamic Post-Type Template &bull; Querying: "${postType}"
854
+ </p>
855
+ </div>
856
+
857
+ {/* Post Grid Loop */}
858
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
859
+ <WpQueryLoop postType="${postType}" postsPerPage={6}>
860
+ <article className="bg-white border border-slate-100 p-6 shadow-lg hover:shadow-xl hover:-translate-y-0.5 transition-all duration-300 rounded-none flex flex-col justify-between">
861
+ <div>
862
+ <div className="relative aspect-video w-full border border-slate-100 overflow-hidden mb-4 bg-slate-50/50">
863
+ <img
864
+ src={useWpFeaturedImage()}
865
+ alt={useWpTitle()}
866
+ className="object-cover w-full h-full"
867
+ />
868
+ </div>
869
+ <h3 className="text-2xl font-black text-slate-900 uppercase tracking-tight leading-none mb-3 hover:text-primary transition-colors">
870
+ <a href={useWpPermalink()}>{useWpTitle()}</a>
871
+ </h3>
872
+ <p className="text-sm text-slate-500 font-sans leading-relaxed mb-6">
873
+ {useWpExcerpt()}
874
+ </p>
875
+ </div>
876
+
877
+ <div className="space-y-2 mt-auto">
878
+ ${customFieldsMarkup}
879
+ </div>
880
+ </article>
881
+ </WpQueryLoop>
882
+ </div>
883
+ </div>
884
+ </div>
885
+ );
886
+ }
887
+ `;
888
+
889
+ writeFileSync(targetFile, templateTemplate, 'utf8');
890
+
891
+ 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!`);
894
+ }
895
+
896
+ console.log(pc.green(`\n⚡ Loop Template "${pascalCase}" successfully created!`));
897
+ console.log(` Location: ${pc.cyan(`src/templates/${pascalCase}.tsx`)}`);
898
+ console.log(` Target Post Type: ${pc.yellow(postType)}`);
899
+ if (customFields.length > 0) {
900
+ console.log(` Seeded Custom Fields: ${pc.yellow(customFields.join(', '))}`);
901
+ }
902
+ 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);
909
+ }
910
+
911
+ export function onMakeIsland(themeRoot, { pascalCase, pc }) {
912
+ const componentsDir = path.join(themeRoot, 'src', 'components');
913
+ if (!existsSync(componentsDir)) {
914
+ mkdirSync(componentsDir, { recursive: true });
915
+ }
916
+
917
+ const targetFile = path.join(componentsDir, `${pascalCase}.tsx`);
918
+ if (existsSync(targetFile)) {
919
+ console.error(pc.red(`\n❌ Error: Island "${pascalCase}.tsx" already exists at src/components/\n`));
920
+ process.exit(1);
921
+ }
922
+
923
+ const islandTemplate = `import { useState, useEffect } from "react";
924
+
925
+ /**
926
+ * ⚡ 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:
934
+ * import ${pascalCase} from "@/components/${pascalCase}";
935
+ * import { Hydrate } from "@forgewp/react";
936
+ *
937
+ * <Hydrate trigger="visible" preload="near-visible">
938
+ * <${pascalCase} />
939
+ * </Hydrate>
940
+ */
941
+ export interface ${pascalCase}Props {
942
+ label?: string;
943
+ }
944
+
945
+ export default function ${pascalCase}({ label = "React State Island (${pascalCase})" }: ${pascalCase}Props) {
946
+ const [count, setCount] = useState(0);
947
+ const [isHydrated, setIsHydrated] = useState(false);
948
+
949
+ useEffect(() => {
950
+ setIsHydrated(true);
951
+ }, []);
952
+
953
+ 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)"}
967
+ </span>
968
+ </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>
972
+ <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"
975
+ >
976
+ Increment Value
977
+ </button>
978
+ </div>
979
+ </div>
980
+ );
981
+ }
982
+ `;
983
+
984
+ writeFileSync(targetFile, islandTemplate, 'utf8');
985
+
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`);
991
+ }
992
+
993
+ export function onSyncRoutes(themeRoot, { routesToScaffold, isForce, pc }) {
994
+ 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';
1001
+ }
1002
+
1003
+ const pagesDir = path.join(themeRoot, 'src', 'app', 'pages');
1004
+ if (!existsSync(pagesDir)) {
1005
+ mkdirSync(pagesDir, { recursive: true });
1006
+ }
1007
+
1008
+ let scaffoldedCount = 0;
1009
+ let skippedCount = 0;
1010
+
1011
+ for (const route of routesToScaffold) {
1012
+ const componentName = toPascalCase(route.title);
1013
+ const componentPath = path.join(pagesDir, `${componentName}.tsx`);
1014
+
1015
+ const componentContent = `/**
1016
+ * ⚡ Auto-Generated Page Component by ForgeWP
1017
+ *
1018
+ * This file was generated automatically from your sitemap configuration (cms/menus.json).
1019
+ * You can safely edit this file to customize the visual layout, styles, and logic.
1020
+ * Subsequent runs of 'pnpm forgewp sync:routes' will NOT overwrite your changes.
1021
+ *
1022
+ * To force reset this page back to boilerplate defaults, run:
1023
+ * 'pnpm forgewp sync:routes --force'
1024
+ */
1025
+ import { WpHead } from "../../.forgewp/wordpress";
1026
+ import { WpQueryLoop, useWpTitle, useWpExcerpt, useWpFeaturedImage } from "../../.forgewp/wordpress";
1027
+
1028
+ export function ${componentName}() {
1029
+ return (
1030
+ <main className="container mx-auto px-6 py-12 font-sans text-slate-900">
1031
+ {/* WordPress SEO — compiles to native <meta> tags in your theme header */}
1032
+ <WpHead
1033
+ title="${route.title}"
1034
+ description="Explore our exclusive ${route.title} section, dynamically loaded in Headless React."
1035
+ />
1036
+
1037
+ {/* Hero Header Area */}
1038
+ <header className="border-b border-slate-100 pb-6 mb-12">
1039
+ <h1 className="text-5xl font-black tracking-tight uppercase text-slate-900">${route.title}</h1>
1040
+ <p className="text-slate-500 mt-2 text-sm">
1041
+ Auto-generated template. Edit <code className="bg-slate-50 px-1 py-0.5 border border-slate-100 text-xs text-primary font-mono">src/app/pages/${componentName}.tsx</code> to customize this page.
1042
+ </p>
1043
+ </header>
1044
+
1045
+ {/* Grid Starter - WordPress Mock Loop */}
1046
+ <section className="grid grid-cols-1 md:grid-cols-3 gap-8">
1047
+ <WpQueryLoop postType="post" postsPerPage={3}>
1048
+ <article className="border border-slate-100 p-6 bg-white shadow-lg hover:shadow-xl hover:-translate-y-0.5 transition-all duration-300 rounded-none flex flex-col justify-between">
1049
+ <div>
1050
+ <div className="w-full h-48 bg-slate-50/50 mb-4 border border-slate-100 overflow-hidden">
1051
+ <img
1052
+ src={useWpFeaturedImage()}
1053
+ alt={useWpTitle()}
1054
+ className="w-full h-full object-cover"
1055
+ />
1056
+ </div>
1057
+ <h2 className="text-xl font-bold uppercase tracking-tight mb-2 text-slate-900">
1058
+ {useWpTitle()}
1059
+ </h2>
1060
+ <p className="text-slate-500 text-sm mb-4">
1061
+ {useWpExcerpt()}
1062
+ </p>
1063
+ </div>
1064
+ <a
1065
+ href="#"
1066
+ className="inline-block px-4 py-2 border border-primary bg-primary text-white font-bold uppercase text-[10px] tracking-wider hover:bg-transparent hover:text-primary transition-colors cursor-pointer text-center"
1067
+ >
1068
+ Read More
1069
+ </a>
1070
+ </article>
1071
+ </WpQueryLoop>
1072
+ </section>
1073
+ </main>
1074
+ );
1075
+ }
1076
+ `;
1077
+
1078
+ if (existsSync(componentPath) && !isForce) {
1079
+ console.log(` ${pc.gray('ℹ️ [Skip] Component already exists:')} src/app/pages/${componentName}.tsx`);
1080
+ skippedCount++;
1081
+ } else {
1082
+ writeFileSync(componentPath, componentContent, 'utf8');
1083
+ console.log(` ${pc.green('✅ Scaffolded component')}: src/app/pages/${componentName}.tsx`);
1084
+ scaffoldedCount++;
1085
+ }
1086
+ }
1087
+
1088
+ // Discover Custom Post Types (CPTs) from cms/mock-data.json
1089
+ const mockDataPath = path.join(themeRoot, 'cms', 'mock-data.json');
1090
+ 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
+ }
1102
+ }
1103
+ } catch (e) {
1104
+ console.log(pc.yellow(` ⚠️ Warning: Failed to parse cms/mock-data.json for CPT auto-discovery.`));
1105
+ }
1106
+ }
1107
+
1108
+ let cptScaffoldedCount = 0;
1109
+ let cptSkippedCount = 0;
1110
+
1111
+ for (const cpt of cpts) {
1112
+ const pascalCpt = cpt.charAt(0).toUpperCase() + cpt.slice(1);
1113
+
1114
+ // 1. Scaffold thin wrapper src/app/single-${cpt}.tsx
1115
+ const wrapperPath = path.join(themeRoot, 'src', 'app', `single-${cpt}.tsx`);
1116
+ const wrapperContent = `import { Single${pascalCpt}Page } from "./pages/Single${pascalCpt}Page";
1117
+ export default Single${pascalCpt}Page;
1118
+ `;
1119
+
1120
+ if (existsSync(wrapperPath) && !isForce) {
1121
+ // Skip wrapper
1122
+ } else {
1123
+ writeFileSync(wrapperPath, wrapperContent, 'utf8');
1124
+ console.log(` ${pc.green('✅ Scaffolded thin CPT wrapper')}: src/app/single-${cpt}.tsx`);
1125
+ }
1126
+
1127
+ // 2. Scaffold page component src/app/pages/Single${pascalCpt}Page.tsx
1128
+ const cptPagePath = path.join(pagesDir, `Single${pascalCpt}Page.tsx`);
1129
+ const cptPageContent = `/**
1130
+ * ⚡ Auto-Generated CPT Single Page Component by ForgeWP
1131
+ *
1132
+ * This file was generated automatically for the custom post type "${cpt}".
1133
+ * You can safely edit this file to customize the visual layout, styles, and custom fields.
1134
+ * Subsequent runs of 'pnpm forgewp sync:routes' will NOT overwrite your changes.
1135
+ *
1136
+ * To force reset this page back to boilerplate defaults, run:
1137
+ * 'pnpm forgewp sync:routes --force'
1138
+ */
1139
+ import { useRoute } from "wouter";
1140
+ import {
1141
+ WpHead,
1142
+ WpLink,
1143
+ useWpQuery,
1144
+ useWpTitle,
1145
+ useWpContent,
1146
+ useWpFeaturedImage
1147
+ } from "../../.forgewp/wordpress";
1148
+ import { ArrowLeft } from "lucide-react";
1149
+
1150
+ export function Single${pascalCpt}Page() {
1151
+ const [, params] = useRoute("/${cpt}/:id");
1152
+ const routeParam = params?.id;
1153
+
1154
+ // In production, forgeWpHydration.post.id holds the real WP numeric ID
1155
+ const hydrationId =
1156
+ typeof window !== 'undefined'
1157
+ ? (window as any).forgeWpHydration?.post?.id || 0
1158
+ : 0;
1159
+ const id = hydrationId || routeParam;
1160
+
1161
+ // Local development mock query for single ${cpt}
1162
+ const { posts } = useWpQuery({
1163
+ postType: "${cpt}",
1164
+ postsPerPage: 100,
1165
+ });
1166
+
1167
+ const devPost = posts.find(
1168
+ (p) => p.id === Number(id) || p.id === Number(hydrationId)
1169
+ );
1170
+
1171
+ // Isomorphic dynamic mapping (compiles directly to WP loops in production)
1172
+ const title = useWpTitle() || devPost?.title || "Details";
1173
+ const content =
1174
+ useWpContent() || devPost?.content || "<p>Loading details...</p>";
1175
+ const rawImage = useWpFeaturedImage();
1176
+ const hydrationImage =
1177
+ typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime
1178
+ ? (window as any).forgeWpHydration?.currentFeaturedImage || ""
1179
+ : "";
1180
+ const restImage =
1181
+ typeof devPost?.featuredImage === "object" && devPost?.featuredImage !== null
1182
+ ? (devPost.featuredImage as any).url || ""
1183
+ : String(devPost?.featuredImage || "");
1184
+ const featuredImage = restImage || hydrationImage || rawImage || "https://picsum.photos/seed/forgewp/1200/630";
1185
+
1186
+ return (
1187
+ <main className="min-h-screen bg-slate-50 font-sans text-slate-800 py-12 px-4 sm:px-6 lg:px-8">
1188
+ <WpHead
1189
+ title={title}
1190
+ description="Dynamic single CPT details, loaded dynamically inside Headless React."
1191
+ />
1192
+
1193
+ <div className="max-w-4xl mx-auto bg-white rounded-3xl overflow-hidden border border-slate-100 shadow-xl p-8 sm:p-12">
1194
+ {/* Back Button */}
1195
+ <WpLink
1196
+ href="/${cpt}s"
1197
+ className="inline-flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-400 hover:text-primary transition-colors mb-8"
1198
+ >
1199
+ <ArrowLeft className="w-3.5 h-3.5" /> Back to overview
1200
+ </WpLink>
1201
+
1202
+ {/* Hero image */}
1203
+ {featuredImage && (
1204
+ <div className="w-full aspect-video rounded-2xl overflow-hidden border border-slate-100 mb-8">
1205
+ <img
1206
+ src={featuredImage}
1207
+ alt={title}
1208
+ className="w-full h-full object-cover"
1209
+ />
1210
+ </div>
1211
+ )}
1212
+
1213
+ {/* Heading */}
1214
+ <h1 className="text-3xl sm:text-5xl font-black tracking-tight text-slate-900 uppercase mb-6 leading-tight">
1215
+ {title}
1216
+ </h1>
1217
+
1218
+ {/* Content */}
1219
+ <div
1220
+ className="prose prose-slate max-w-none text-slate-600 text-sm leading-relaxed"
1221
+ dangerouslySetInnerHTML={{ __html: content }}
1222
+ />
1223
+ </div>
1224
+ </main>
1225
+ );
1226
+ }
1227
+ `;
1228
+
1229
+ if (existsSync(cptPagePath) && !isForce) {
1230
+ console.log(` ${pc.gray('ℹ️ [Skip] CPT Page Component already exists:')} src/app/pages/Single${pascalCpt}Page.tsx`);
1231
+ cptSkippedCount++;
1232
+ } else {
1233
+ writeFileSync(cptPagePath, cptPageContent, 'utf8');
1234
+ console.log(` ${pc.green('✅ Scaffolded CPT Page Component')}: src/app/pages/Single${pascalCpt}Page.tsx`);
1235
+ cptScaffoldedCount++;
1236
+ }
1237
+ }
1238
+
1239
+ const routesFilePath = path.join(themeRoot, 'src', 'app', 'routes.tsx');
1240
+ if (existsSync(routesFilePath)) {
1241
+ let routesContent = readFileSync(routesFilePath, 'utf8');
1242
+ let modified = false;
1243
+
1244
+ for (const route of routesToScaffold) {
1245
+ const componentName = toPascalCase(route.title);
1246
+
1247
+ const importRegex = new RegExp(`import\\s+\\{\\s*${componentName}\\s*\\}\\s+from\\s+["']\\./pages/${componentName}["']`);
1248
+ if (!importRegex.test(routesContent)) {
1249
+ const defaultExportIndex = routesContent.indexOf('export default function');
1250
+ if (defaultExportIndex !== -1) {
1251
+ routesContent =
1252
+ routesContent.slice(0, defaultExportIndex) +
1253
+ `import { ${componentName} } from "./pages/${componentName}";\n` +
1254
+ routesContent.slice(defaultExportIndex);
1255
+ modified = true;
1256
+ }
1257
+ }
1258
+
1259
+ const routeRegex = new RegExp(`path\\s*=\\s*["']${route.path}["']`);
1260
+ if (!routeRegex.test(routesContent)) {
1261
+ const fallbackMarker = '{/* Fallback route */}';
1262
+ const fallbackIndex = routesContent.indexOf(fallbackMarker);
1263
+ if (fallbackIndex !== -1) {
1264
+ routesContent =
1265
+ routesContent.slice(0, fallbackIndex) +
1266
+ `<Route path="${route.path}" component={${componentName}} />\n\n ` +
1267
+ routesContent.slice(fallbackIndex);
1268
+ modified = true;
1269
+ } else {
1270
+ const switchCloseIndex = routesContent.indexOf('</Switch>');
1271
+ if (switchCloseIndex !== -1) {
1272
+ routesContent =
1273
+ routesContent.slice(0, switchCloseIndex) +
1274
+ ` <Route path="${route.path}" component={${componentName}} />\n ` +
1275
+ routesContent.slice(switchCloseIndex);
1276
+ modified = true;
1277
+ }
1278
+ }
1279
+ }
1280
+ }
1281
+
1282
+ // --- CPT Routing Sync ---
1283
+ for (const cpt of cpts) {
1284
+ const pascalCpt = cpt.charAt(0).toUpperCase() + cpt.slice(1);
1285
+ const componentName = `Single${pascalCpt}Page`;
1286
+
1287
+ const importRegex = new RegExp(`import\\s+\\{\\s*${componentName}\\s*\\}\\s+from\\s+["']\\./pages/${componentName}["']`);
1288
+ if (!importRegex.test(routesContent)) {
1289
+ const defaultExportIndex = routesContent.indexOf('export default function');
1290
+ if (defaultExportIndex !== -1) {
1291
+ routesContent =
1292
+ routesContent.slice(0, defaultExportIndex) +
1293
+ `import { ${componentName} } from "./pages/${componentName}";\n` +
1294
+ routesContent.slice(defaultExportIndex);
1295
+ modified = true;
1296
+ }
1297
+ }
1298
+
1299
+ const routeRegex = new RegExp(`path\\s*=\\s*["']/${cpt}/:id["']`);
1300
+ if (!routeRegex.test(routesContent)) {
1301
+ const fallbackMarker = '{/* Fallback route */}';
1302
+ const fallbackIndex = routesContent.indexOf(fallbackMarker);
1303
+ if (fallbackIndex !== -1) {
1304
+ routesContent =
1305
+ routesContent.slice(0, fallbackIndex) +
1306
+ `<Route path="/${cpt}/:id" component={${componentName}} />\n\n ` +
1307
+ routesContent.slice(fallbackIndex);
1308
+ modified = true;
1309
+ } else {
1310
+ const switchCloseIndex = routesContent.indexOf('</Switch>');
1311
+ if (switchCloseIndex !== -1) {
1312
+ routesContent =
1313
+ routesContent.slice(0, switchCloseIndex) +
1314
+ ` <Route path="/${cpt}/:id" component={${componentName}} />\n ` +
1315
+ routesContent.slice(switchCloseIndex);
1316
+ modified = true;
1317
+ }
1318
+ }
1319
+ }
1320
+ }
1321
+
1322
+ if (modified) {
1323
+ writeFileSync(routesFilePath, routesContent, 'utf8');
1324
+ console.log(` ${pc.green('✅ Synced routing paths in')}: src/app/routes.tsx`);
1325
+ } else {
1326
+ console.log(` ${pc.gray('ℹ️ Routes are already fully up to date in')}: src/app/routes.tsx`);
1327
+ }
1328
+ } else {
1329
+ console.log(pc.yellow(` ⚠️ Warning: routes.tsx not found. Skipped route linking.`));
1330
+ }
1331
+
1332
+ 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`));
1334
+ }
1335
+
1336
+ export { scanForHydrationIslands, findComponentPath, getHydrationRollupInputs };