@forgewp/compiler 0.1.2 → 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, 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
  /**
@@ -18,6 +18,11 @@ export function generateTheme({
18
18
  appHtml,
19
19
  headerHtml = "",
20
20
  footerHtml = "",
21
+ headHtml = "",
22
+ singleHeadHtml = "",
23
+ singleHtml = "",
24
+ notFoundHtml = "",
25
+ archiveHtml = "",
21
26
  assets,
22
27
  }) {
23
28
  if (existsSync(outDir)) {
@@ -55,29 +60,128 @@ export function generateTheme({
55
60
  contentHtml = contentHtml.replace(processedFooter, "");
56
61
  }
57
62
 
63
+ // Process single post template if exists
64
+ let processedSingle = "";
65
+ if (singleHtml) {
66
+ processedSingle = processMarkup(singleHtml);
67
+ if (processedHeader) {
68
+ processedSingle = processedSingle.replace(processedHeader, "");
69
+ }
70
+ if (processedFooter) {
71
+ processedSingle = processedSingle.replace(processedFooter, "");
72
+ }
73
+ }
74
+
75
+ // Process 404 template if exists
76
+ let processedNotFound = "";
77
+ if (notFoundHtml) {
78
+ processedNotFound = processMarkup(notFoundHtml);
79
+ if (processedHeader) {
80
+ processedNotFound = processedNotFound.replace(processedHeader, "");
81
+ }
82
+ if (processedFooter) {
83
+ processedNotFound = processedNotFound.replace(processedFooter, "");
84
+ }
85
+ }
86
+
58
87
  const staticDir = path.join(outDir, "forgewp-static");
59
88
  mkdirSync(staticDir, { recursive: true });
60
89
  writeFileSync(path.join(staticDir, "content.html"), contentHtml, "utf8");
61
90
  writeFileSync(path.join(staticDir, "header.html"), processedHeader, "utf8");
62
91
  writeFileSync(path.join(staticDir, "footer.html"), processedFooter, "utf8");
92
+ if (headHtml) {
93
+ writeFileSync(path.join(staticDir, "head.html"), headHtml, "utf8");
94
+ }
95
+ if (singleHeadHtml) {
96
+ writeFileSync(path.join(staticDir, "single-head.html"), singleHeadHtml, "utf8");
97
+ }
98
+ if (processedSingle) {
99
+ writeFileSync(path.join(staticDir, "single.html"), processedSingle, "utf8");
100
+ }
101
+ if (processedNotFound) {
102
+ writeFileSync(path.join(staticDir, "404.html"), processedNotFound, "utf8");
103
+ }
104
+
105
+ // Archive page (category / tag / date archives)
106
+ let processedArchive = "";
107
+ if (archiveHtml) {
108
+ processedArchive = processMarkup(archiveHtml);
109
+ if (processedHeader) processedArchive = processedArchive.replace(processedHeader, "");
110
+ if (processedFooter) processedArchive = processedArchive.replace(processedFooter, "");
111
+ writeFileSync(path.join(staticDir, "archive.html"), processedArchive, "utf8");
112
+ }
113
+
114
+ // Dynamic Gutenberg blocks compilation (Phase 5)
115
+ const compiledBlocks = compileBlocks(themeRoot, outDir);
63
116
 
64
117
  writeFileSync(path.join(outDir, "style.css"), buildStyleCss(config), "utf8");
65
118
  writeFileSync(
66
119
  path.join(outDir, "functions.php"),
67
- buildFunctionsPhp(config, assets),
120
+ buildFunctionsPhp(config, assets, compiledBlocks),
68
121
  "utf8",
69
122
  );
70
123
  writeFileSync(path.join(outDir, "header.php"), buildHeaderPhp(config), "utf8");
71
124
  writeFileSync(path.join(outDir, "footer.php"), buildFooterPhp(config), "utf8");
72
125
  writeFileSync(path.join(outDir, "index.php"), buildIndexPhp(), "utf8");
73
126
  writeFileSync(path.join(outDir, "single.php"), buildSinglePhp(), "utf8");
127
+ writeFileSync(path.join(outDir, "404.php"), build404Php(), "utf8");
74
128
  writeFileSync(path.join(outDir, "front-page.php"), buildIndexPhp(), "utf8");
129
+ writeFileSync(path.join(outDir, "archive.php"), buildArchivePhp(), "utf8");
130
+ writeFileSync(path.join(outDir, "page.php"), buildPagePhp(), "utf8");
75
131
 
132
+ // Dynamic theme.json compiler (Phase 5)
76
133
  const themeJsonSrc = path.join(themeRoot, "wordpress", "theme.json");
134
+ let themeJson = {
135
+ "$schema": "https://schemas.wp.org/trunk/theme.json",
136
+ "version": 3,
137
+ "settings": {
138
+ "appearanceTools": true,
139
+ },
140
+ };
141
+
77
142
  if (existsSync(themeJsonSrc)) {
78
- copyFileSync(themeJsonSrc, path.join(outDir, "theme.json"));
143
+ try {
144
+ themeJson = JSON.parse(readFileSync(themeJsonSrc, "utf8"));
145
+ } catch (e) {
146
+ console.warn("Failed to parse theme.json template:", e.message);
147
+ }
148
+ }
149
+
150
+ // Merge tokens from wp.config.ts
151
+ if (config.settings) {
152
+ if (!themeJson.settings) themeJson.settings = {};
153
+
154
+ // Layout (contentSize, wideSize)
155
+ if (config.settings.layout) {
156
+ themeJson.settings.layout = {
157
+ ...themeJson.settings.layout,
158
+ ...config.settings.layout,
159
+ };
160
+ }
161
+
162
+ // Colors (custom, palette)
163
+ if (config.settings.color) {
164
+ themeJson.settings.color = {
165
+ ...themeJson.settings.color,
166
+ ...config.settings.color,
167
+ };
168
+ }
169
+
170
+ // Typography (fontSizes, fontFamilies)
171
+ if (config.settings.typography) {
172
+ themeJson.settings.typography = {
173
+ ...themeJson.settings.typography,
174
+ ...config.settings.typography,
175
+ };
176
+ }
79
177
  }
80
178
 
179
+ writeFileSync(
180
+ path.join(outDir, "theme.json"),
181
+ JSON.stringify(themeJson, null, 2),
182
+ "utf8"
183
+ );
184
+
81
185
  const screenshot = path.join(themeRoot, "wordpress", "screenshot.png");
82
186
  if (existsSync(screenshot)) {
83
187
  copyFileSync(screenshot, path.join(outDir, "screenshot.png"));
@@ -92,12 +196,115 @@ function processMarkup(html) {
92
196
  // Fix nav links — # → <?php echo esc_url( home_url( '/' ) ); ?>
93
197
  // We use a placeholder and replace it in the PHP file generation if needed,
94
198
  // but for now we'll do it via string replacement in the template files.
95
- return html.replace(
199
+ let processed = html.replace(
96
200
  /href="#"/g,
97
201
  'href="<?php echo esc_url( home_url( \'/\' ) ); ?>"',
98
202
  );
203
+
204
+ processed = processed.replace(
205
+ /__FORGEWP_THE_TITLE__/g,
206
+ '<?php the_title(); ?>'
207
+ );
208
+
209
+ processed = processed.replace(
210
+ /__FORGEWP_THE_CONTENT__/g,
211
+ '<?php the_content(); ?>'
212
+ );
213
+
214
+ processed = processed.replace(
215
+ /__FORGEWP_THE_PERMALINK__/g,
216
+ '<?php the_permalink(); ?>'
217
+ );
218
+
219
+ processed = processed.replace(
220
+ /__FORGEWP_THE_EXCERPT__/g,
221
+ '<?php the_excerpt(); ?>'
222
+ );
223
+
224
+ processed = processed.replace(
225
+ /__FORGEWP_THE_DATE__/g,
226
+ "<?php echo esc_html( get_the_date() ); ?>"
227
+ );
228
+
229
+ processed = processed.replace(
230
+ /__FORGEWP_THE_AUTHOR__/g,
231
+ "<?php echo esc_html( get_the_author() ); ?>"
232
+ );
233
+
234
+ processed = processed.replace(
235
+ /__FORGEWP_THE_POST_THUMBNAIL_URL__/g,
236
+ "<?php echo esc_url( get_the_post_thumbnail_url( null, 'large' ) ); ?>"
237
+ );
238
+
239
+ processed = processed.replace(
240
+ /__FORGEWP_THE_CATEGORY_LIST__/g,
241
+ "<?php the_category( ', ' ); ?>"
242
+ );
243
+
244
+ processed = processed.replace(
245
+ /__FORGEWP_THE_ARCHIVE_TITLE__/g,
246
+ "<?php the_archive_title(); ?>"
247
+ );
248
+
249
+ processed = processed.replace(
250
+ /<forgewp-loop-start\s*\/?>/g,
251
+ '<?php if (have_posts()) : while (have_posts()) : the_post(); ?>'
252
+ );
253
+
254
+ processed = processed.replace(
255
+ /<\/forgewp-loop-start>/g,
256
+ ''
257
+ );
258
+
259
+ processed = processed.replace(
260
+ /<forgewp-loop-end\s*\/?>/g,
261
+ '<?php endwhile; else : echo "<p>No posts found.</p>"; endif; ?>'
262
+ );
263
+
264
+ processed = processed.replace(
265
+ /<\/forgewp-loop-end>/g,
266
+ ''
267
+ );
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
+
304
+ return processed;
99
305
  }
100
306
 
307
+
101
308
  /**
102
309
  * @param {import('./types.js').ForgeWPThemeConfig} config
103
310
  */
