@forgewp/compiler 0.1.9 โ†’ 0.3.0

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.
package/bin/fresh.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import { rmSync, existsSync, writeFileSync, mkdirSync, readdirSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import { spawnSync } from "node:child_process";
6
+ import readline from "node:readline";
6
7
  import pc from "picocolors";
7
8
  import { SYSTEM_BLUEPRINTS } from "../lib/blueprints.js";
8
9
 
@@ -10,6 +11,8 @@ console.log(`\n๐Ÿงน ${pc.bold(pc.bgRed(pc.black(" FORGEWP FACTORY RESET (FRESH
10
11
 
11
12
  const projectRoot = process.cwd();
12
13
 
14
+ function runReset() {
15
+
13
16
  // 1. Clean Build Caches & Artifacts
14
17
  const foldersToClean = [".forgewp", "dist", ".vite"];
15
18
  for (const folder of foldersToClean) {
@@ -419,3 +422,55 @@ if (existsSync(monorepoSyncScript)) {
419
422
  console.log("\n" + "โ”€".repeat(60));
420
423
  console.log(pc.green(`\n๐ŸŽ‰ ${pc.bold("CANVAS RESET COMPLETE:")} Reverted workspace back to standard empty blueprints.`));
421
424
  console.log(pc.cyan(" Your ForgeWP canvas is now factory-fresh, clean, and perfectly synced!\n"));
425
+ }
426
+
427
+ function hasWorkBeenDone() {
428
+ const dirsToCheck = [
429
+ "src/app/pages",
430
+ "src/blocks",
431
+ "src/components"
432
+ ];
433
+ for (const dir of dirsToCheck) {
434
+ const fullPath = path.join(projectRoot, dir);
435
+ if (existsSync(fullPath)) {
436
+ try {
437
+ const files = readdirSync(fullPath);
438
+ if (files.length > 0) {
439
+ return true;
440
+ }
441
+ } catch (e) {
442
+ // Directory exists but failed to read or is empty
443
+ }
444
+ }
445
+ }
446
+ return false;
447
+ }
448
+
449
+ const isForce = process.argv.includes("--force") || process.argv.includes("-f") || process.argv.includes("-y");
450
+
451
+ if (hasWorkBeenDone() && !isForce) {
452
+ if (!process.stdin.isTTY) {
453
+ console.log(pc.red(`โŒ Non-interactive environment detected. Please use the --force flag to reset active work.`));
454
+ process.exit(1);
455
+ }
456
+
457
+ const rl = readline.createInterface({
458
+ input: process.stdin,
459
+ output: process.stdout
460
+ });
461
+
462
+ console.log(pc.yellow(`โš ๏ธ ${pc.bold("WARNING:")} Existing custom pages, blocks, or components detected in your canvas!`));
463
+ console.log(pc.yellow(` Continuing will permanently delete all custom work and reset back to factory default.`));
464
+
465
+ rl.question(`\n Are you sure you want to proceed? (y/N): `, (answer) => {
466
+ rl.close();
467
+ const confirmed = answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes";
468
+ if (!confirmed) {
469
+ console.log(pc.blue(`\nโŒ Reset aborted. No changes were made.\n`));
470
+ process.exit(0);
471
+ }
472
+ runReset();
473
+ });
474
+ } else {
475
+ runReset();
476
+ }
@@ -1,6 +1,7 @@
1
1
  import { execSync } from "node:child_process";
2
2
  import { readFileSync, writeFileSync, readdirSync, existsSync, mkdirSync } from "node:fs";
3
3
  import path from "node:path";
4
+ import readline from "node:readline";
4
5
  import pc from "picocolors";
5
6
 
6
7
  export async function addComponent(component, options) {
@@ -34,6 +35,13 @@ export async function addComponent(component, options) {
34
35
  const content = readFileSync(localComponentFile, "utf8");
35
36
  writeFileSync(targetFile, content, "utf8");
36
37
 
38
+ // Auto-detect and install missing third-party dependencies from imported component files
39
+ await autoInstallMissingDependencies(targetFile, projectRoot);
40
+
41
+ if (style === "forgewp") {
42
+ sharpenFile(targetFile);
43
+ }
44
+
37
45
  console.log(pc.green(`\n Success! ${component} added to src/components/ui/\n`));
38
46
  return;
39
47
  }
@@ -111,3 +119,113 @@ function sharpenFile(filePath) {
111
119
  console.log(pc.dim(` Sharpened ${path.basename(filePath)}`));
112
120
  }
113
121
  }
122
+
123
+ function autoInstallMissingDependencies(filePath, projectRoot) {
124
+ return new Promise((resolve) => {
125
+ const content = readFileSync(filePath, "utf8");
126
+
127
+ // Find all import statements
128
+ const importRegex = /import\s+(?:[a-zA-Z0-9_*$,{}\s]+from\s+)?['"]([^'"]+)['"]/g;
129
+ const foundImports = new Set();
130
+ let match;
131
+
132
+ while ((match = importRegex.exec(content)) !== null) {
133
+ const importPath = match[1];
134
+ // Filter out local imports, React, and standard framework packages
135
+ if (
136
+ !importPath.startsWith(".") &&
137
+ !importPath.startsWith("/") &&
138
+ importPath !== "react" &&
139
+ importPath !== "react-dom" &&
140
+ importPath !== "@forgewp/react"
141
+ ) {
142
+ // Extract the base package name (e.g. framer-motion or @radix-ui/react-slot)
143
+ let basePkg = importPath;
144
+ if (importPath.startsWith("@")) {
145
+ const parts = importPath.split("/");
146
+ basePkg = `${parts[0]}/${parts[1]}`;
147
+ } else {
148
+ basePkg = importPath.split("/")[0];
149
+ }
150
+ foundImports.add(basePkg);
151
+ }
152
+ }
153
+
154
+ if (foundImports.size === 0) {
155
+ resolve();
156
+ return;
157
+ }
158
+
159
+ const pkgJsonPath = path.join(projectRoot, "package.json");
160
+ if (!existsSync(pkgJsonPath)) {
161
+ resolve();
162
+ return;
163
+ }
164
+
165
+ const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
166
+ const currentDeps = {
167
+ ...(pkg.dependencies || {}),
168
+ ...(pkg.devDependencies || {})
169
+ };
170
+
171
+ const missingDeps = Array.from(foundImports).filter(dep => !currentDeps[dep]);
172
+
173
+ if (missingDeps.length > 0) {
174
+ console.log(pc.yellow(`\n โšก Detected missing dependencies: ${missingDeps.join(", ")}`));
175
+
176
+ // Detect Package Manager
177
+ let installCmd = "npm install --save";
178
+ let managerName = "npm";
179
+ if (existsSync(path.join(projectRoot, "pnpm-lock.yaml"))) {
180
+ installCmd = "pnpm add";
181
+ managerName = "pnpm";
182
+ } else if (existsSync(path.join(projectRoot, "yarn.lock"))) {
183
+ installCmd = "yarn add";
184
+ managerName = "yarn";
185
+ } else if (existsSync(path.join(projectRoot, "bun.lockb"))) {
186
+ installCmd = "bun add";
187
+ managerName = "bun";
188
+ }
189
+
190
+ // Check if environment is interactive
191
+ if (!process.stdin.isTTY) {
192
+ console.log(pc.dim(` Non-interactive environment detected. Skipping auto-install.`));
193
+ console.log(pc.yellow(` Please manually install: ${installCmd} ${missingDeps.join(" ")}\n`));
194
+ resolve();
195
+ return;
196
+ }
197
+
198
+ const rl = readline.createInterface({
199
+ input: process.stdin,
200
+ output: process.stdout
201
+ });
202
+
203
+ rl.question(` ? Would you like to install them via ${pc.bold(managerName)}? (Y/n): `, (answer) => {
204
+ rl.close();
205
+ const confirmed = answer.trim().toLowerCase() !== "n";
206
+
207
+ if (confirmed) {
208
+ console.log(pc.dim(" Automatically installing dependencies..."));
209
+ try {
210
+ execSync(`${installCmd} ${missingDeps.join(" ")}`, {
211
+ stdio: "inherit",
212
+ cwd: projectRoot,
213
+ shell: process.platform === "win32"
214
+ });
215
+ console.log(pc.green(` โœ… Successfully installed: ${missingDeps.join(", ")}\n`));
216
+ } catch (err) {
217
+ console.log(pc.red(` โŒ Auto-installation failed: ${err.message}`));
218
+ console.log(pc.yellow(` Please manually install: ${installCmd} ${missingDeps.join(" ")}\n`));
219
+ }
220
+ } else {
221
+ console.log(pc.blue(" Skipped installation."));
222
+ console.log(pc.yellow(` Please manually install: ${installCmd} ${missingDeps.join(" ")}\n`));
223
+ }
224
+ resolve();
225
+ });
226
+ } else {
227
+ resolve();
228
+ }
229
+ });
230
+ }
231
+
@@ -1,5 +1,6 @@
1
1
  import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import path from "node:path";
3
+ import { scanForHydrationIslands } from "./hydration-scanner.js";
3
4
 
4
5
  /**
5
6
  * @param {Object} options
@@ -31,16 +32,249 @@ export function generateTheme({
31
32
 
32
33
  mkdirSync(outDir, { recursive: true });
33
34
 
35
+ // Load menus configuration for auto-registration and setup
36
+ let menus = {};
37
+ const menusJsonSrc = path.join(themeRoot, "wordpress", "menus.json");
38
+ if (existsSync(menusJsonSrc)) {
39
+ try {
40
+ menus = JSON.parse(readFileSync(menusJsonSrc, "utf8"));
41
+ } catch (e) {
42
+ console.warn("Failed to parse menus.json:", e.message);
43
+ }
44
+ }
45
+
46
+ // Gather compiled custom page templates for auto-creation with smart slug mapping
47
+ const pagesToAutoCreate = [];
48
+ const forgewpDir = path.join(themeRoot, ".forgewp");
49
+ if (existsSync(forgewpDir)) {
50
+ const templateFiles = readdirSync(forgewpDir);
51
+ for (const file of templateFiles) {
52
+ if (file.startsWith("template-") && file.endsWith(".html") && !file.includes("-head")) {
53
+ const slug = file.replace(".html", "");
54
+ const pageTemplateSlug = slug.replace("template-", "");
55
+
56
+ let matchedSlug = null;
57
+ let matchedTitle = null;
58
+
59
+ const toKebabTemplateSlug = (str) => {
60
+ const compName = str
61
+ .replace(/[^a-zA-Z0-9]/g, " ")
62
+ .trim()
63
+ .split(/\s+/)
64
+ .map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
65
+ .join("") + "Page";
66
+ return compName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
67
+ };
68
+
69
+ const targetKebab = pageTemplateSlug;
70
+
71
+ // Search in menus to find matching target URL slugs defined by the developer
72
+ for (const [location, items] of Object.entries(menus)) {
73
+ if (!Array.isArray(items)) continue;
74
+ for (const item of items) {
75
+ if (!item.url || !item.url.startsWith("/")) continue;
76
+ const menuUrlSlug = item.url.replace(/^\//, "");
77
+
78
+ if (
79
+ toKebabTemplateSlug(item.title) === targetKebab ||
80
+ toKebabTemplateSlug(menuUrlSlug) === targetKebab
81
+ ) {
82
+ matchedSlug = menuUrlSlug;
83
+ matchedTitle = item.title;
84
+ break;
85
+ }
86
+ }
87
+ if (matchedSlug) break;
88
+ }
89
+
90
+ // Fallback 1: Strip trailing "-page" from template slug
91
+ if (!matchedSlug) {
92
+ matchedSlug = pageTemplateSlug.endsWith("-page")
93
+ ? pageTemplateSlug.slice(0, -5)
94
+ : pageTemplateSlug;
95
+ }
96
+
97
+ // Fallback 2: Generate clean human-readable title
98
+ if (!matchedTitle) {
99
+ const cleanName = pageTemplateSlug.endsWith("-page") ? pageTemplateSlug.slice(0, -5) : pageTemplateSlug;
100
+ matchedTitle = cleanName.split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
101
+ }
102
+
103
+ pagesToAutoCreate.push({
104
+ title: matchedTitle,
105
+ slug: matchedSlug,
106
+ template: `page-${pageTemplateSlug}.php`
107
+ });
108
+ }
109
+ }
110
+ }
111
+
112
+ const hydrationIslands = scanForHydrationIslands(themeRoot);
113
+ const hasHydration = hydrationIslands.length > 0;
114
+
34
115
  const assetsOut = path.join(outDir, "assets");
35
116
  const distAssets = path.join(themeRoot, "dist", "assets");
36
117
  mkdirSync(assetsOut, { recursive: true });
37
118
  cpSync(distAssets, assetsOut, { recursive: true });
38
119
 
120
+ let hydrationManifestJson = "{}";
121
+ if (hasHydration) {
122
+ const manifestPath = path.join(themeRoot, "dist", ".vite", "manifest.json");
123
+ let viteManifest = {};
124
+ if (existsSync(manifestPath)) {
125
+ try {
126
+ viteManifest = JSON.parse(readFileSync(manifestPath, "utf8"));
127
+ } catch (e) {
128
+ console.warn("Failed to parse Vite manifest.json:", e.message);
129
+ }
130
+ }
131
+
132
+ const mapping = {};
133
+ let mainJsFile = "";
134
+ const entryChunk = viteManifest["index.html"] || Object.values(viteManifest).find(c => c.isEntry);
135
+ if (entryChunk) {
136
+ mainJsFile = entryChunk.file;
137
+ }
138
+
139
+ for (const island of hydrationIslands) {
140
+ const pascalName = island
141
+ .split("-")
142
+ .map(w => w.charAt(0).toUpperCase() + w.slice(1))
143
+ .join("");
144
+
145
+ let resolvedChunk = null;
146
+ for (const [key, value] of Object.entries(viteManifest)) {
147
+ if (
148
+ key.endsWith(`${pascalName}.tsx`) ||
149
+ key.endsWith(`${pascalName}.ts`) ||
150
+ key.endsWith(`${island}.tsx`) ||
151
+ key.endsWith(`${island}.ts`) ||
152
+ (value.file && value.file.includes(island))
153
+ ) {
154
+ resolvedChunk = value.file;
155
+ break;
156
+ }
157
+ }
158
+
159
+ if (resolvedChunk) {
160
+ mapping[island] = resolvedChunk;
161
+ }
162
+ }
163
+
164
+ const hydratorScript = `(function () {
165
+ const config = window.forgeWpHydration || { themeUri: "", manifest: {} };
166
+ const islands = document.querySelectorAll("[data-forgewp-hydrate]");
167
+
168
+ const observer = new IntersectionObserver((entries) => {
169
+ entries.forEach((entry) => {
170
+ if (entry.isIntersecting) {
171
+ const hydrate = entry.target.__forgewpHydrate;
172
+ if (typeof hydrate === "function") hydrate();
173
+ observer.unobserve(entry.target);
174
+ }
175
+ });
176
+ }, { rootMargin: "200px" });
177
+
178
+ const StrategyRegistry = {
179
+ load: (el, hydrate) => {
180
+ if (document.readyState === "complete") {
181
+ hydrate();
182
+ } else {
183
+ window.addEventListener("load", hydrate);
184
+ }
185
+ },
186
+ visible: (el, hydrate) => {
187
+ el.__forgewpHydrate = hydrate;
188
+ observer.observe(el);
189
+ },
190
+ interaction: (el, hydrate) => {
191
+ const run = () => {
192
+ hydrate();
193
+ el.removeEventListener("click", run);
194
+ el.removeEventListener("mouseenter", run);
195
+ el.removeEventListener("focusin", run);
196
+ };
197
+ el.addEventListener("click", run);
198
+ el.addEventListener("mouseenter", run);
199
+ el.addEventListener("focusin", run);
200
+ },
201
+ // Modern extensible triggers (e.g. idle trigger for low priority activation)
202
+ idle: (el, hydrate) => {
203
+ if ("requestIdleCallback" in window) {
204
+ window.requestIdleCallback(hydrate);
205
+ } else {
206
+ setTimeout(hydrate, 200);
207
+ }
208
+ }
209
+ };
210
+
211
+ islands.forEach((el) => {
212
+ const trigger = el.getAttribute("data-forgewp-trigger") || "visible";
213
+ const runHydration = () => hydrateElement(el);
214
+
215
+ const strategy = StrategyRegistry[trigger];
216
+ if (strategy) {
217
+ strategy(el, runHydration);
218
+ } else {
219
+ StrategyRegistry.visible(el, runHydration);
220
+ }
221
+ });
222
+
223
+ function hydrateElement(el) {
224
+ const islandName = el.getAttribute("data-forgewp-hydrate");
225
+ const rawProps = el.getAttribute("data-forgewp-props") || "{}";
226
+ const props = JSON.parse(rawProps);
227
+
228
+ const chunkPath = config.manifest[islandName];
229
+ if (!chunkPath) {
230
+ console.error("[ForgeWP Hydrator] Could not find compiled chunk for island " + islandName);
231
+ return;
232
+ }
233
+
234
+ const scriptUrl = config.themeUri + "/assets/" + chunkPath.replace(/^assets\\//, "").replace(/^assets\\/, "");
235
+
236
+ import(scriptUrl)
237
+ .then((module) => {
238
+ const Component = module.default || Object.values(module)[0];
239
+ if (typeof Component !== "function") {
240
+ console.error("[ForgeWP Hydrator] Chunk for " + islandName + " does not export a valid React component");
241
+ return;
242
+ }
243
+
244
+ if (window.ReactDOM && window.React) {
245
+ const isClientOnly = el.hasAttribute("data-forgewp-client-only");
246
+ if (isClientOnly) {
247
+ // No SSR markup present: clean render
248
+ const root = window.ReactDOM.createRoot(el);
249
+ root.render(window.React.createElement(Component, props));
250
+ } else {
251
+ // Highly optimized hydration of server-side visual markup
252
+ window.ReactDOM.hydrateRoot(el, window.React.createElement(Component, props));
253
+ }
254
+ } else {
255
+ console.error("[ForgeWP Hydration Error] React or ReactDOM not found on window object.");
256
+ }
257
+ })
258
+ .catch((err) => {
259
+ console.error("[ForgeWP Hydrator] Failed to load chunk for " + islandName + ":", err);
260
+ });
261
+ }
262
+ })();`;
263
+
264
+ writeFileSync(path.join(assetsOut, "forgewp-hydrator.js"), hydratorScript, "utf8");
265
+ hydrationManifestJson = JSON.stringify({
266
+ mainJsFile,
267
+ mapping
268
+ });
269
+ }
270
+
39
271
  // Drop unused JS from the theme ZIP
40
272
  const files = readdirSync(assetsOut);
41
273
  for (const file of files) {
42
- if ((file.endsWith(".js") || file.endsWith(".js.map")) && file !== "forgewp-editor.js") {
43
- rmSync(path.join(assetsOut, file), { force: true });
274
+ if ((file.endsWith(".js") || file.endsWith(".js.map")) && file !== "forgewp-editor.js" && file !== "forgewp-hydrator.js") {
275
+ if (!hasHydration) {
276
+ rmSync(path.join(assetsOut, file), { force: true });
277
+ }
44
278
  }
45
279
  }
46
280
 
@@ -159,9 +393,17 @@ if (window.forgeWpBlocks) {
159
393
  writeFileSync(path.join(outDir, "assets", "forgewp-editor.js"), editorScriptContent, "utf8");
160
394
 
161
395
  writeFileSync(path.join(outDir, "style.css"), buildStyleCss(config), "utf8");
396
+
397
+ let hydrationData = null;
398
+ if (hasHydration) {
399
+ try {
400
+ hydrationData = JSON.parse(hydrationManifestJson);
401
+ } catch {}
402
+ }
403
+
162
404
  writeFileSync(
163
405
  path.join(outDir, "functions.php"),
164
- buildFunctionsPhp(config, assets, compiledBlocks, themeRoot),
406
+ buildFunctionsPhp(config, assets, compiledBlocks, themeRoot, pagesToAutoCreate, menus, hydrationData),
165
407
  "utf8",
166
408
  );
167
409
  writeFileSync(path.join(outDir, "header.php"), buildHeaderPhp(config), "utf8");
@@ -174,7 +416,6 @@ if (window.forgeWpBlocks) {
174
416
  writeFileSync(path.join(outDir, "page.php"), buildPagePhp(), "utf8");
175
417
 
176
418
  // Dynamic Custom Page Templates Compiler
177
- const forgewpDir = path.join(themeRoot, ".forgewp");
178
419
  if (existsSync(forgewpDir)) {
179
420
  const templateFiles = readdirSync(forgewpDir);
180
421
  for (const file of templateFiles) {
@@ -418,7 +659,7 @@ Text Domain: ${config.textDomain}
418
659
  * @param {import('./types.js').ForgeWPThemeConfig} config
419
660
  * @param {import('./types.js').ForgeWPBuildAssets} assets
420
661
  */
421
- function buildFunctionsPhp(config, assets, blockSlugs = [], themeRoot = "") {
662
+ function buildFunctionsPhp(config, assets, blockSlugs = [], themeRoot = "", pagesToAutoCreate = [], menus = {}, hydrationData = null) {
422
663
  const css = assets.cssFile.replace(/^assets\//, "");
423
664
  const version = config.version.replace(/'/g, "\\'");
424
665
  const googleFonts = config.settings?.typography?.googleFonts || [];
@@ -535,6 +776,172 @@ add_action('enqueue_block_editor_assets', 'forgewp_enqueue_block_editor_assets')
535
776
  `;
536
777
  }
537
778
 
779
+ let registerMenusPhp = "";
780
+ const menuLocations = Object.keys(menus).filter(k => !k.startsWith("_"));
781
+ if (menuLocations.length > 0) {
782
+ registerMenusPhp = `
783
+ // Register custom navigation menus from sitemap config
784
+ register_nav_menus(array(
785
+ ${menuLocations.map(loc => ` '${loc}' => __('${loc.charAt(0).toUpperCase() + loc.slice(1)} Navigation', '${config.textDomain}'),`).join("\n")}
786
+ ));`;
787
+ }
788
+
789
+ const pagesPhpArray = pagesToAutoCreate.map(p => {
790
+ return ` array(
791
+ 'title' => '${p.title.replace(/'/g, "\\'")}',
792
+ 'slug' => '${p.slug.replace(/'/g, "\\'")}',
793
+ 'template' => '${p.template.replace(/'/g, "\\'")}',
794
+ )`;
795
+ }).join(",\n");
796
+
797
+ const menuItemsPhpArray = Object.entries(menus)
798
+ .filter(([loc]) => !loc.startsWith("_"))
799
+ .map(([loc, items]) => {
800
+ const itemsPhp = items.map(item => {
801
+ return ` array(
802
+ 'title' => '${item.title.replace(/'/g, "\\'")}',
803
+ 'url' => '${item.url.replace(/'/g, "\\'")}',
804
+ )`;
805
+ }).join(",\n");
806
+ return ` '${loc}' => array(
807
+ ${itemsPhp}
808
+ )`;
809
+ }).join(",\n");
810
+
811
+ const autoCreationPhp = `
812
+ /**
813
+ * Automatically create routes defined in menus.json and assign custom page templates upon theme activation.
814
+ */
815
+ function forgewp_auto_create_pages_and_menus(): void {
816
+ $activated_option = '${config.textDomain}_activated_' . str_replace('.', '_', FORGEWP_THEME_VERSION);
817
+ if (get_option($activated_option) === 'yes') {
818
+ return;
819
+ }
820
+
821
+ $pages = array(
822
+ ${pagesPhpArray}
823
+ );
824
+
825
+ foreach ($pages as $p) {
826
+ $existing_page = get_page_by_path($p['slug']);
827
+ if (!$existing_page) {
828
+ $page_id = wp_insert_post(array(
829
+ 'post_title' => $p['title'],
830
+ 'post_name' => $p['slug'],
831
+ 'post_status' => 'publish',
832
+ 'post_type' => 'page',
833
+ ));
834
+ if (!is_wp_error($page_id) && $page_id > 0) {
835
+ update_post_meta($page_id, '_wp_page_template', $p['template']);
836
+ }
837
+ } else {
838
+ update_post_meta($existing_page->ID, '_wp_page_template', $p['template']);
839
+ }
840
+ }
841
+
842
+ $menu_structure = array(
843
+ ${menuItemsPhpArray}
844
+ );
845
+
846
+ foreach ($menu_structure as $location => $items) {
847
+ $menu_name = ucfirst($location) . ' Navigation';
848
+ $menu_exists = wp_get_nav_menu_object($menu_name);
849
+
850
+ if (!$menu_exists) {
851
+ $menu_id = wp_create_nav_menu($menu_name);
852
+ if (!is_wp_error($menu_id)) {
853
+ $locations = get_theme_mod('nav_menu_locations');
854
+ if (!is_array($locations)) {
855
+ $locations = array();
856
+ }
857
+ $locations[$location] = $menu_id;
858
+ set_theme_mod('nav_menu_locations', $locations);
859
+
860
+ foreach ($items as $item) {
861
+ $item_title = $item['title'];
862
+ $item_url = $item['url'];
863
+
864
+ $object_id = 0;
865
+ $object_type = 'custom';
866
+ $target_url = $item_url;
867
+
868
+ if (strpos($item_url, '/') === 0) {
869
+ $slug = trim($item_url, '/');
870
+ if ($slug === '') {
871
+ $target_url = home_url('/');
872
+ } else {
873
+ $page = get_page_by_path($slug);
874
+ if ($page) {
875
+ $object_id = $page->ID;
876
+ $object_type = 'page';
877
+ $target_url = get_permalink($page->ID);
878
+ } else {
879
+ $target_url = home_url($item_url);
880
+ }
881
+ }
882
+ }
883
+
884
+ wp_update_nav_menu_item($menu_id, 0, array(
885
+ 'menu-item-title' => $item_title,
886
+ 'menu-item-url' => $target_url,
887
+ 'menu-item-object-id' => $object_id,
888
+ 'menu-item-object' => $object_type === 'page' ? 'page' : '',
889
+ 'menu-item-type' => $object_type === 'page' ? 'post_type' : 'custom',
890
+ 'menu-item-status' => 'publish',
891
+ ));
892
+ }
893
+ }
894
+ }
895
+ }
896
+
897
+ update_option($activated_option, 'yes');
898
+ }
899
+ add_action('after_switch_theme', 'forgewp_auto_create_pages_and_menus');
900
+ `;
901
+
902
+ let hydrationEnqueue = "";
903
+ if (hydrationData && hydrationData.mapping) {
904
+ const mainJs = hydrationData.mainJsFile.replace(/^assets\//, "").replace(/^assets\\/, "");
905
+ const manifestPairs = Object.entries(hydrationData.mapping).map(([key, val]) => {
906
+ const cleanVal = val.replace(/^assets\//, "").replace(/^assets\\/, "");
907
+ return ` '${key}' => 'assets/${cleanVal}'`;
908
+ }).join(",\n");
909
+
910
+ hydrationEnqueue = `
911
+ // Enqueue React runtime entrypoint and dynamic Selective Hydration assets
912
+ $js_path = get_template_directory() . '/assets/${mainJs}';
913
+ if (file_exists($js_path)) {
914
+ wp_enqueue_script(
915
+ '${config.textDomain}-react-runtime',
916
+ $theme_uri . '/assets/${mainJs}',
917
+ array(),
918
+ FORGEWP_THEME_VERSION,
919
+ true
920
+ );
921
+
922
+ // Inject hydration manifest mappings dynamically
923
+ wp_localize_script(
924
+ '${config.textDomain}-react-runtime',
925
+ 'forgeWpHydration',
926
+ array(
927
+ 'themeUri' => $theme_uri,
928
+ 'manifest' => array(
929
+ ${manifestPairs}
930
+ )
931
+ )
932
+ );
933
+
934
+ // Enqueue Micro-Hydrator orchestrator script
935
+ wp_enqueue_script(
936
+ '${config.textDomain}-hydrator',
937
+ $theme_uri . '/assets/forgewp-hydrator.js',
938
+ array('${config.textDomain}-react-runtime'),
939
+ FORGEWP_THEME_VERSION,
940
+ true
941
+ );
942
+ }`;
943
+ }
944
+
538
945
  return `<?php
539
946
  /**
540
947
  * ${config.name} โ€” generated by ForgeWP
@@ -564,6 +971,7 @@ ${fontsEnqueue}
564
971
  FORGEWP_THEME_VERSION
565
972
  );
566
973
  }
974
+ ${hydrationEnqueue}
567
975
  }
568
976
  add_action('wp_enqueue_scripts', 'forgewp_enqueue_assets');
569
977
 
@@ -579,9 +987,10 @@ function forgewp_theme_setup(): void {
579
987
 
580
988
  // Load compiled theme stylesheet inside Gutenberg Block Editor
581
989
  add_editor_style('assets/${css}');
990
+ ${registerMenusPhp}
582
991
  }
583
992
  add_action('after_setup_theme', 'forgewp_theme_setup');
584
- ${preconnectFilter}${blocksRegistration}${cptRegistration}`;
993
+ ${preconnectFilter}${blocksRegistration}${cptRegistration}${autoCreationPhp}`;
585
994
  }
586
995
 
587
996
  function buildHeaderPhp(config) {
@@ -0,0 +1,179 @@
1
+ import { readFileSync, readdirSync, existsSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ /**
5
+ * Scans the theme's page files (page.tsx, layout.tsx, pages/*.tsx)
6
+ * for <Hydrate> boundaries and extracts their resolved kebab-case component names.
7
+ *
8
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
9
+ * @returns {string[]} An array of discovered kebab-case hydration chunk identifiers.
10
+ */
11
+ export function scanForHydrationIslands(themeRoot) {
12
+ const islands = new Set();
13
+ const filesToScan = [];
14
+
15
+ const appDir = path.join(themeRoot, "src", "app");
16
+ if (existsSync(appDir)) {
17
+ // Scan page.tsx
18
+ const mainPage = path.join(appDir, "page.tsx");
19
+ if (existsSync(mainPage)) filesToScan.push(mainPage);
20
+
21
+ // Scan layout.tsx
22
+ const mainLayout = path.join(appDir, "layout.tsx");
23
+ if (existsSync(mainLayout)) filesToScan.push(mainLayout);
24
+
25
+ // Scan pages/ directory
26
+ const pagesDir = path.join(appDir, "pages");
27
+ if (existsSync(pagesDir)) {
28
+ try {
29
+ const pages = readdirSync(pagesDir).filter((f) => f.endsWith(".tsx"));
30
+ for (const file of pages) {
31
+ filesToScan.push(path.join(pagesDir, file));
32
+ }
33
+ } catch {}
34
+ }
35
+ }
36
+
37
+ // Scan each file for <Hydrate> occurrences
38
+ for (const filePath of filesToScan) {
39
+ try {
40
+ const content = readFileSync(filePath, "utf8");
41
+
42
+ // Matches <Hydrate ...> ... </Hydrate>
43
+ const hydrateRegex = /<Hydrate\b([\s\S]*?)>([\s\S]*?)<\/Hydrate>/g;
44
+ let match;
45
+ while ((match = hydrateRegex.exec(content)) !== null) {
46
+ const propsStr = match[1];
47
+ const childrenStr = match[2].trim();
48
+
49
+ // 1. Try to parse explicit 'id' attribute
50
+ const idMatch = propsStr.match(/id\s*=\s*["']([^"']*)["']/);
51
+ if (idMatch) {
52
+ islands.add(idMatch[1]);
53
+ continue;
54
+ }
55
+
56
+ // 2. Fallback: Parse Component Tag name from children (e.g. <FadeUpSection />)
57
+ const componentTagMatch = childrenStr.match(/<([A-Z][a-zA-Z0-9]*)\b/);
58
+ if (componentTagMatch) {
59
+ const compName = componentTagMatch[1];
60
+ const kebabName = compName
61
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
62
+ .toLowerCase();
63
+ islands.add(kebabName);
64
+ }
65
+ }
66
+ } catch (err) {
67
+ console.warn(`[Hydration Scanner] Failed to scan file ${filePath}:`, err.message);
68
+ }
69
+ }
70
+
71
+ // 3. Smart Component Discovery: scan src/components/ for interactive/animated components
72
+ const compDir = path.join(themeRoot, "src", "components");
73
+ const interactiveComponents = new Set();
74
+
75
+ function scanComponentsRecursive(dir) {
76
+ if (!existsSync(dir)) return;
77
+ try {
78
+ const items = readdirSync(dir, { withFileTypes: true });
79
+ for (const item of items) {
80
+ const fullPath = path.join(dir, item.name);
81
+ if (item.isDirectory()) {
82
+ scanComponentsRecursive(fullPath);
83
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
84
+ try {
85
+ const fileContent = readFileSync(fullPath, "utf8");
86
+ const hasState = fileContent.includes("useState") || fileContent.includes("useEffect") || fileContent.includes("useRef");
87
+ const hasMotion = fileContent.includes("framer-motion") || fileContent.includes("gsap") || fileContent.includes("animate") || fileContent.includes("motion.");
88
+ if (hasState || hasMotion) {
89
+ const compName = path.basename(item.name, path.extname(item.name));
90
+ interactiveComponents.add(compName);
91
+ }
92
+ } catch {}
93
+ }
94
+ }
95
+ } catch {}
96
+ }
97
+
98
+ scanComponentsRecursive(compDir);
99
+
100
+ for (const filePath of filesToScan) {
101
+ try {
102
+ const content = readFileSync(filePath, "utf8");
103
+ for (const compName of interactiveComponents) {
104
+ if (content.includes(`<${compName}`)) {
105
+ const kebabName = compName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
106
+ if (!islands.has(kebabName)) {
107
+ islands.add(kebabName);
108
+ console.log(`\x1b[33m[ForgeWP Optimizer] Smart Discovery: Detected "${compName}" uses interactive hooks/animations. Auto-enforcing code-splitting chunk. Wrap it in <Hydrate> in page markup for dynamic browser activation!\x1b[0m`);
109
+ }
110
+ }
111
+ }
112
+ } catch {}
113
+ }
114
+
115
+ return Array.from(islands);
116
+ }
117
+
118
+ /**
119
+ * Searches components directories for a file matching the kebab-case component name.
120
+ *
121
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
122
+ * @param {string} kebabName - The target component's kebab-case identifier.
123
+ * @returns {string|null} The absolute path to the component file, or null if not found.
124
+ */
125
+ export function findComponentPath(themeRoot, kebabName) {
126
+ const compDirs = [
127
+ path.join(themeRoot, "src", "components"),
128
+ path.join(themeRoot, "src", "components", "ui"),
129
+ ];
130
+
131
+ // Convert kebab-case back to PascalCase and check candidates
132
+ const pascalName = kebabName
133
+ .split("-")
134
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
135
+ .join("");
136
+
137
+ const candidates = [
138
+ `${pascalName}.tsx`,
139
+ `${pascalName}.ts`,
140
+ `${kebabName}.tsx`,
141
+ `${kebabName}.ts`,
142
+ ];
143
+
144
+ for (const dir of compDirs) {
145
+ if (!existsSync(dir)) continue;
146
+ try {
147
+ const files = readdirSync(dir);
148
+ for (const file of files) {
149
+ if (candidates.includes(file)) {
150
+ return path.join(dir, file);
151
+ }
152
+ }
153
+ } catch {}
154
+ }
155
+
156
+ return null;
157
+ }
158
+
159
+ /**
160
+ * Resolves Rollup's multi-entry input mapping for Vite based on discovered hydration islands.
161
+ *
162
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
163
+ * @returns {Record<string, string>} Rollup input object.
164
+ */
165
+ export function getHydrationRollupInputs(themeRoot) {
166
+ const inputs = {
167
+ index: path.resolve(themeRoot, "index.html"),
168
+ };
169
+
170
+ const islands = scanForHydrationIslands(themeRoot);
171
+ for (const island of islands) {
172
+ const compPath = findComponentPath(themeRoot, island);
173
+ if (compPath) {
174
+ inputs[island] = compPath;
175
+ }
176
+ }
177
+
178
+ return inputs;
179
+ }
package/lib/index.d.ts CHANGED
@@ -59,3 +59,9 @@ export function exportTheme(options: {
59
59
  export function loadConfig(themeRoot: string): Promise<ForgeWPThemeConfig>;
60
60
 
61
61
  export function validateCriticalFiles(themeRoot: string): void;
62
+
63
+ export function scanForHydrationIslands(themeRoot: string): string[];
64
+
65
+ export function findComponentPath(themeRoot: string, kebabName: string): string | null;
66
+
67
+ export function getHydrationRollupInputs(themeRoot: string): Record<string, string>;
package/lib/index.js CHANGED
@@ -1,3 +1,6 @@
1
1
  export { exportTheme } from "./export-theme.js";
2
2
  export { loadConfig } from "./load-config.js";
3
3
  export { validateCriticalFiles } from "./validate.js";
4
+ export { scanForHydrationIslands, findComponentPath, getHydrationRollupInputs } from "./hydration-scanner.js";
5
+
6
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forgewp/compiler",
3
- "version": "0.1.9",
3
+ "version": "0.3.0",
4
4
  "description": "Compile ForgeWP React themes into installable WordPress themes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -25,7 +25,7 @@
25
25
  "jiti": "^2.6.1",
26
26
  "picocolors": "^1.1.1",
27
27
  "react-helmet-async": "^3.0.0",
28
- "@forgewp/ui": "0.1.9"
28
+ "@forgewp/ui": "0.3.0"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/node": "^22.19.19"