@forgewp/compiler 0.1.8 → 0.2.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.
@@ -31,20 +31,95 @@ export function generateTheme({
31
31
 
32
32
  mkdirSync(outDir, { recursive: true });
33
33
 
34
+ // Load menus configuration for auto-registration and setup
35
+ let menus = {};
36
+ const menusJsonSrc = path.join(themeRoot, "wordpress", "menus.json");
37
+ if (existsSync(menusJsonSrc)) {
38
+ try {
39
+ menus = JSON.parse(readFileSync(menusJsonSrc, "utf8"));
40
+ } catch (e) {
41
+ console.warn("Failed to parse menus.json:", e.message);
42
+ }
43
+ }
44
+
45
+ // Gather compiled custom page templates for auto-creation with smart slug mapping
46
+ const pagesToAutoCreate = [];
47
+ const forgewpDir = path.join(themeRoot, ".forgewp");
48
+ if (existsSync(forgewpDir)) {
49
+ const templateFiles = readdirSync(forgewpDir);
50
+ for (const file of templateFiles) {
51
+ if (file.startsWith("template-") && file.endsWith(".html") && !file.includes("-head")) {
52
+ const slug = file.replace(".html", "");
53
+ const pageTemplateSlug = slug.replace("template-", "");
54
+
55
+ let matchedSlug = null;
56
+ let matchedTitle = null;
57
+
58
+ const toKebabTemplateSlug = (str) => {
59
+ const compName = str
60
+ .replace(/[^a-zA-Z0-9]/g, " ")
61
+ .trim()
62
+ .split(/\s+/)
63
+ .map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
64
+ .join("") + "Page";
65
+ return compName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
66
+ };
67
+
68
+ const targetKebab = pageTemplateSlug;
69
+
70
+ // Search in menus to find matching target URL slugs defined by the developer
71
+ for (const [location, items] of Object.entries(menus)) {
72
+ if (!Array.isArray(items)) continue;
73
+ for (const item of items) {
74
+ if (!item.url || !item.url.startsWith("/")) continue;
75
+ const menuUrlSlug = item.url.replace(/^\//, "");
76
+
77
+ if (
78
+ toKebabTemplateSlug(item.title) === targetKebab ||
79
+ toKebabTemplateSlug(menuUrlSlug) === targetKebab
80
+ ) {
81
+ matchedSlug = menuUrlSlug;
82
+ matchedTitle = item.title;
83
+ break;
84
+ }
85
+ }
86
+ if (matchedSlug) break;
87
+ }
88
+
89
+ // Fallback 1: Strip trailing "-page" from template slug
90
+ if (!matchedSlug) {
91
+ matchedSlug = pageTemplateSlug.endsWith("-page")
92
+ ? pageTemplateSlug.slice(0, -5)
93
+ : pageTemplateSlug;
94
+ }
95
+
96
+ // Fallback 2: Generate clean human-readable title
97
+ if (!matchedTitle) {
98
+ const cleanName = pageTemplateSlug.endsWith("-page") ? pageTemplateSlug.slice(0, -5) : pageTemplateSlug;
99
+ matchedTitle = cleanName.split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
100
+ }
101
+
102
+ pagesToAutoCreate.push({
103
+ title: matchedTitle,
104
+ slug: matchedSlug,
105
+ template: `page-${pageTemplateSlug}.php`
106
+ });
107
+ }
108
+ }
109
+ }
110
+
34
111
  const assetsOut = path.join(outDir, "assets");
35
112
  const distAssets = path.join(themeRoot, "dist", "assets");
36
113
  mkdirSync(assetsOut, { recursive: true });
37
114
  cpSync(distAssets, assetsOut, { recursive: true });
38
115
 
39
116
  // Drop unused JS from the theme ZIP
40
- import("node:fs").then(({ readdirSync, unlinkSync }) => {
41
- const files = readdirSync(assetsOut);
42
- for (const file of files) {
43
- if (file.endsWith(".js") || file.endsWith(".js.map")) {
44
- unlinkSync(path.join(assetsOut, file));
45
- }
117
+ const files = readdirSync(assetsOut);
118
+ for (const file of files) {
119
+ if ((file.endsWith(".js") || file.endsWith(".js.map")) && file !== "forgewp-editor.js") {
120
+ rmSync(path.join(assetsOut, file), { force: true });
46
121
  }
47
- });
122
+ }
48
123
 
49
124
  // Fix nav links and split markup
50
125
  const processedApp = processMarkup(appHtml);
@@ -114,10 +189,56 @@ export function generateTheme({
114
189
  // Dynamic Gutenberg blocks compilation (Phase 5)
115
190
  const compiledBlocks = compileBlocks(themeRoot, outDir);
116
191
 
192
+ const editorScriptContent = `
193
+ const { registerBlockType } = wp.blocks;
194
+ const { createElement } = wp.element;
195
+ const { InspectorControls, useBlockProps } = wp.blockEditor;
196
+ const { PanelBody, TextControl } = wp.components;
197
+ const ServerSideRender = wp.serverSideRender;
198
+
199
+ if (window.forgeWpBlocks) {
200
+ window.forgeWpBlocks.forEach(block => {
201
+ registerBlockType(block.name, {
202
+ title: block.title,
203
+ icon: block.icon,
204
+ category: block.category,
205
+ attributes: block.attributes,
206
+ edit: function(props) {
207
+ const { attributes, setAttributes } = props;
208
+ const blockProps = useBlockProps();
209
+
210
+ // Build inspector controls dynamically from attributes
211
+ const controls = Object.keys(block.attributes).map(key => {
212
+ return createElement(TextControl, {
213
+ label: key.charAt(0).toUpperCase() + key.slice(1),
214
+ value: attributes[key],
215
+ onChange: (val) => setAttributes({ [key]: val })
216
+ });
217
+ });
218
+
219
+ return createElement('div', blockProps,
220
+ createElement(InspectorControls, null,
221
+ createElement(PanelBody, { title: 'Block Settings', initialOpen: true }, controls)
222
+ ),
223
+ createElement(ServerSideRender, {
224
+ block: block.name,
225
+ attributes: attributes
226
+ })
227
+ );
228
+ },
229
+ save: function() {
230
+ return null; // Dynamic blocks return null in save
231
+ }
232
+ });
233
+ });
234
+ }
235
+ `;
236
+ writeFileSync(path.join(outDir, "assets", "forgewp-editor.js"), editorScriptContent, "utf8");
237
+
117
238
  writeFileSync(path.join(outDir, "style.css"), buildStyleCss(config), "utf8");
118
239
  writeFileSync(
119
240
  path.join(outDir, "functions.php"),
120
- buildFunctionsPhp(config, assets, compiledBlocks),
241
+ buildFunctionsPhp(config, assets, compiledBlocks, themeRoot, pagesToAutoCreate, menus),
121
242
  "utf8",
122
243
  );
123
244
  writeFileSync(path.join(outDir, "header.php"), buildHeaderPhp(config), "utf8");
@@ -129,6 +250,48 @@ export function generateTheme({
129
250
  writeFileSync(path.join(outDir, "archive.php"), buildArchivePhp(), "utf8");
130
251
  writeFileSync(path.join(outDir, "page.php"), buildPagePhp(), "utf8");
131
252
 
253
+ // Dynamic Custom Page Templates Compiler
254
+ if (existsSync(forgewpDir)) {
255
+ const templateFiles = readdirSync(forgewpDir);
256
+ for (const file of templateFiles) {
257
+ if (file.startsWith("template-") && file.endsWith(".html") && !file.includes("-head")) {
258
+ const slug = file.replace(".html", "");
259
+ const rawHtml = readFileSync(path.join(forgewpDir, file), "utf8");
260
+
261
+ let processedHtml = processMarkup(rawHtml);
262
+ if (processedHeader) processedHtml = processedHtml.replace(processedHeader, "");
263
+ if (processedFooter) processedHtml = processedHtml.replace(processedFooter, "");
264
+
265
+ writeFileSync(path.join(staticDir, file), processedHtml, "utf8");
266
+
267
+ const headFile = file.replace(".html", "-head.html");
268
+ if (existsSync(path.join(forgewpDir, headFile))) {
269
+ writeFileSync(path.join(staticDir, headFile), readFileSync(path.join(forgewpDir, headFile), "utf8"), "utf8");
270
+ }
271
+
272
+ // Generate the native WordPress PHP Custom Page Template
273
+ const templateName = slug.replace("template-", "").split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
274
+ const phpContent = `<?php
275
+ /**
276
+ * Template Name: ${templateName}
277
+ *
278
+ * @package ${config.textDomain}
279
+ */
280
+
281
+ get_header();
282
+
283
+ $markup_file = get_template_directory() . '/forgewp-static/${file}';
284
+ if (file_exists($markup_file)) {
285
+ include $markup_file;
286
+ }
287
+
288
+ get_footer();
289
+ `;
290
+ writeFileSync(path.join(outDir, `page-${slug.replace("template-", "")}.php`), phpContent, "utf8");
291
+ }
292
+ }
293
+ }
294
+
132
295
  // Dynamic theme.json compiler (Phase 5)
133
296
  const themeJsonSrc = path.join(themeRoot, "wordpress", "theme.json");
134
297
  let themeJson = {
@@ -331,11 +494,51 @@ Text Domain: ${config.textDomain}
331
494
  * @param {import('./types.js').ForgeWPThemeConfig} config
332
495
  * @param {import('./types.js').ForgeWPBuildAssets} assets
333
496
  */
334
- function buildFunctionsPhp(config, assets, blockSlugs = []) {
497
+ function buildFunctionsPhp(config, assets, blockSlugs = [], themeRoot = "", pagesToAutoCreate = [], menus = {}) {
335
498
  const css = assets.cssFile.replace(/^assets\//, "");
336
499
  const version = config.version.replace(/'/g, "\\'");
337
500
  const googleFonts = config.settings?.typography?.googleFonts || [];
338
501
 
502
+ let cptRegistration = "";
503
+ try {
504
+ const mockDataPath = path.join(themeRoot, "wordpress", "mock-data.json");
505
+ if (existsSync(mockDataPath)) {
506
+ const mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
507
+ const postTypes = Object.keys(mockData).filter(k => k !== "posts" && k !== "pages" && k !== "post" && k !== "page" && k !== "menus");
508
+ if (postTypes.length > 0) {
509
+ cptRegistration = `
510
+ /**
511
+ * Register dynamic Custom Post Types inferred from local mock data.
512
+ */
513
+ function forgewp_register_custom_post_types() {
514
+ ${postTypes.map(pt => ` register_post_type('${pt}', array(
515
+ 'labels' => array(
516
+ 'name' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
517
+ 'singular_name' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}',
518
+ 'menu_name' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
519
+ 'name_admin_bar' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}',
520
+ 'add_new' => 'Add New',
521
+ 'add_new_item' => 'Add New ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
522
+ 'new_item' => 'New ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
523
+ 'edit_item' => 'Edit ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
524
+ 'view_item' => 'View ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
525
+ 'all_items' => 'All ${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
526
+ 'search_items' => 'Search ${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
527
+ 'not_found' => 'No ${pt.charAt(0).toUpperCase() + pt.slice(1)}s found.',
528
+ ),
529
+ 'public' => true,
530
+ 'has_archive' => true,
531
+ 'show_in_rest'=> true,
532
+ 'supports' => array('title', 'editor', 'thumbnail', 'custom-fields', 'excerpt'),
533
+ 'menu_icon' => 'dashicons-admin-post',
534
+ ));`).join("\n")}
535
+ }
536
+ add_action('init', 'forgewp_register_custom_post_types');
537
+ `;
538
+ }
539
+ }
540
+ } catch (e) {}
541
+
339
542
  let fontsEnqueue = "";
340
543
  let preconnectFilter = "";
341
544
 
@@ -379,15 +582,158 @@ add_filter('wp_resource_hints', 'forgewp_google_fonts_resource_hints', 10, 2);
379
582
  * Register dynamic Gutenberg blocks compiled by ForgeWP.
380
583
  */
381
584
  function forgewp_register_dynamic_blocks(): void {
382
- $blocks = array(${blocksArray});
585
+ $blocks = array(${blockSlugs.map(s => `'${s.name.replace("forgewp/", "")}'`).join(", ")});
383
586
  foreach ($blocks as $block) {
384
587
  register_block_type(__DIR__ . '/blocks/' . $block);
385
588
  }
386
589
  }
387
590
  add_action('init', 'forgewp_register_dynamic_blocks');
591
+
592
+ /**
593
+ * Enqueue Block Editor JavaScript to dynamically render block interfaces.
594
+ */
595
+ function forgewp_enqueue_block_editor_assets(): void {
596
+ wp_enqueue_script(
597
+ 'forgewp-editor-script',
598
+ get_template_directory_uri() . '/assets/forgewp-editor.js',
599
+ array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render'),
600
+ FORGEWP_THEME_VERSION,
601
+ true
602
+ );
603
+
604
+ wp_localize_script(
605
+ 'forgewp-editor-script',
606
+ 'forgeWpBlocks',
607
+ json_decode('${JSON.stringify(blockSlugs)}')
608
+ );
609
+ }
610
+ add_action('enqueue_block_editor_assets', 'forgewp_enqueue_block_editor_assets');
388
611
  `;
389
612
  }
390
613
 
614
+ let registerMenusPhp = "";
615
+ const menuLocations = Object.keys(menus).filter(k => !k.startsWith("_"));
616
+ if (menuLocations.length > 0) {
617
+ registerMenusPhp = `
618
+ // Register custom navigation menus from sitemap config
619
+ register_nav_menus(array(
620
+ ${menuLocations.map(loc => ` '${loc}' => __('${loc.charAt(0).toUpperCase() + loc.slice(1)} Navigation', '${config.textDomain}'),`).join("\n")}
621
+ ));`;
622
+ }
623
+
624
+ const pagesPhpArray = pagesToAutoCreate.map(p => {
625
+ return ` array(
626
+ 'title' => '${p.title.replace(/'/g, "\\'")}',
627
+ 'slug' => '${p.slug.replace(/'/g, "\\'")}',
628
+ 'template' => '${p.template.replace(/'/g, "\\'")}',
629
+ )`;
630
+ }).join(",\n");
631
+
632
+ const menuItemsPhpArray = Object.entries(menus)
633
+ .filter(([loc]) => !loc.startsWith("_"))
634
+ .map(([loc, items]) => {
635
+ const itemsPhp = items.map(item => {
636
+ return ` array(
637
+ 'title' => '${item.title.replace(/'/g, "\\'")}',
638
+ 'url' => '${item.url.replace(/'/g, "\\'")}',
639
+ )`;
640
+ }).join(",\n");
641
+ return ` '${loc}' => array(
642
+ ${itemsPhp}
643
+ )`;
644
+ }).join(",\n");
645
+
646
+ const autoCreationPhp = `
647
+ /**
648
+ * Automatically create routes defined in menus.json and assign custom page templates upon theme activation.
649
+ */
650
+ function forgewp_auto_create_pages_and_menus(): void {
651
+ $activated_option = '${config.textDomain}_activated_' . str_replace('.', '_', FORGEWP_THEME_VERSION);
652
+ if (get_option($activated_option) === 'yes') {
653
+ return;
654
+ }
655
+
656
+ $pages = array(
657
+ ${pagesPhpArray}
658
+ );
659
+
660
+ foreach ($pages as $p) {
661
+ $existing_page = get_page_by_path($p['slug']);
662
+ if (!$existing_page) {
663
+ $page_id = wp_insert_post(array(
664
+ 'post_title' => $p['title'],
665
+ 'post_name' => $p['slug'],
666
+ 'post_status' => 'publish',
667
+ 'post_type' => 'page',
668
+ ));
669
+ if (!is_wp_error($page_id) && $page_id > 0) {
670
+ update_post_meta($page_id, '_wp_page_template', $p['template']);
671
+ }
672
+ } else {
673
+ update_post_meta($existing_page->ID, '_wp_page_template', $p['template']);
674
+ }
675
+ }
676
+
677
+ $menu_structure = array(
678
+ ${menuItemsPhpArray}
679
+ );
680
+
681
+ foreach ($menu_structure as $location => $items) {
682
+ $menu_name = ucfirst($location) . ' Navigation';
683
+ $menu_exists = wp_get_nav_menu_object($menu_name);
684
+
685
+ if (!$menu_exists) {
686
+ $menu_id = wp_create_nav_menu($menu_name);
687
+ if (!is_wp_error($menu_id)) {
688
+ $locations = get_theme_mod('nav_menu_locations');
689
+ if (!is_array($locations)) {
690
+ $locations = array();
691
+ }
692
+ $locations[$location] = $menu_id;
693
+ set_theme_mod('nav_menu_locations', $locations);
694
+
695
+ foreach ($items as $item) {
696
+ $item_title = $item['title'];
697
+ $item_url = $item['url'];
698
+
699
+ $object_id = 0;
700
+ $object_type = 'custom';
701
+ $target_url = $item_url;
702
+
703
+ if (strpos($item_url, '/') === 0) {
704
+ $slug = trim($item_url, '/');
705
+ if ($slug === '') {
706
+ $target_url = home_url('/');
707
+ } else {
708
+ $page = get_page_by_path($slug);
709
+ if ($page) {
710
+ $object_id = $page->ID;
711
+ $object_type = 'page';
712
+ $target_url = get_permalink($page->ID);
713
+ } else {
714
+ $target_url = home_url($item_url);
715
+ }
716
+ }
717
+ }
718
+
719
+ wp_update_nav_menu_item($menu_id, 0, array(
720
+ 'menu-item-title' => $item_title,
721
+ 'menu-item-url' => $target_url,
722
+ 'menu-item-object-id' => $object_id,
723
+ 'menu-item-object' => $object_type === 'page' ? 'page' : '',
724
+ 'menu-item-type' => $object_type === 'page' ? 'post_type' : 'custom',
725
+ 'menu-item-status' => 'publish',
726
+ ));
727
+ }
728
+ }
729
+ }
730
+ }
731
+
732
+ update_option($activated_option, 'yes');
733
+ }
734
+ add_action('after_switch_theme', 'forgewp_auto_create_pages_and_menus');
735
+ `;
736
+
391
737
  return `<?php
392
738
  /**
393
739
  * ${config.name} — generated by ForgeWP
@@ -432,9 +778,10 @@ function forgewp_theme_setup(): void {
432
778
 
433
779
  // Load compiled theme stylesheet inside Gutenberg Block Editor
434
780
  add_editor_style('assets/${css}');
781
+ ${registerMenusPhp}
435
782
  }
436
783
  add_action('after_setup_theme', 'forgewp_theme_setup');
437
- ${preconnectFilter}${blocksRegistration}`;
784
+ ${preconnectFilter}${blocksRegistration}${cptRegistration}${autoCreationPhp}`;
438
785
  }
439
786
 
440
787
  function buildHeaderPhp(config) {
@@ -784,7 +1131,7 @@ ${phpMarkup}
784
1131
  writeFileSync(path.join(blockOutDir, "block.json"), JSON.stringify(settings, null, 2), "utf8");
785
1132
  writeFileSync(path.join(blockOutDir, "render.php"), renderPhpContent, "utf8");
786
1133
 
787
- blockSlugs.push(blockSlug);
1134
+ blockSlugs.push(settings);
788
1135
  } catch (e) {
789
1136
  console.error(`[Gutenberg Block Compiler] Failed to compile block ${blockSlug}:`, e.message);
790
1137
  }
@@ -43,6 +43,10 @@ export async function renderStaticMarkup(themeRoot) {
43
43
  const detail = result.stderr?.trim() || result.stdout?.trim() || "Unknown error";
44
44
  throw new Error(`Static render failed:\n${detail}`);
45
45
  }
46
+
47
+ if (result.stderr) {
48
+ console.warn(result.stderr);
49
+ }
46
50
 
47
51
  const outDir = result.stdout?.trim() || path.join(themeRoot, ".forgewp");
48
52
  const appHtmlPath = path.join(outDir, "app.html");
@@ -13,6 +13,7 @@ if (!themeRoot) {
13
13
  // Use the theme's own node_modules for ALL packages (React 19)
14
14
  const require = createRequire(path.join(themeRoot, "package.json"));
15
15
  const React = require("react");
16
+ globalThis.React = React; // Polyfill for classic JSX transform in Node.js
16
17
  const { renderToStaticMarkup } = require("react-dom/server");
17
18
 
18
19
  const appUrl = pathToFileURL(path.join(themeRoot, "src", "app", "page.tsx")).href;
@@ -197,4 +198,35 @@ if (singleHtml) writeFileSync(path.join(outDir, "single.html"), singleHtml, "utf
197
198
  if (notFoundHtml) writeFileSync(path.join(outDir, "404.html"), notFoundHtml, "utf8");
198
199
  if (archiveHtml) writeFileSync(path.join(outDir, "archive.html"), archiveHtml, "utf8");
199
200
 
201
+ // ── Compile Custom Page Templates ──────────────────────────────────────────────
202
+ const pagesDir = path.join(themeRoot, "src", "app", "pages");
203
+ console.warn("CHECKING PAGES DIR: " + pagesDir + " EXISTS: " + existsSync(pagesDir));
204
+ if (existsSync(pagesDir)) {
205
+ const { readdirSync } = require("node:fs");
206
+ const pages = readdirSync(pagesDir).filter(f => f.endsWith(".tsx"));
207
+
208
+ for (const pageFile of pages) {
209
+ const pagePath = path.join(pagesDir, pageFile);
210
+ console.warn(`Attempting to compile template: ${pageFile}`);
211
+ try {
212
+ const module = await import(pathToFileURL(pagePath).href);
213
+ const CustomPage = module.default || Object.values(module)[0];
214
+ if (CustomPage) {
215
+ const customHtml = renderPage(CustomPage);
216
+ const pageName = pageFile.replace(".tsx", "");
217
+ const slug = pageName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
218
+ writeFileSync(path.join(outDir, `template-${slug}.html`), customHtml, "utf8");
219
+ console.warn(`WROTE template-${slug}.html to ${outDir}`);
220
+
221
+ const customSeo = extractSeoPropsFromSource(pagePath);
222
+ const customHeadHtml = buildHeadHtml(layoutSeo, customSeo);
223
+ writeFileSync(path.join(outDir, `template-${slug}-head.html`), customHeadHtml, "utf8");
224
+ console.warn(`WROTE template-${slug}-head.html to ${outDir}`);
225
+ }
226
+ } catch (e) {
227
+ console.warn(`Failed to render custom page ${pageFile}:`, e.message);
228
+ }
229
+ }
230
+ }
231
+
200
232
  process.stdout.write(outDir);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forgewp/compiler",
3
- "version": "0.1.8",
3
+ "version": "0.2.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/registry": "0.1.8"
28
+ "@forgewp/ui": "0.2.0"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/node": "^22.19.19"