@forgewp/compiler 0.4.1 → 0.4.3

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 (51) hide show
  1. package/README.md +11 -3
  2. package/bin/add.js +15 -6
  3. package/bin/analyze.js +66 -1
  4. package/bin/cli.js +20 -12
  5. package/bin/fresh.js +1 -1
  6. package/bin/make-block.js +11 -0
  7. package/bin/make-island.js +11 -0
  8. package/bin/{make-template.js → make-loop.js} +24 -19
  9. package/bin/make-page.js +83 -0
  10. package/bin/make-post-type.js +11 -0
  11. package/bin/make-sandbox.js +558 -0
  12. package/bin/sync-hooks.js +221 -0
  13. package/lib/adapters/html-adapter.js +8 -3
  14. package/lib/adapters/stub-adapter.js +6 -2
  15. package/lib/asset-loader.js +22 -0
  16. package/lib/blueprints.js +122 -1434
  17. package/lib/functions-builder.js +1172 -3
  18. package/lib/generate-theme.js +340 -23
  19. package/lib/hydration-scanner.js +170 -11
  20. package/lib/index.d.ts +38 -1
  21. package/lib/index.js +1 -1
  22. package/lib/load-config.js +98 -0
  23. package/lib/markup-processor.js +110 -0
  24. package/lib/page-config-plugin.js +40 -0
  25. package/lib/php-builders.js +4 -2
  26. package/lib/react-adapter.js +82 -23
  27. package/lib/render-theme.mts +115 -25
  28. package/lib/validate-export.js +49 -0
  29. package/package.json +4 -2
  30. package/templates/PresetsStyle.tsx +74 -0
  31. package/templates/SEO.tsx +109 -0
  32. package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
  33. package/templates/auth/components/forgot-password-form-wrapper.tsx +133 -0
  34. package/templates/auth/components/login-form-wrapper.tsx +203 -0
  35. package/templates/auth/components/reset-password-form-wrapper.tsx +182 -0
  36. package/templates/auth/components/signup-form-wrapper.tsx +257 -0
  37. package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
  38. package/templates/auth/pages/DashboardPage.tsx +15 -0
  39. package/templates/auth/pages/ForgotPasswordPage.tsx +14 -0
  40. package/templates/auth/pages/LoginPage.tsx +14 -0
  41. package/templates/auth/pages/ResetPasswordPage.tsx +14 -0
  42. package/templates/auth/pages/SignUpPage.tsx +14 -0
  43. package/templates/auth/pages/VerifyEmailPage.tsx +14 -0
  44. package/templates/forgewp-config.ts +110 -0
  45. package/templates/menus.json +11 -0
  46. package/templates/mock-data.json +123 -0
  47. package/templates/products.json +5 -0
  48. package/templates/roles.json +7 -0
  49. package/templates/sessions.json +1 -0
  50. package/templates/users.json +34 -0
  51. package/templates/wordpress.tsx +1390 -0
@@ -212,17 +212,30 @@ export async function generateTheme({
212
212
  }
213
213
  }
214
214
 
215
+ const manifestPath = path.join(themeRoot, 'dist', '.vite', 'manifest.json');
216
+ let viteManifest = {};
217
+ if (existsSync(manifestPath)) {
218
+ try {
219
+ viteManifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
220
+ } catch (e) {
221
+ console.warn('Failed to parse Vite manifest.json:', e.message);
222
+ }
223
+ }
224
+
225
+ const replaceAssetPlaceholders = (markup) => {
226
+ if (!markup) return '';
227
+ return markup.replace(/__FORGEWP_ASSET__([a-zA-Z0-9_\-\.\/]+)/g, (match, srcPath) => {
228
+ const manifestEntry = viteManifest[srcPath];
229
+ if (manifestEntry && manifestEntry.file) {
230
+ return `<?php echo esc_url( get_template_directory_uri() ); ?>/${manifestEntry.file}`;
231
+ }
232
+ return `<?php echo esc_url( get_template_directory_uri() ); ?>/${srcPath}`;
233
+ });
234
+ };
235
+
215
236
  let hydrationManifestJson = '{}';
