@forgewp/compiler 0.1.7 → 0.1.8

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.
@@ -1,4 +1,4 @@
1
- import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1
+ import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
4
  /**
@@ -111,10 +111,13 @@ export function generateTheme({
111
111
  writeFileSync(path.join(staticDir, "archive.html"), processedArchive, "utf8");
112
112
  }
113
113
 
114
+ // Dynamic Gutenberg blocks compilation (Phase 5)
115
+ const compiledBlocks = compileBlocks(themeRoot, outDir);
116
+
114
117
  writeFileSync(path.join(outDir, "style.css"), buildStyleCss(config), "utf8");
115
118
  writeFileSync(
116
119
  path.join(outDir, "functions.php"),
117
- buildFunctionsPhp(config, assets),
120
+ buildFunctionsPhp(config, assets, compiledBlocks),
118
121
  "utf8",
119
122
  );
120
123
  writeFileSync(path.join(outDir, "header.php"), buildHeaderPhp(config), "utf8");
@@ -263,6 +266,41 @@ function processMarkup(html) {
263
266
  ''
264
267
  );
265
268
 
269
+ // ── Custom Meta Fields (ACF / metadata support) ──
270
+ processed = processed.replace(
271
+ /__FORGEWP_CUSTOM_FIELD__([a-zA-Z0-9_-]+)__/g,
272
+ "<?php echo esc_html( get_post_meta( get_the_ID(), '$1', true ) ); ?>"
273
+ );
274
+
275
+ // ── Dynamic Custom Menus ──
276
+ processed = processed.replace(
277
+ /<forgewp-menu\s+[^>]*location="([^"]+)"\s+[^>]*className="([^"]*)"\s+[^>]*linkClassName="([^"]*)"\s*\/?>/g,
278
+ '<?php\n $locations = get_nav_menu_locations();\n $menu_id = isset($locations[\'$1\']) ? $locations[\'$1\'] : null;\n $menu_items = $menu_id ? wp_get_nav_menu_items($menu_id) : array();\n if (!empty($menu_items)) {\n echo \'<nav class="$2">\';\n foreach ($menu_items as $item) {\n echo \'<a href="\' . esc_url($item->url) . \'" class="$3">\' . esc_html($item->title) . \'</a>\';\n }\n echo \'</nav>\';\n } else {\n echo \'<nav class="$2"><a href="\' . esc_url(home_url(\'/\')) . \'" class="$3">Home</a></nav>\';\n }\n ?>'
279
+ );
280
+ processed = processed.replace(/<\/forgewp-menu>/g, '');
281
+
282
+ // ── WordPress Shortcodes Support ──
283
+ processed = processed.replace(
284
+ /<forgewp-shortcode\s+[^>]*code="([^"]+)"\s*\/?>/g,
285
+ (match, code) => {
286
+ const decodedCode = code.replace(/&quot;/g, '"').replace(/&#39;/g, "'");
287
+ return `<?php echo do_shortcode('${decodedCode}'); ?>`;
288
+ }
289
+ );
290
+ processed = processed.replace(/<\/forgewp-shortcode>/g, '');
291
+
292
+ // ── Custom WP_Query Loop Blocks ──
293
+ processed = processed.replace(
294
+ /<forgewp-query-loop-start\s+[^>]*post[Tt]ype="([^"]+)"\s+[^>]*posts[Pp]er[Pp]age="([^"]+)"\s*(?:[^>]*category[Nn]ame="([^"]*)")?\s*\/?>/g,
295
+ '<?php\n $query_args = array(\n \'post_type\' => \'$1\',\n \'posts_per_page\' => $2,\n );\n if (\'$3\' !== \'\') {\n $query_args[\'category_name\'] = \'$3\';\n }\n $custom_query = new WP_Query($query_args);\n if ($custom_query->have_posts()) : while ($custom_query->have_posts()) : $custom_query->the_post();\n ?>'
296
+ );
297
+ processed = processed.replace(/<\/forgewp-query-loop-start>/g, '');
298
+ processed = processed.replace(
299
+ /<forgewp-query-loop-end\s*\/?>/g,
300
+ '<?php\n endwhile;\n wp_reset_postdata();\n endif;\n ?>'
301
+ );
302
+ processed = processed.replace(/<\/forgewp-query-loop-end>/g, '');
303
+
266
304
  return processed;
267
305
  }
268
306
 
@@ -293,7 +331,7 @@ Text Domain: ${config.textDomain}
293
331
  * @param {import('./types.js').ForgeWPThemeConfig} config
294
332
  * @param {import('./types.js').ForgeWPBuildAssets} assets
295
333
  */