@@ -124,9 +331,62 @@ Text Domain: ${config.textDomain}
124
331
  * @param {import('./types.js').ForgeWPThemeConfig} config
125
332
  * @param {import('./types.js').ForgeWPBuildAssets} assets
126
333
  */
127
- function buildFunctionsPhp(config, assets) {
334
+ function buildFunctionsPhp(config, assets, blockSlugs = []) {
128
335
  const css = assets.cssFile.replace(/^assets\//, "");
129
336
  const version = config.version.replace(/'/g, "\\'");
337
+ const googleFonts = config.settings?.typography?.googleFonts || [];
338
+
339
+ let fontsEnqueue = "";
340
+ let preconnectFilter = "";
341
+
342
+ if (googleFonts.length > 0) {
343
+ const fontsParam = googleFonts.map(f => encodeURIComponent(f)).join("&family=");
344
+ fontsEnqueue = `
345
+ // Enqueue Google Fonts (dynamic preset via wp.config.ts)
346
+ wp_enqueue_style(
347
+ '${config.textDomain}-google-fonts',
348
+ 'https://fonts.googleapis.com/css2?family=${fontsParam}&display=swap',
349
+ array(),
350
+ null
351
+ );`;
352
+
353
+ preconnectFilter = `
354
+ /**
355
+ * Add preconnect resource hints for Google Fonts performance.
356
+ */
357
+ function forgewp_google_fonts_resource_hints(array $urls, string $relation_type): array {
358
+ if (wp_style_is('${config.textDomain}-google-fonts', 'queue') && 'preconnect' === $relation_type) {
359
+ $urls[] = array(
360
+ 'href' => 'https://fonts.googleapis.com',
361
+ 'crossorigin' => 'anonymous',
362
+ );
363
+ $urls[] = array(
364
+ 'href' => 'https://fonts.gstatic.com',
365
+ 'crossorigin' => 'anonymous',
366
+ );
367
+ }
368
+ return $urls;
369
+ }
370
+ add_filter('wp_resource_hints', 'forgewp_google_fonts_resource_hints', 10, 2);
371
+ `;
372
+ }
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
+ }
130
390
 
131
391
  return `<?php
132
392
  /**
@@ -142,11 +402,12 @@ if (! defined('ABSPATH')) {
142
402
  define('FORGEWP_THEME_VERSION', '${version}');
143
403
 
144
404
  /**
145
- * Enqueue compiled theme assets (CSS only in v1 — static HTML, no hydration).
405
+ * Enqueue compiled theme assets.
146
406
  */
147
407
  function forgewp_enqueue_assets(): void {
148
408
  $theme_uri = get_template_directory_uri();
149
409
  $css_path = get_template_directory() . '/assets/${css}';
410
+ ${fontsEnqueue}
150
411
 
151
412
  if (file_exists($css_path)) {
152
413
  wp_enqueue_style(
@@ -168,9 +429,12 @@ function forgewp_theme_setup(): void {
168
429
  add_theme_support('html5', array('search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'style', 'script'));
169
430
  add_theme_support('wp-block-styles');
170
431
  add_theme_support('editor-styles');
432
+
433
+ // Load compiled theme stylesheet inside Gutenberg Block Editor
434
+ add_editor_style('assets/${css}');
171
435
  }
172
436
  add_action('after_setup_theme', 'forgewp_theme_setup');
173
- `;
437
+ ${preconnectFilter}${blocksRegistration}`;
174
438
  }
175
439
 
176
440
  function buildHeaderPhp(config) {
@@ -185,6 +449,15 @@ function buildHeaderPhp(config) {
185
449
  <head>
186
450
  <meta charset="<?php bloginfo('charset'); ?>">
187
451
  <meta name="viewport" content="width=device-width, initial-scale=1">
452
+ <?php
453
+ $single_head = get_template_directory() . '/forgewp-static/single-head.html';
454
+ $head_file = get_template_directory() . '/forgewp-static/head.html';
455
+ if (is_single() && file_exists($single_head)) {
456
+ include $single_head;
457
+ } elseif (file_exists($head_file)) {
458
+ include $head_file;
459
+ }
460
+ ?>
188
461
  <?php wp_head(); ?>
189
462
  <style>
190
463
  /* Reset WP link underlines to match React/Tailwind expected styling */
@@ -263,20 +536,261 @@ function buildSinglePhp() {
263
536
 
264
537
  get_header();
265
538
 
266
- if (have_posts()) {
267
- while (have_posts()) {
268
- the_post();
269
- echo '<main class="mx-auto max-w-3xl px-6 py-12">';
270
- echo '<article>';
271
- echo '<h1 class="text-4xl font-bold mb-6">' . get_the_title() . '</h1>';
272
- echo '<div class="prose prose-zinc max-w-none">';
273
- the_content();
539
+ $single_file = get_template_directory() . '/forgewp-static/single.html';
540
+ if (file_exists($single_file)) {
541
+ if (have_posts()) {
542
+ while (have_posts()) {
543
+ the_post();
544
+ include $single_file;
545
+ }
546
+ }
547
+ } else {
548
+ if (have_posts()) {
549
+ while (have_posts()) {
550
+ the_post();
551
+ echo '<main class="mx-auto max-w-3xl px-6 py-12">';
552
+ echo '<article>';
553
+ echo '<h1 class="text-4xl font-bold mb-6">' . get_the_title() . '</h1>';
554
+ echo '<div class="prose prose-zinc max-w-none">';
555
+ the_content();
556
+ echo '</div>';
557
+ echo '</article>';
558
+ echo '</main>';
559
+ }
560
+ }
561
+ }
562
+
563
+ get_footer();
564
+ `;
565
+ }
566
+
567
+ function build404Php() {
568
+ return `<?php
569
+ /**
570
+ * 404 template
571
+ *
572
+ * @package forgewp
573
+ */
574
+
575
+ get_header();
576
+
577
+ $notFound_file = get_template_directory() . '/forgewp-static/404.html';
578
+ if (file_exists($notFound_file)) {
579
+ include $notFound_file;
580
+ } else {
581
+ echo '<main class="flex min-h-[60vh] flex-col items-center justify-center text-center px-6 py-24">';
582
+ echo '<p class="text-base font-semibold text-zinc-900">404</p>';
583
+ echo '<h1 class="mt-4 text-3xl font-bold tracking-tight text-zinc-900 sm:text-5xl">Page not found</h1>';
584
+ echo '<p class="mt-6 text-base leading-7 text-zinc-600">Sorry, we couldn’t find the page you’re looking for.</p>';
585
+ echo '</main>';
586
+ }
587
+
588
+ get_footer();
589
+ `;
590
+ }
591
+
592
+ function buildArchivePhp() {
593
+ return `<?php
594
+ /**
595
+ * Archive template — category, tag, date, and author archives.
596
+ * Loads the ForgeWP compiled archive.html which contains the WpLoop.
597
+ *
598
+ * @package forgewp
599
+ */
600
+
601
+ get_header();
602
+
603
+ $archive_file = get_template_directory() . '/forgewp-static/archive.html';
604
+
605
+ if (file_exists($archive_file)) {
606
+ include $archive_file;
607
+ } else {
608
+ echo '<main class="mx-auto max-w-3xl px-6 py-12">';
609
+ the_archive_title('<h1 class="text-3xl font-bold mb-8">', '</h1>');
610
+ if (have_posts()) {
611
+ echo '<div class="space-y-8">';
612
+ while (have_posts()) {
613
+ the_post();
614
+ echo '<article>';
615
+ echo '<h2 class="text-xl font-bold"><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';
616
+ echo '<div class="text-sm text-zinc-500 mt-1">' . get_the_date() . ' by ' . get_the_author() . '</div>';
617
+ echo '<div class="mt-3 text-zinc-600">';
618
+ the_excerpt();
619
+ echo '</div>';
620
+ echo '</article>';
621
+ }
274
622
  echo '</div>';
275
- echo '</article>';
276
- echo '</main>';
623
+ } else {
624
+ echo '<p>No posts found.</p>';
277
625
  }
626
+ echo '</main>';
278
627
  }
279
628
 
280
629
  get_footer();
281
630
  `;
282
631
  }
632
+
633
+ function buildPagePhp() {
634
+ return `<?php
635
+ /**
636
+ * Static page template — WordPress pages (e.g. About, Contact).
637
+ * Reuses single.html since static pages share the same title+content structure.
638
+ *
639
+ * @package forgewp
640
+ */
641
+
642
+ get_header();
643
+
644
+ $page_file = get_template_directory() . '/forgewp-static/single.html';
645
+
646
+ if (file_exists($page_file)) {
647
+ if (have_posts()) {
648
+ while (have_posts()) {
649
+ the_post();
650
+ include $page_file;
651
+ }
652
+ }
653
+ } else {
654
+ if (have_posts()) {
655
+ while (have_posts()) {
656
+ the_post();
657
+ echo '<main class="mx-auto max-w-3xl px-6 py-12">';
658
+ echo '<article>';
659
+ echo '<h1 class="text-4xl font-bold mb-6">' . get_the_title() . '</h1>';
660
+ echo '<div class="prose prose-zinc max-w-none">';
661
+ the_content();
662
+ echo '</div>';
663
+ echo '</article>';
664
+ echo '</main>';
665
+ }
666
+ }
667
+ }
668
+
669
+ get_footer();
670
+ `;
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 ADDED
@@ -0,0 +1,61 @@
1
+ export interface ColorPreset {
2
+ name: string;
3
+ slug: string;
4
+ color: string;
5
+ }
6
+
7
+ export interface FontSizePreset {
8
+ name: string;
9
+ slug: string;
10
+ size: string;
11
+ }
12
+
13
+ export interface FontFamilyPreset {
14
+ name: string;
15
+ slug: string;
16
+ fontFamily: string;
17
+ }
18
+
19
+ export interface ForgeWPThemeConfig {
20
+ name: string;
21
+ slug: string;
22
+ version: string;
23
+ description: string;
24
+ textDomain: string;
25
+ style?: "forgewp" | "shadcn";
26
+ settings?: {
27
+ layout?: {
28
+ contentSize?: string;
29
+ wideSize?: string;
30
+ };
31
+ color?: {
32
+ palette?: ColorPreset[];
33
+ custom?: boolean;
34
+ };
35
+ typography?: {
36
+ fontSizes?: FontSizePreset[];
37
+ fontFamilies?: FontFamilyPreset[];
38
+ googleFonts?: string[];
39
+ };
40
+ };
41
+ }
42
+
43
+ export interface ForgeWPBuildAssets {
44
+ cssFile: string;
45
+ }
46
+
47
+ export function exportTheme(options: {
48
+ themeRoot: string;
49
+ skipBuild?: boolean;
50
+ zip?: boolean;
51
+ packageManager?: string;
52
+ }): Promise<{
53
+ config: ForgeWPThemeConfig;
54
+ outDir: string;
55
+ zipPath: string | null;
56
+ assets: ForgeWPBuildAssets;
57
+ }>;
58
+
59
+ export function loadConfig(themeRoot: string): Promise<ForgeWPThemeConfig>;
60
+
61
+ export function validateCriticalFiles(themeRoot: string): void;