216
237
  if (hasHydration) {
217
- const manifestPath = path.join(themeRoot, 'dist', '.vite', 'manifest.json');
218
- let viteManifest = {};
219
- if (existsSync(manifestPath)) {
220
- try {
221
- viteManifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
222
- } catch (e) {
223
- console.warn('Failed to parse Vite manifest.json:', e.message);
224
- }
225
- } else {
238
+ if (!existsSync(manifestPath)) {
226
239
  console.warn(
227
240
  'Hydration manifest not found at dist/.vite/manifest.json. Hydration asset generation may be incomplete.',
228
241
  );
@@ -621,24 +634,24 @@ export async function generateTheme({
621
634
 
622
635
  const staticDir = path.join(outDir, 'forgewp-static');
623
636
  mkdirSync(staticDir, { recursive: true });
624
- writeFileSync(path.join(staticDir, 'content.html'), contentHtml, 'utf8');
625
- writeFileSync(path.join(staticDir, 'header.html'), processedHeader, 'utf8');
626
- writeFileSync(path.join(staticDir, 'footer.html'), processedFooter, 'utf8');
637
+ writeFileSync(path.join(staticDir, 'content.html'), replaceAssetPlaceholders(contentHtml), 'utf8');
638
+ writeFileSync(path.join(staticDir, 'header.html'), replaceAssetPlaceholders(processedHeader), 'utf8');
639
+ writeFileSync(path.join(staticDir, 'footer.html'), replaceAssetPlaceholders(processedFooter), 'utf8');
627
640
  if (headHtml) {
628
- writeFileSync(path.join(staticDir, 'head.html'), headHtml, 'utf8');
641
+ writeFileSync(path.join(staticDir, 'head.html'), replaceAssetPlaceholders(headHtml), 'utf8');
629
642
  }
630
643
  if (singleHeadHtml) {
631
644
  writeFileSync(
632
645
  path.join(staticDir, 'single-head.html'),
633
- singleHeadHtml,
646
+ replaceAssetPlaceholders(singleHeadHtml),
634
647
  'utf8',
635
648
  );
636
649
  }
637
650
  if (processedSingle) {
638
- writeFileSync(path.join(staticDir, 'single.html'), processedSingle, 'utf8');
651
+ writeFileSync(path.join(staticDir, 'single.html'), replaceAssetPlaceholders(processedSingle), 'utf8');
639
652
  }
640
653
  if (processedNotFound) {
641
- writeFileSync(path.join(staticDir, '404.html'), processedNotFound, 'utf8');
654
+ writeFileSync(path.join(staticDir, '404.html'), replaceAssetPlaceholders(processedNotFound), 'utf8');
642
655
  }
643
656
 
644
657
  // Archive page (category / tag / date archives)
@@ -656,7 +669,7 @@ export async function generateTheme({
656
669
  processedArchive = processedArchive.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
657
670
  writeFileSync(
658
671
  path.join(staticDir, 'archive.html'),
659
- processedArchive,
672
+ replaceAssetPlaceholders(processedArchive),
660
673
  'utf8',
661
674
  );
662
675
  }
@@ -735,6 +748,9 @@ if (window.forgeWpBlocks) {
735
748
  } catch {}
736
749
  }
737
750
 
751
+ const queries = scanForQueries(themeRoot);
752
+ console.log(`[ForgeWP Compiler] Scanned and compiled ${queries.length} REST endpoints: ${queries.map(q => q.queryId).join(', ') || '<none>'}`);
753
+
738
754
  let functionsPhpContent = buildFunctionsPhp(
739
755
  config,
740
756
  assets,
@@ -745,6 +761,7 @@ if (window.forgeWpBlocks) {
745
761
  hydrationData,
746
762
  Array.from(i18nKeys),
747
763
  schemas,
764
+ queries,
748
765
  );
749
766
 
750
767
  if (projectHooks && typeof projectHooks.processFunctionsPhp === 'function') {
@@ -836,13 +853,13 @@ if (window.forgeWpBlocks) {
836
853
  }
837
854
  processedHtml = processedHtml.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
838
855
 
839
- writeFileSync(path.join(staticDir, file), processedHtml, 'utf8');
856
+ writeFileSync(path.join(staticDir, file), replaceAssetPlaceholders(processedHtml), 'utf8');
840
857
 
841
858
  const headFile = file.replace('.html', '-head.html');
842
859
  if (existsSync(path.join(forgewpDir, headFile))) {
843
860
  writeFileSync(
844
861
  path.join(staticDir, headFile),
845
- readFileSync(path.join(forgewpDir, headFile), 'utf8'),
862
+ replaceAssetPlaceholders(readFileSync(path.join(forgewpDir, headFile), 'utf8')),
846
863
  'utf8',
847
864
  );
848
865
  }
@@ -885,6 +902,11 @@ get_footer();
885
902
  }
886
903
  }
887
904
 
905
+ const authManifest = {
906
+ protectedPages: [],
907
+ authGates: [],
908
+ };
909
+
888
910
  // Dynamic Custom Page Templates Compiler
889
911
  if (existsSync(forgewpDir)) {
890
912
  const templateFiles = readdirSync(forgewpDir);
@@ -897,7 +919,163 @@ get_footer();
897
919
  const slug = file.replace('.html', '');
898
920
  const rawHtml = readFileSync(path.join(forgewpDir, file), 'utf8');
899
921
 
900
- let processedHtml = processMarkup(rawHtml, config.textDomain);
922
+ let isProtected = false;
923
+ let allowedCapability = null;
924
+ let redirectUrl = null;
925
+
926
+ if (rawHtml.includes('<forgewp-require-auth')) {
927
+ isProtected = true;
928
+ const match = rawHtml.match(/<forgewp-require-auth\s+([^>]*)\/?>/i);
929
+ if (match) {
930
+ const attrsStr = match[1];
931
+ const getAttr = (name) => {
932
+ const regex = new RegExp(
933
+ `(?:${name}|${name.toLowerCase()})=(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,
934
+ 'i',
935
+ );
936
+ const m = attrsStr.match(regex);
937
+ return m ? m[1] || m[2] || m[3] || '' : '';
938
+ };
939
+ allowedCapability = getAttr('allowed') || null;
940
+ redirectUrl = getAttr('redirect') || null;
941
+ }
942
+ }
943
+
944
+ if (isProtected) {
945
+ authManifest.protectedPages.push({
946
+ page: slug.replace('template-', ''),
947
+ allowed: allowedCapability,
948
+ redirect: redirectUrl,
949
+ });
950
+ }
951
+
952
+ if (rawHtml.includes('forgewp-auth-gate-start')) {
953
+ authManifest.authGates.push({
954
+ page: slug.replace('template-', ''),
955
+ type: 'logged_in',
956
+ });
957
+ }
958
+
959
+ if (rawHtml.includes('forgewp-capability-gate-start')) {
960
+ const match = rawHtml.match(/forgewp-capability-gate-start\s+allowed="([^"]*)"/);
961
+ authManifest.authGates.push({
962
+ page: slug.replace('template-', ''),
963
+ type: 'capability',
964
+ allowed: match ? match[1] : null,
965
+ });
966
+ }
967
+
968
+ let redirectPhp = '';
969
+ let cleanedRawHtml = rawHtml;
970
+ if (rawHtml.includes('<forgewp-require-auth')) {
971
+ const match = rawHtml.match(/<forgewp-require-auth\s+([^>]*)\/?>/i);
972
+ if (match) {
973
+ const attrsStr = match[1];
974
+ const getAttr = (name) => {
975
+ const regex = new RegExp(
976
+ `(?:${name}|${name.toLowerCase()})=(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,
977
+ 'i',
978
+ );
979
+ const m = attrsStr.match(regex);
980
+ return m ? m[1] || m[2] || m[3] || '' : '';
981
+ };
982
+
983
+ const allowed = getAttr('allowed');
984
+ const redirect = getAttr('redirect');
985
+
986
+ let redirectUrlExpr = 'wp_login_url()';
987
+ let redirectSetup = '';
988
+ if (redirect) {
989
+ if (redirect.startsWith('__FORGEWP_PAGELINK_')) {
990
+ const match = redirect.match(/__FORGEWP_PAGELINK_([a-zA-Z0-9_-]+)_DEFAULT_(.*?)__/);
991
+ if (match) {
992
+ const name = match[1];
993
+ const decoded = decodeURIComponent(match[2]);
994
+ redirectSetup = ` $redirect_url = home_url('${decoded.replace(/'/g, "\\'")}');
995
+ $current_lang = function_exists('pll_current_language') ? pll_current_language() : '';
996
+ $get_pages_args = array('meta_key' => '_wp_page_template', 'meta_value' => 'page-${name}.php', 'number' => 1);
997
+ if (!empty($current_lang)) {
998
+ $get_pages_args['lang'] = $current_lang;
999
+ }
1000
+ $matched_pages = get_pages($get_pages_args);
1001
+ if (!empty($matched_pages)) {
1002
+ $redirect_url = get_permalink($matched_pages[0]->ID);
1003
+ }`;
1004
+ redirectUrlExpr = '$redirect_url';
1005
+ } else {
1006
+ const matchPlain = redirect.match(/__FORGEWP_PAGELINK_([a-zA-Z0-9_-]+)__/);
1007
+ if (matchPlain) {
1008
+ const name = matchPlain[1];
1009
+ redirectSetup = ` $redirect_url = home_url('/');
1010
+ $current_lang = function_exists('pll_current_language') ? pll_current_language() : '';
1011
+ $get_pages_args = array('meta_key' => '_wp_page_template', 'meta_value' => 'page-${name}.php', 'number' => 1);
1012
+ if (!empty($current_lang)) {
1013
+ $get_pages_args['lang'] = $current_lang;
1014
+ }
1015
+ $matched_pages = get_pages($get_pages_args);
1016
+ if (!empty($matched_pages)) {
1017
+ $redirect_url = get_permalink($matched_pages[0]->ID);
1018
+ }`;
1019
+ redirectUrlExpr = '$redirect_url';
1020
+ } else {
1021
+ redirectUrlExpr = `home_url('${redirect}')`;
1022
+ }
1023
+ }
1024
+ } else if (redirect.startsWith('template:')) {
1025
+ const name = redirect.replace('template:', '');
1026
+ redirectSetup = ` $redirect_url = home_url('/');
1027
+ $current_lang = function_exists('pll_current_language') ? pll_current_language() : '';
1028
+ $get_pages_args = array('meta_key' => '_wp_page_template', 'meta_value' => 'page-${name}.php', 'number' => 1);
1029
+ if (!empty($current_lang)) {
1030
+ $get_pages_args['lang'] = $current_lang;
1031
+ }
1032
+ $matched_pages = get_pages($get_pages_args);
1033
+ if (!empty($matched_pages)) {
1034
+ $redirect_url = get_permalink($matched_pages[0]->ID);
1035
+ }`;
1036
+ redirectUrlExpr = '$redirect_url';
1037
+ } else {
1038
+ redirectUrlExpr = `home_url('${redirect}')`;
1039
+ }
1040
+ }
1041
+
1042
+ redirectPhp = `
1043
+ if ( ! is_user_logged_in() ) {
1044
+ ${redirectSetup ? redirectSetup + '\n' : ''} wp_safe_redirect( ${redirectUrlExpr} );
1045
+ exit;
1046
+ } else {
1047
+ $email_verification_enabled = get_option( 'forgewp_auth_email_verification_enabled' ) === '1';
1048
+ $verified_meta = get_user_meta( get_current_user_id(), 'forgewp_email_verified', true );
1049
+ $email_verified = ( $verified_meta === '' ) || ( $verified_meta === '1' ) || ( $verified_meta === true );
1050
+ if ( $email_verification_enabled && ! $email_verified ) {
1051
+ $verify_url = home_url( '/verify-email' );
1052
+ $current_lang = function_exists('pll_current_language') ? pll_current_language() : '';
1053
+ $get_pages_args = array('meta_key' => '_wp_page_template', 'meta_value' => 'page-verify-email-page.php', 'number' => 1);
1054
+ if (!empty($current_lang)) {
1055
+ $get_pages_args['lang'] = $current_lang;
1056
+ }
1057
+ $matched_pages = get_pages($get_pages_args);
1058
+ if (!empty($matched_pages)) {
1059
+ $verify_url = get_permalink($matched_pages[0]->ID);
1060
+ }
1061
+ wp_safe_redirect( $verify_url );
1062
+ exit;
1063
+ }
1064
+ }`;
1065
+
1066
+ if (allowed) {
1067
+ redirectPhp += `
1068
+ if ( ! current_user_can( '${allowed}' ) ) {
1069
+ wp_safe_redirect( home_url( '/' ) );
1070
+ exit;
1071
+ }`;
1072
+ }
1073
+ }
1074
+ cleanedRawHtml = rawHtml.replace(/<forgewp-require-auth\s*([^>]*)\/?>/gi, '');
1075
+ cleanedRawHtml = cleanedRawHtml.replace(/<\/forgewp-require-auth>/gi, '');
1076
+ }
1077
+
1078
+ let processedHtml = processMarkup(cleanedRawHtml, config.textDomain);
901
1079
  if (processedHeader) {
902
1080
  const replaced = processedHtml.replace(processedHeader, '');
903
1081
  processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
@@ -912,13 +1090,13 @@ get_footer();
912
1090
  processedHtml = projectHooks.processTemplateMarkup(slug, processedHtml, config);
913
1091
  }
914
1092
 
915
- writeFileSync(path.join(staticDir, file), processedHtml, 'utf8');
1093
+ writeFileSync(path.join(staticDir, file), replaceAssetPlaceholders(processedHtml), 'utf8');
916
1094
 
917
1095
  const headFile = file.replace('.html', '-head.html');
918
1096
  if (existsSync(path.join(forgewpDir, headFile))) {
919
1097
  writeFileSync(
920
1098
  path.join(staticDir, headFile),
921
- readFileSync(path.join(forgewpDir, headFile), 'utf8'),
1099
+ replaceAssetPlaceholders(readFileSync(path.join(forgewpDir, headFile), 'utf8')),
922
1100
  'utf8',
923
1101
  );
924
1102
  }
@@ -935,7 +1113,7 @@ get_footer();
935
1113
  *
936
1114
  * @package ${config.textDomain}
937
1115
  */
938
-
1116
+ ${redirectPhp}
939
1117
  get_header();
940
1118
 
941
1119
  $markup_file = get_template_directory() . '/forgewp-static/${file}';
@@ -990,6 +1168,22 @@ get_footer();
990
1168
  ...themeJson.settings.color,
991
1169
  ...config.settings.color,
992
1170
  };
1171
+
1172
+ // Smartly extract background and text colors from palette to style the WP editor canvas
1173
+ if (config.settings.color.palette && Array.isArray(config.settings.color.palette)) {
1174
+ if (!themeJson.styles) themeJson.styles = {};
1175
+ if (!themeJson.styles.color) themeJson.styles.color = {};
1176
+
1177
+ const bgPreset = config.settings.color.palette.find(p => p && p.slug === 'background');
1178
+ const textPreset = config.settings.color.palette.find(p => p && (p.slug === 'text' || p.slug === 'primary'));
1179
+
1180
+ if (bgPreset && !themeJson.styles.color.background) {
1181
+ themeJson.styles.color.background = bgPreset.color;
1182
+ }
1183
+ if (textPreset && !themeJson.styles.color.text) {
1184
+ themeJson.styles.color.text = textPreset.color;
1185
+ }
1186
+ }
993
1187
  }
994
1188
 
995
1189
  // Typography (fontSizes, fontFamilies)
@@ -1007,6 +1201,12 @@ get_footer();
1007
1201
  'utf8',
1008
1202
  );
1009
1203
 
1204
+ writeFileSync(
1205
+ path.join(outDir, 'auth-manifest.json'),
1206
+ JSON.stringify(authManifest, null, 2),
1207
+ 'utf8',
1208
+ );
1209
+
1010
1210
  const screenshot = path.join(themeRoot, 'cms', 'screenshot.png');
1011
1211
  if (existsSync(screenshot)) {
1012
1212
  copyFileSync(screenshot, path.join(outDir, 'screenshot.png'));
@@ -1017,3 +1217,120 @@ get_footer();
1017
1217
  }
1018
1218
  }
1019
1219
  }
1220
+
1221
+ function extractUseWpQueryArgs(fileContent) {
1222
+ const queries = [];
1223
+ const regex = /useWpQuery\s*\(/g;
1224
+ let match;
1225
+ while ((match = regex.exec(fileContent)) !== null) {
1226
+ const startIdx = regex.lastIndex; // index right after the '('
1227
+ let parenCount = 1;
1228
+ let endIdx = startIdx;
1229
+ let inString = false;
1230
+ let stringChar = null;
1231
+
1232
+ for (let i = startIdx; i < fileContent.length; i++) {
1233
+ const char = fileContent[i];
1234
+
1235
+ if (inString) {
1236
+ if (char === stringChar && fileContent[i - 1] !== '\\') {
1237
+ inString = false;
1238
+ }
1239
+ continue;
1240
+ }
1241
+ if (char === '"' || char === "'" || char === '`') {
1242
+ inString = true;
1243
+ stringChar = char;
1244
+ continue;
1245
+ }
1246
+
1247
+ if (char === '(') parenCount++;
1248
+ if (char === ')') {
1249
+ parenCount--;
1250
+ if (parenCount === 0) {
1251
+ endIdx = i;
1252
+ break;
1253
+ }
1254
+ }
1255
+ }
1256
+
1257
+ if (endIdx > startIdx) {
1258
+ const argText = fileContent.slice(startIdx, endIdx).trim();
1259
+ queries.push(argText);
1260
+ }
1261
+ }
1262
+ return queries;
1263
+ }
1264
+
1265
+ function safeEvalObject(objText) {
1266
+ if (!objText) return null;
1267
+ if (!objText.startsWith('{') || !objText.endsWith('}')) {
1268
+ return null;
1269
+ }
1270
+ try {
1271
+ const sandbox = new Proxy({}, {
1272
+ has() { return true; },
1273
+ get(target, prop) {
1274
+ if (prop === 'Symbol(Symbol.toPrimitive)') return undefined;
1275
+ return `__DYNAMIC_${String(prop)}__`;
1276
+ }
1277
+ });
1278
+ const fn = new Function('sandbox', `with(sandbox) { return (${objText}); }`);
1279
+ return fn(sandbox);
1280
+ } catch (e) {
1281
+ console.warn('[ForgeWP Query Parser] safeEvalObject failed for:', objText, e.message);
1282
+ return null;
1283
+ }
1284
+ }
1285
+
1286
+ function scanForQueries(themeRoot) {
1287
+ const srcDir = path.join(themeRoot, 'src');
1288
+ if (!existsSync(srcDir)) return [];
1289
+
1290
+ const queries = [];
1291
+ const walk = (dir) => {
1292
+ if (!existsSync(dir)) return;
1293
+ const files = readdirSync(dir);
1294
+ for (const file of files) {
1295
+ const fullPath = path.join(dir, file);
1296
+ const stat = statSync(fullPath);
1297
+ if (stat.isDirectory()) {
1298
+ walk(fullPath);
1299
+ } else if (/\.(js|jsx|ts|tsx)$/.test(file)) {
1300
+ const content = readFileSync(fullPath, 'utf8');
1301
+ if (content.includes('useWpQuery')) {
1302
+ const rawArgsList = extractUseWpQueryArgs(content);
1303
+ for (const rawArgs of rawArgsList) {
1304
+ if (!rawArgs) continue;
1305
+ const parsed = safeEvalObject(rawArgs);
1306
+ if (parsed && typeof parsed === 'object') {
1307
+ if (!parsed.postType) {
1308
+ parsed.postType = 'post';
1309
+ }
1310
+ if (!parsed.queryId) {
1311
+ const baseName = path.basename(file, path.extname(file));
1312
+ const postTypePart = String(parsed.postType).toLowerCase();
1313
+ const cleanBase = baseName.toLowerCase().replace(/[^a-z0-9]+/g, '-');
1314
+ parsed.queryId = cleanBase + '-' + postTypePart;
1315
+ }
1316
+ queries.push(parsed);
1317
+ }
1318
+ }
1319
+ }
1320
+ }
1321
+ }
1322
+ };
1323
+
1324
+ walk(srcDir);
1325
+
1326
+ const uniqueQueries = [];
1327
+ const seenIds = new Set();
1328
+ for (const q of queries) {
1329
+ const cleanId = q.queryId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
1330
+ if (!seenIds.has(cleanId)) {
1331
+ seenIds.add(cleanId);
1332
+ uniqueQueries.push(q);
1333
+ }
1334
+ }
1335
+ return uniqueQueries;
1336
+ }
@@ -126,10 +126,8 @@ export function scanForHydrationIslands(themeRoot) {
126
126
  * @returns {string|null} The absolute path to the component file, or null if not found.
127
127
  */
128
128
  export function findComponentPath(themeRoot, kebabName) {
129
- const compDirs = [
130
- path.join(themeRoot, "src", "components"),
131
- path.join(themeRoot, "src", "components", "ui"),
132
- ];
129
+ const compDir = path.join(themeRoot, "src", "components");
130
+ if (!existsSync(compDir)) return null;
133
131
 
134
132
  // Convert kebab-case back to PascalCase and check candidates
135
133
  const pascalName = kebabName
@@ -144,19 +142,28 @@ export function findComponentPath(themeRoot, kebabName) {
144
142
  `${kebabName}.ts`,
145
143
  ];
146
144
 
147
- for (const dir of compDirs) {
148
- if (!existsSync(dir)) continue;
145
+ let result = null;
146
+
147
+ function searchRecursive(dir) {
148
+ if (result) return;
149
149
  try {
150
- const files = readdirSync(dir);
151
- for (const file of files) {
152
- if (candidates.includes(file)) {
153
- return path.join(dir, file);
150
+ const items = readdirSync(dir, { withFileTypes: true });
151
+ for (const item of items) {
152
+ const fullPath = path.join(dir, item.name);
153
+ if (item.isDirectory()) {
154
+ searchRecursive(fullPath);
155
+ } else if (item.isFile()) {
156
+ if (candidates.includes(item.name)) {
157
+ result = fullPath;
158
+ return;
159
+ }
154
160
  }
155
161
  }
156
162
  } catch {}
157
163
  }
158
164
 
159
- return null;
165
+ searchRecursive(compDir);
166
+ return result;
160
167
  }
161
168
 
162
169
  /**
@@ -380,6 +387,107 @@ export function runStaticLintChecks(themeRoot) {
380
387
  const violations = [];
381
388
  const filesToScan = [];
382
389
 
390
+ // Load CPTs, Taxonomies, and Custom Fields from wp.config.ts and cms/mock-data.json
391
+ const validPostTypes = new Set(["post", "page"]);
392
+ const postTypeTaxonomies = {
393
+ "post": new Set(["category", "post_tag"]),
394
+ "page": new Set()
395
+ };
396
+ const postTypeCustomFields = {
397
+ "post": new Set(),
398
+ "page": new Set()
399
+ };
400
+
401
+ // 1. Scan CPTs from wp.config.ts
402
+ const configPath = path.join(themeRoot, "wp.config.ts");
403
+ if (existsSync(configPath)) {
404
+ try {
405
+ const configContent = readFileSync(configPath, "utf8");
406
+ const postTypesMatch = configContent.match(/postTypes\s*:\s*\{([\s\S]*?)\}/);
407
+ if (postTypesMatch) {
408
+ const block = postTypesMatch[1];
409
+ const keyRegex = /\b([a-zA-Z0-9_-]+)\s*:/g;
410
+ let m;
411
+ while ((m = keyRegex.exec(block)) !== null) {
412
+ const pt = m[1];
413
+ if (pt !== 'labels' && pt !== 'singular' && pt !== 'plural' && pt !== 'translatable') {
414
+ validPostTypes.add(pt);
415
+ if (!postTypeTaxonomies[pt]) {
416
+ postTypeTaxonomies[pt] = new Set(["category", "post_tag"]);
417
+ }
418
+ if (!postTypeCustomFields[pt]) {
419
+ postTypeCustomFields[pt] = new Set();
420
+ }
421
+ }
422
+ }
423
+ }
424
+ } catch {}
425
+ }
426
+
427
+ // 2. Scan CPTs, Taxonomies, and Custom Fields from cms/mock-data.json and cms/products.json
428
+ const dataFiles = [
429
+ path.join(themeRoot, "cms", "mock-data.json"),
430
+ path.join(themeRoot, "cms", "products.json")
431
+ ];
432
+ for (const dbPath of dataFiles) {
433
+ if (existsSync(dbPath)) {
434
+ try {
435
+ const mockData = JSON.parse(readFileSync(dbPath, "utf8"));
436
+ for (const pt of Object.keys(mockData)) {
437
+ if (
438
+ pt !== 'posts' &&
439
+ pt !== 'pages' &&
440
+ pt !== 'post' &&
441
+ pt !== 'page' &&
442
+ pt !== 'menus' &&
443
+ pt !== 'attachment' &&
444
+ !pt.startsWith('_')
445
+ ) {
446
+ validPostTypes.add(pt);
447
+ if (!postTypeTaxonomies[pt]) {
448
+ postTypeTaxonomies[pt] = new Set(["category", "post_tag"]);
449
+ }
450
+ if (!postTypeCustomFields[pt]) {
451
+ postTypeCustomFields[pt] = new Set();
452
+ }
453
+
454
+ const items = mockData[pt];
455
+ if (Array.isArray(items)) {
456
+ for (const item of items) {
457
+ if (item._terms && typeof item._terms === 'object') {
458
+ for (const tax of Object.keys(item._terms)) {
459
+ postTypeTaxonomies[pt].add(tax);
460
+ }
461
+ }
462
+ if (item.customFields && typeof item.customFields === 'object') {
463
+ for (const key of Object.keys(item.customFields)) {
464
+ postTypeCustomFields[pt].add(key);
465
+ }
466
+ }
467
+ }
468
+ }
469
+ } else if (pt === 'post' || pt === 'page') {
470
+ const items = mockData[pt];
471
+ if (Array.isArray(items)) {
472
+ for (const item of items) {
473
+ if (item._terms && typeof item._terms === 'object') {
474
+ for (const tax of Object.keys(item._terms)) {
475
+ postTypeTaxonomies[pt].add(tax);
476
+ }
477
+ }
478
+ if (item.customFields && typeof item.customFields === 'object') {
479
+ for (const key of Object.keys(item.customFields)) {
480
+ postTypeCustomFields[pt].add(key);
481
+ }
482
+ }
483
+ }
484
+ }
485
+ }
486
+ }
487
+ } catch {}
488
+ }
489
+ }
490
+
383
491
  const validSlugs = new Set(["page"]);
384
492
  const pagesDir = path.join(themeRoot, "src", "app", "pages");
385
493
  if (existsSync(pagesDir)) {
@@ -557,6 +665,57 @@ export function runStaticLintChecks(themeRoot) {
557
665
  }
558
666
  }
559
667
 
668
+ // 5. useWpQuery arguments audit
669
+ const useWpQueryRegex = /useWpQuery\s*\(\s*(\{[\s\S]*?\})\s*\)/g;
670
+ let queryMatch;
671
+ while ((queryMatch = useWpQueryRegex.exec(content)) !== null) {
672
+ const argsStr = queryMatch[1];
673
+
674
+ const postTypeMatch = argsStr.match(/postType\s*:\s*['"]([^'"]+)['"]/);
675
+ const postType = postTypeMatch ? postTypeMatch[1] : 'post';
676
+
677
+ if (!validPostTypes.has(postType)) {
678
+ violations.push({
679
+ type: "query",
680
+ file: relFile,
681
+ message: `useWpQuery references unregistered postType "${postType}".`,
682
+ severity: "warning"
683
+ });
684
+ } else {
685
+ // Validate Taxonomies inside taxQuery
686
+ const taxRegex = /\btaxonomy\s*:\s*['"]([^'"]+)['"]/g;
687
+ let taxMatch;
688
+ const allowedTaxonomies = postTypeTaxonomies[postType] || new Set();
689
+ while ((taxMatch = taxRegex.exec(argsStr)) !== null) {
690
+ const taxSlug = taxMatch[1];
691
+ if (!allowedTaxonomies.has(taxSlug)) {
692
+ violations.push({
693
+ type: "query",
694
+ file: relFile,
695
+ message: `useWpQuery in ${path.basename(filePath)} queries taxonomy "${taxSlug}", which is not registered for postType "${postType}" in wp.config.ts.`,
696
+ severity: "warning"
697
+ });
698
+ }
699
+ }
700
+
701
+ // Validate Custom Fields inside metaQuery
702
+ const keyRegex = /\bkey\s*:\s*['"]([^'"]+)['"]/g;
703
+ let keyMatch;
704
+ const allowedFields = postTypeCustomFields[postType] || new Set();
705
+ while ((keyMatch = keyRegex.exec(argsStr)) !== null) {
706
+ const fieldKey = keyMatch[1];
707
+ if (!allowedFields.has(fieldKey)) {
708
+ violations.push({
709
+ type: "query",
710
+ file: relFile,
711
+ message: `useWpQuery in ${path.basename(filePath)} queries custom field "${fieldKey}", which is not defined for postType "${postType}" in wp.config.ts.`,
712
+ severity: "warning"
713
+ });
714
+ }
715
+ }
716
+ }
717
+ }
718
+
560
719
  } catch (err) {
561
720
  console.warn(`[Static Lint] Failed to scan file ${filePath}:`, err.message);
562
721
  }