296
- function buildFunctionsPhp(config, assets) {
334
+ function buildFunctionsPhp(config, assets, blockSlugs = []) {
297
335
  const css = assets.cssFile.replace(/^assets\//, "");
298
336
  const version = config.version.replace(/'/g, "\\'");
299
337
  const googleFonts = config.settings?.typography?.googleFonts || [];
@@ -333,6 +371,23 @@ add_filter('wp_resource_hints', 'forgewp_google_fonts_resource_hints', 10, 2);
333
371
  `;
334
372
  }
335
373
 
374
+ let blocksRegistration = "";
375
+ if (blockSlugs.length > 0) {
376
+ const blocksArray = blockSlugs.map(s => `'${s}'`).join(", ");
377
+ blocksRegistration = `
378
+ /**
379
+ * Register dynamic Gutenberg blocks compiled by ForgeWP.
380
+ */
381
+ function forgewp_register_dynamic_blocks(): void {
382
+ $blocks = array(${blocksArray});
383
+ foreach ($blocks as $block) {
384
+ register_block_type(__DIR__ . '/blocks/' . $block);
385
+ }
386
+ }
387
+ add_action('init', 'forgewp_register_dynamic_blocks');
388
+ `;
389
+ }
390
+
336
391
  return `<?php
337
392
  /**
338
393
  * ${config.name} — generated by ForgeWP
@@ -374,9 +429,12 @@ function forgewp_theme_setup(): void {
374
429
  add_theme_support('html5', array('search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'style', 'script'));
375
430
  add_theme_support('wp-block-styles');
376
431
  add_theme_support('editor-styles');
432
+
433
+ // Load compiled theme stylesheet inside Gutenberg Block Editor
434
+ add_editor_style('assets/${css}');
377
435
  }
378
436
  add_action('after_setup_theme', 'forgewp_theme_setup');
379
- ${preconnectFilter}`;
437
+ ${preconnectFilter}${blocksRegistration}`;
380
438
  }
381
439
 
382
440
  function buildHeaderPhp(config) {
@@ -611,3 +669,128 @@ if (file_exists($page_file)) {
611
669
  get_footer();
612
670
  `;
613
671
  }
672
+
673
+ /**
674
+ * Scans the \`src/blocks/\` folder, parses block settings and JSX content,
675
+ * and compiles them into official, dynamic WordPress blocks.
676
+ *
677
+ * @param {string} themeRoot
678
+ * @param {string} outDir
679
+ * @returns {string[]} Compiled block slugs
680
+ */
681
+ function compileBlocks(themeRoot, outDir) {
682
+ const blocksDir = path.join(themeRoot, "src", "blocks");
683
+ const blockSlugs = [];
684
+
685
+ if (!existsSync(blocksDir)) {
686
+ return blockSlugs;
687
+ }
688
+
689
+ const entries = readdirSync(blocksDir);
690
+ for (const entry of entries) {
691
+ const entryPath = path.join(blocksDir, entry);
692
+ let blockFile = "";
693
+ let blockSlug = "";
694
+
695
+ if (statSync(entryPath).isDirectory()) {
696
+ const indexPath = path.join(entryPath, "index.tsx");
697
+ if (existsSync(indexPath)) {
698
+ blockFile = indexPath;
699
+ blockSlug = entry.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase().replace(/[^a-z0-9]+/g, "-");
700
+ }
701
+ } else if (entry.endsWith(".tsx") || entry.endsWith(".jsx")) {
702
+ blockFile = entryPath;
703
+ blockSlug = entry.replace(/\.(tsx|jsx)$/, "").replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase().replace(/[^a-z0-9]+/g, "-");
704
+ }
705
+
706
+ if (blockFile) {
707
+ try {
708
+ const code = readFileSync(blockFile, "utf8");
709
+
710
+ // Parse human-readable title and metadata from setting exports
711
+ const settingsMatch = code.match(/export\s+const\s+settings\s*=\s*(\{[\s\S]*?\});/);
712
+ let settings = {
713
+ apiVersion: 3,
714
+ name: `forgewp/${blockSlug}`,
715
+ title: blockSlug.split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" "),
716
+ category: "design",
717
+ icon: "admin-generic",
718
+ attributes: {},
719
+ render: "file:./render.php"
720
+ };
721
+
722
+ if (settingsMatch) {
723
+ try {
724
+ // Evaluates settings safely without external libraries
725
+ const evalFn = new Function(`return ${settingsMatch[1]};`);
726
+ settings = { ...settings, ...evalFn() };
727
+ // Ensure schema, apiVersion, name and render path are strictly aligned
728
+ settings.name = `forgewp/${blockSlug}`;
729
+ settings.apiVersion = 3;
730
+ settings.render = "file:./render.php";
731
+ } catch (e) {
732
+ console.warn(`[Gutenberg Block Compiler] Error parsing settings for ${blockSlug}:`, e.message);
733
+ }
734
+ }
735
+
736
+ // Parse JSX block content
737
+ let jsx = "";
738
+ const returnMatch = code.match(/return\s*\(\s*(<[\s\S]*?>)\s*\)/);
739
+ if (returnMatch) {
740
+ jsx = returnMatch[1];
741
+ } else {
742
+ const returnMatchSingle = code.match(/return\s+(<[\s\S]*?>);/);
743
+ if (returnMatchSingle) {
744
+ jsx = returnMatchSingle[1];
745
+ }
746
+ }
747
+
748
+ if (!jsx) {
749
+ console.warn(`[Gutenberg Block Compiler] Skipping block ${blockSlug}: No returning JSX element found.`);
750
+ continue;
751
+ }
752
+
753
+ // Translate dynamic attributes inside returning JSX into dynamic PHP echoes
754
+ let phpMarkup = jsx;
755
+
756
+ // className="..." -> class="..."
757
+ phpMarkup = phpMarkup.replace(/className=/g, "class=");
758
+
759
+ // src={image} or src={attributes.image}
760
+ phpMarkup = phpMarkup.replace(/(src|href|alt|title)=\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/gi, (match, attr, varName) => {
761
+ const escFunc = attr === "href" || attr === "src" ? "esc_url" : "esc_attr";
762
+ return `${attr}="<?php echo ${escFunc}( $attributes['${varName}'] ?? '' ); ?>"`;
763
+ });
764
+
765
+ // {title} or {props.title}
766
+ phpMarkup = phpMarkup.replace(/\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/g, (match, varName) => {
767
+ return `<?php echo esc_html( $attributes['${varName}'] ?? '' ); ?>`;
768
+ });
769
+
770
+ // Wrap the final PHP template markup in a clean block wrapper
771
+ const renderPhpContent = `<?php
772
+ /**
773
+ * Gutenberg dynamic block template — ${settings.title}
774
+ * Autogenerated by ForgeWP Theme Compiler. Do not modify manually.
775
+ */
776
+ ?>
777
+ ${phpMarkup}
778
+ `;
779
+
780
+ const blockOutDir = path.join(outDir, "blocks", blockSlug);
781
+ mkdirSync(blockOutDir, { recursive: true });
782
+
783
+ // Write block.json and render.php
784
+ writeFileSync(path.join(blockOutDir, "block.json"), JSON.stringify(settings, null, 2), "utf8");
785
+ writeFileSync(path.join(blockOutDir, "render.php"), renderPhpContent, "utf8");
786
+
787
+ blockSlugs.push(blockSlug);
788
+ } catch (e) {
789
+ console.error(`[Gutenberg Block Compiler] Failed to compile block ${blockSlug}:`, e.message);
790
+ }
791
+ }
792
+ }
793
+
794
+ return blockSlugs;
795
+ }
796
+
package/lib/index.d.ts CHANGED
@@ -22,6 +22,7 @@ export interface ForgeWPThemeConfig {
22
22
  version: string;
23
23
  description: string;
24
24
  textDomain: string;
25
+ style?: "forgewp" | "shadcn";
25
26
  settings?: {
26
27
  layout?: {
27
28
  contentSize?: string;
package/package.json CHANGED
@@ -1,12 +1,11 @@
1
1
  {
2
2
  "name": "@forgewp/compiler",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "Compile ForgeWP React themes into installable WordPress themes",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "bin": {
8
- "forgewp-export": "./bin/export.js",
9
- "forgewp-add": "./bin/add.js"
8
+ "forgewp": "./bin/cli.js"
10
9
  },
11
10
  "exports": {
12
11
  ".": {
@@ -26,7 +25,7 @@
26
25
  "jiti": "^2.6.1",
27
26
  "picocolors": "^1.1.1",
28
27
  "react-helmet-async": "^3.0.0",
29
- "@forgewp/registry": "0.1.7"
28
+ "@forgewp/registry": "0.1.8"
30
29
  },
31
30
  "devDependencies": {
32
31
  "@types/node": "^22.19.19"