@forgewp/compiler 0.3.0 → 0.4.2

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 (52) hide show
  1. package/README.md +24 -5
  2. package/bin/analyze.js +158 -0
  3. package/bin/cli.js +33 -4
  4. package/bin/doctor.js +125 -11
  5. package/bin/export.js +20 -0
  6. package/bin/fresh.js +32 -343
  7. package/bin/i18n-extract.js +121 -0
  8. package/bin/i18n-translate.js +112 -0
  9. package/bin/make-block.js +27 -60
  10. package/bin/make-island.js +72 -0
  11. package/bin/make-post-type.js +6 -6
  12. package/bin/make-template.js +145 -0
  13. package/bin/repair.js +2 -2
  14. package/bin/sync-hooks.js +221 -0
  15. package/bin/sync-routes.js +28 -158
  16. package/define-config.d.ts +1 -0
  17. package/define-config.js +1 -0
  18. package/lib/adapters/html-adapter.js +65 -0
  19. package/lib/adapters/stub-adapter.js +49 -0
  20. package/lib/add-component.js +282 -183
  21. package/lib/asset-loader.js +27 -0
  22. package/lib/block-compiler.js +552 -0
  23. package/lib/blueprints.js +15 -501
  24. package/lib/define-config.d.ts +3 -0
  25. package/lib/define-config.js +8 -0
  26. package/lib/diagnostics.js +798 -0
  27. package/lib/export-theme.js +81 -18
  28. package/lib/framework-adapter.js +34 -0
  29. package/lib/functions-builder.js +2044 -0
  30. package/lib/generate-theme.js +1140 -1352
  31. package/lib/hydration-scanner.js +663 -21
  32. package/lib/i18n/extractor.js +60 -0
  33. package/lib/i18n/providers.js +165 -0
  34. package/lib/index.d.ts +115 -3
  35. package/lib/index.js +19 -5
  36. package/lib/load-config.js +122 -6
  37. package/lib/markup-processor.js +589 -0
  38. package/lib/php-builders.js +381 -0
  39. package/lib/react-adapter.js +1336 -0
  40. package/lib/render-static.js +9 -82
  41. package/lib/render-theme.mts +543 -232
  42. package/lib/screenshot-fallback.png +0 -0
  43. package/lib/types.js +1 -0
  44. package/lib/validate-export.js +183 -0
  45. package/package.json +15 -3
  46. package/templates/PresetsStyle.tsx +74 -0
  47. package/templates/SEO.tsx +109 -0
  48. package/templates/forgewp-config.ts +43 -0
  49. package/templates/menus.json +11 -0
  50. package/templates/mock-data.json +434 -0
  51. package/templates/wordpress.tsx +1297 -0
  52. package/bin/make-component.js +0 -200
@@ -0,0 +1,60 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ function walkDir(dir, fileList = []) {
5
+ const files = fs.readdirSync(dir);
6
+ for (const file of files) {
7
+ const filePath = path.join(dir, file);
8
+ const stat = fs.statSync(filePath);
9
+ if (stat.isDirectory()) {
10
+ if (file !== 'node_modules' && file !== '.git' && file !== '.forgewp' && file !== 'dist') {
11
+ walkDir(filePath, fileList);
12
+ }
13
+ } else {
14
+ const ext = path.extname(file);
15
+ if (['.ts', '.tsx', '.js', '.jsx'].includes(ext)) {
16
+ fileList.push(filePath);
17
+ }
18
+ }
19
+ }
20
+ return fileList;
21
+ }
22
+
23
+ /**
24
+ * Scans directories recursively for instances of __('string') or __("string").
25
+ * @param {string} dirPath
26
+ * @returns {string[]} Sorted unique translation keys
27
+ */
28
+ export function extractKeysFromDirectory(dirPath) {
29
+ const keys = new Set();
30
+ if (!fs.existsSync(dirPath)) {
31
+ return [];
32
+ }
33
+
34
+ const files = walkDir(dirPath);
35
+
36
+ // Regexes matching __('text') or __("text") handling escaped quotes natively
37
+ const singleQuoteRegex = /__\(\s*'((?:[^'\\]|\\.)*)'\s*\)/g;
38
+ const doubleQuoteRegex = /__\(\s*"((?:[^"\\]|\\.)*)"\s*\)/g;
39
+
40
+ for (const file of files) {
41
+ const content = fs.readFileSync(file, 'utf8');
42
+
43
+ // Single quote matches
44
+ let match;
45
+ singleQuoteRegex.lastIndex = 0;
46
+ while ((match = singleQuoteRegex.exec(content)) !== null) {
47
+ const val = match[1].replace(/\\'/g, "'").replace(/\\\\/g, "\\");
48
+ if (val) keys.add(val);
49
+ }
50
+
51
+ // Double quote matches
52
+ doubleQuoteRegex.lastIndex = 0;
53
+ while ((match = doubleQuoteRegex.exec(content)) !== null) {
54
+ const val = match[1].replace(/\\"/g, '"').replace(/\\\\/g, "\\");
55
+ if (val) keys.add(val);
56
+ }
57
+ }
58
+
59
+ return Array.from(keys).sort();
60
+ }
@@ -0,0 +1,165 @@
1
+ export class LocalProvider {
2
+ async translate(texts, sourceLang, targetLang) {
3
+ // Return empty translations to allow manual edit
4
+ const result = {};
5
+ for (const text of texts) {
6
+ result[text] = "";
7
+ }
8
+ return result;
9
+ }
10
+ }
11
+
12
+ export class DeepLProvider {
13
+ constructor(apiKey) {
14
+ this.apiKey = apiKey;
15
+ }
16
+
17
+ async translate(texts, sourceLang, targetLang) {
18
+ if (!this.apiKey) {
19
+ throw new Error("DeepL API key is required but missing. Configure FORGEWP_DEEPL_API_KEY in your env.");
20
+ }
21
+
22
+ const isFreeKey = this.apiKey.endsWith(':fx');
23
+ const endpoint = isFreeKey
24
+ ? 'https://api-free.deepl.com/v2/translate'
25
+ : 'https://api.deepl.com/v2/translate';
26
+
27
+ let target = targetLang.toUpperCase();
28
+ if (target === 'EN') target = 'EN-US';
29
+
30
+ const source = sourceLang.toUpperCase();
31
+
32
+ try {
33
+ const response = await fetch(endpoint, {
34
+ method: 'POST',
35
+ headers: {
36
+ 'Authorization': `DeepL-Auth-Key ${this.apiKey}`,
37
+ 'Content-Type': 'application/json',
38
+ },
39
+ body: JSON.stringify({
40
+ text: texts,
41
+ source_lang: source,
42
+ target_lang: target,
43
+ }),
44
+ });
45
+
46
+ if (!response.ok) {
47
+ const errText = await response.text();
48
+ throw new Error(`DeepL API error (${response.status}): ${errText}`);
49
+ }
50
+
51
+ const data = await response.json();
52
+ const translations = {};
53
+ if (data && Array.isArray(data.translations)) {
54
+ texts.forEach((text, index) => {
55
+ translations[text] = data.translations[index]?.text || "";
56
+ });
57
+ }
58
+ return translations;
59
+ } catch (err) {
60
+ throw new Error(`DeepL translation failed: ${err.message}`);
61
+ }
62
+ }
63
+ }
64
+
65
+ export class LibreTranslateProvider {
66
+ constructor(endpoint) {
67
+ this.endpoint = endpoint || 'http://localhost:5000';
68
+ }
69
+
70
+ async translate(texts, sourceLang, targetLang) {
71
+ const url = `${this.endpoint.replace(/\/$/, '')}/translate`;
72
+ try {
73
+ const response = await fetch(url, {
74
+ method: 'POST',
75
+ headers: {
76
+ 'Content-Type': 'application/json',
77
+ },
78
+ body: JSON.stringify({
79
+ q: texts,
80
+ source: sourceLang.toLowerCase(),
81
+ target: targetLang.toLowerCase(),
82
+ format: 'text',
83
+ }),
84
+ });
85
+
86
+ if (!response.ok) {
87
+ const errText = await response.text();
88
+ throw new Error(`LibreTranslate error (${response.status}): ${errText}`);
89
+ }
90
+
91
+ const data = await response.json();
92
+ const translations = {};
93
+
94
+ if (data && Array.isArray(data.translatedText)) {
95
+ texts.forEach((text, index) => {
96
+ translations[text] = data.translatedText[index] || "";
97
+ });
98
+ } else if (data && typeof data.translatedText === 'string') {
99
+ translations[texts[0]] = data.translatedText;
100
+ }
101
+ return translations;
102
+ } catch (err) {
103
+ throw new Error(`LibreTranslate translation failed: ${err.message}`);
104
+ }
105
+ }
106
+ }
107
+
108
+ export class GoogleProvider {
109
+ constructor(apiKey) {
110
+ this.apiKey = apiKey;
111
+ }
112
+
113
+ async translate(texts, sourceLang, targetLang) {
114
+ if (!this.apiKey) {
115
+ throw new Error("Google Translation API key is required but missing.");
116
+ }
117
+
118
+ const url = `https://translation.googleapis.com/language/translate/v2?key=${this.apiKey}`;
119
+ try {
120
+ const response = await fetch(url, {
121
+ method: 'POST',
122
+ headers: {
123
+ 'Content-Type': 'application/json',
124
+ },
125
+ body: JSON.stringify({
126
+ q: texts,
127
+ source: sourceLang.toLowerCase(),
128
+ target: targetLang.toLowerCase(),
129
+ format: 'text',
130
+ }),
131
+ });
132
+
133
+ if (!response.ok) {
134
+ const errText = await response.text();
135
+ throw new Error(`Google Translate error (${response.status}): ${errText}`);
136
+ }
137
+
138
+ const data = await response.json();
139
+ const translations = {};
140
+ if (data && data.data && Array.isArray(data.data.translations)) {
141
+ texts.forEach((text, index) => {
142
+ translations[text] = data.data.translations[index]?.translatedText || "";
143
+ });
144
+ }
145
+ return translations;
146
+ } catch (err) {
147
+ throw new Error(`Google translation failed: ${err.message}`);
148
+ }
149
+ }
150
+ }
151
+
152
+ export function getProvider(name, config = {}) {
153
+ switch (name) {
154
+ case 'deepl':
155
+ return new DeepLProvider(config.apiKey || process.env.FORGEWP_DEEPL_API_KEY);
156
+ case 'libretranslate':
157
+ return new LibreTranslateProvider(config.endpoint);
158
+ case 'google':
159
+ return new GoogleProvider(config.apiKey || process.env.FORGEWP_GOOGLE_API_KEY);
160
+ case 'local':
161
+ case 'manual':
162
+ default:
163
+ return new LocalProvider();
164
+ }
165
+ }
package/lib/index.d.ts CHANGED
@@ -16,13 +16,55 @@ export interface FontFamilyPreset {
16
16
  fontFamily: string;
17
17
  }
18
18
 
19
+ export interface CustomPostTypeConfig {
20
+ translatable?: boolean;
21
+ labels?: {
22
+ singular?: string;
23
+ plural?: string;
24
+ };
25
+ }
26
+
27
+ export interface ForgeWPI18nConfig {
28
+ locales: string[];
29
+ defaultLocale: string;
30
+ provider?: 'local' | 'deepl' | 'libretranslate' | 'google' | string;
31
+ cache?: string;
32
+ providerConfig?: {
33
+ apiKey?: string;
34
+ endpoint?: string;
35
+ };
36
+ }
37
+
38
+ export interface ForgeWpSeoSitemapsConfig {
39
+ postTypes: string[];
40
+ taxonomies: string[];
41
+ }
42
+
43
+ export interface ForgeWPPlugin {
44
+ name: string;
45
+ validateConfig?: (config: ForgeWPThemeConfig, themeRoot: string) => void;
46
+ transformFunctionsPhp?: (php: string, config: ForgeWPThemeConfig, themeRoot: string) => string;
47
+ }
48
+
19
49
  export interface ForgeWPThemeConfig {
20
50
  name: string;
21
51
  slug: string;
22
52
  version: string;
23
53
  description: string;
24
54
  textDomain: string;
25
- style?: "forgewp" | "shadcn";
55
+ configVersion?: number;
56
+ favicon?: string;
57
+ seo?: {
58
+ sitemaps?: ForgeWpSeoSitemapsConfig;
59
+ plugins?: {
60
+ yoast?: boolean;
61
+ rankMath?: boolean;
62
+ };
63
+ };
64
+ frameworkAdapter?: 'react' | 'html' | 'stub';
65
+ style?: 'forgewp' | 'shadcn';
66
+ postTypes?: Record<string, CustomPostTypeConfig>;
67
+ i18n?: ForgeWPI18nConfig;
26
68
  settings?: {
27
69
  layout?: {
28
70
  contentSize?: string;
@@ -38,12 +80,69 @@ export interface ForgeWPThemeConfig {
38
80
  googleFonts?: string[];
39
81
  };
40
82
  };
83
+ plugins?: ForgeWPPlugin[];
41
84
  }
42
85
 
86
+
87
+
43
88
  export interface ForgeWPBuildAssets {
44
89
  cssFile: string;
90
+ jsFile?: string;
45
91
  }
46
92
 
93
+ export interface ForgeWPStaticMarkup {
94
+ appHtml: string;
95
+ headerHtml?: string;
96
+ footerHtml?: string;
97
+ headHtml?: string;
98
+ singleHtml?: string;
99
+ singleHeadHtml?: string;
100
+ notFoundHtml?: string;
101
+ archiveHtml?: string;
102
+ }
103
+
104
+ export interface ForgeWPFrameworkAdapter {
105
+ renderStaticMarkup(
106
+ themeRoot: string,
107
+ ): Promise<ForgeWPStaticMarkup> | ForgeWPStaticMarkup;
108
+ scanForHydrationIslands(themeRoot: string): string[];
109
+ findComponentPath(themeRoot: string, kebabName: string): string | null;
110
+ getHydrationRollupInputs(themeRoot: string): Record<string, string>;
111
+ onFresh?(themeRoot: string): Promise<void> | void;
112
+ onMakeBlock?(
113
+ themeRoot: string,
114
+ options: {
115
+ pascalCase: string;
116
+ readableTitle: string;
117
+ attributesList: string[];
118
+ pc: any;
119
+ },
120
+ ): Promise<void> | void;
121
+ onMakeComponent?(
122
+ themeRoot: string,
123
+ options: {
124
+ pascalCase: string;
125
+ postType: string;
126
+ customFields: string[];
127
+ automaticallySeeded: boolean;
128
+ pc: any;
129
+ },
130
+ ): Promise<void> | void;
131
+ onSyncRoutes?(
132
+ themeRoot: string,
133
+ options: {
134
+ routesToScaffold: Array<{ path: string; title: string }>;
135
+ isForce: boolean;
136
+ pc: any;
137
+ },
138
+ ): Promise<void> | void;
139
+ getCriticalFiles?(themeRoot: string): string[];
140
+ }
141
+
142
+ export type ForgeWPFrameworkAdapterModule = ForgeWPFrameworkAdapter & {
143
+ default?: ForgeWPFrameworkAdapter;
144
+ };
145
+
47
146
  export function exportTheme(options: {
48
147
  themeRoot: string;
49
148
  skipBuild?: boolean;
@@ -58,10 +157,23 @@ export function exportTheme(options: {
58
157
 
59
158
  export function loadConfig(themeRoot: string): Promise<ForgeWPThemeConfig>;
60
159
 
160
+ export function defineConfig(config: ForgeWPThemeConfig): ForgeWPThemeConfig;
161
+
61
162
  export function validateCriticalFiles(themeRoot: string): void;
62
163
 
63
164
  export function scanForHydrationIslands(themeRoot: string): string[];
64
165
 
65
- export function findComponentPath(themeRoot: string, kebabName: string): string | null;
166
+ export function findComponentPath(
167
+ themeRoot: string,
168
+ kebabName: string,
169
+ ): string | null;
170
+
171
+ export function getHydrationRollupInputs(
172
+ themeRoot: string,
173
+ ): Record<string, string>;
174
+
175
+ export function resolveFrameworkAdapter(adapterName?: string): string;
66
176
 
67
- export function getHydrationRollupInputs(themeRoot: string): Record<string, string>;
177
+ export function loadFrameworkAdapter(
178
+ adapterName?: string,
179
+ ): Promise<ForgeWPFrameworkAdapterModule>;
package/lib/index.js CHANGED
@@ -1,6 +1,20 @@
1
- export { exportTheme } from "./export-theme.js";
2
- export { loadConfig } from "./load-config.js";
3
- export { validateCriticalFiles } from "./validate.js";
4
- export { scanForHydrationIslands, findComponentPath, getHydrationRollupInputs } from "./hydration-scanner.js";
5
-
1
+ export { exportTheme } from './export-theme.js';
2
+ export { loadConfig, defineConfig } from './load-config.js';
3
+ export { validateCriticalFiles } from './validate.js';
4
+ export {
5
+ scanForHydrationIslands,
6
+ scanForHydrationIslandsWithProps,
7
+ findComponentPath,
8
+ getHydrationRollupInputs,
9
+ scanForEditableSchemas,
10
+ } from './hydration-scanner.js';
11
+ export { validateExport } from './validate-export.js';
12
+ export {
13
+ resolveFrameworkAdapter,
14
+ loadFrameworkAdapter,
15
+ } from './framework-adapter.js';
16
+ export {
17
+ analyzeHydrationIslands,
18
+ generateVisualReport,
19
+ } from './diagnostics.js';
6
20
 
@@ -1,14 +1,14 @@
1
- import { existsSync } from "node:fs";
2
- import path from "node:path";
3
- import { pathToFileURL } from "node:url";
4
- import { createJiti } from "jiti";
1
+ import fs, { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { createJiti } from 'jiti';
5
5
 
6
6
  /**
7
7
  * @param {string} themeRoot
8
8
  * @returns {Promise<import('./types.js').ForgeWPThemeConfig>}
9
9
  */
10
10
  export async function loadConfig(themeRoot) {
11
- const configPath = path.join(themeRoot, "wp.config.ts");
11
+ const configPath = path.join(themeRoot, 'wp.config.ts');
12
12
 
13
13
  if (!existsSync(configPath)) {
14
14
  throw new Error(`Missing wp.config.ts in ${themeRoot}`);
@@ -21,8 +21,124 @@ export async function loadConfig(themeRoot) {
21
21
  const config = await jiti.import(configPath);
22
22
 
23
23
  if (!config?.slug || !config?.name) {
24
- throw new Error("wp.config.ts must export name, slug, version, description, textDomain");
24
+ throw new Error(
25
+ 'wp.config.ts must export name, slug, version, description, textDomain',
26
+ );
25
27
  }
26
28
 
29
+ // Validate configVersion
30
+ if (config.configVersion === undefined) {
31
+ console.warn(
32
+ '\x1b[33m%s\x1b[0m',
33
+ '⚠️ [ForgeWP Warning]: "configVersion" is missing in wp.config.ts. In a future version, "configVersion: 1" will be required.'
34
+ );
35
+ } else if (config.configVersion !== 1) {
36
+ throw new Error(
37
+ `Unsupported configVersion: ${config.configVersion}. The current supported version is 1.`
38
+ );
39
+ }
40
+
41
+ // Validate favicon
42
+ if (config.favicon !== undefined) {
43
+ if (typeof config.favicon !== 'string') {
44
+ throw new Error(
45
+ 'favicon must be a string pointing to an asset file (e.g. "/Logo/favicon.svg")'
46
+ );
47
+ }
48
+ const cleanedFavicon = config.favicon.replace(/^\//, '');
49
+ const path1 = path.join(themeRoot, cleanedFavicon);
50
+ const path2 = path.join(themeRoot, 'public', cleanedFavicon);
51
+ if (!existsSync(path1) && !existsSync(path2)) {
52
+ console.warn(
53
+ '\x1b[33m%s\x1b[0m',
54
+ `⚠️ [ForgeWP Warning]: Favicon file not found at "${config.favicon}". Please verify the file path exists in your theme directory.`
55
+ );
56
+ }
57
+ }
58
+
59
+ // Validate seo
60
+ if (config.seo !== undefined) {
61
+ if (typeof config.seo !== 'object' || config.seo === null) {
62
+ throw new Error('seo configuration must be an object');
63
+ }
64
+ if (config.seo.sitemaps !== undefined) {
65
+ const { postTypes, taxonomies } = config.seo.sitemaps;
66
+ if (
67
+ postTypes !== undefined &&
68
+ (!Array.isArray(postTypes) || postTypes.some((pt) => typeof pt !== 'string'))
69
+ ) {
70
+ throw new Error('seo.sitemaps.postTypes must be an array of strings');
71
+ }
72
+ if (postTypes && new Set(postTypes).size !== postTypes.length) {
73
+ throw new Error('seo.sitemaps.postTypes contains duplicate entries');
74
+ }
75
+
76
+ if (
77
+ taxonomies !== undefined &&
78
+ (!Array.isArray(taxonomies) || taxonomies.some((t) => typeof t !== 'string'))
79
+ ) {
80
+ throw new Error('seo.sitemaps.taxonomies must be an array of strings');
81
+ }
82
+ if (taxonomies && new Set(taxonomies).size !== taxonomies.length) {
83
+ throw new Error('seo.sitemaps.taxonomies contains duplicate entries');
84
+ }
85
+ }
86
+ }
87
+
88
+ if (config.i18n) {
89
+ const { locales, defaultLocale, provider } = config.i18n;
90
+ if (locales !== undefined) {
91
+ if (!Array.isArray(locales) || locales.some(l => typeof l !== 'string')) {
92
+ throw new Error('i18n.locales must be an array of locale code strings (e.g. ["en", "de"])');
93
+ }
94
+ if (locales.length === 0) {
95
+ throw new Error('i18n.locales array cannot be empty');
96
+ }
97
+ }
98
+ if (defaultLocale !== undefined) {
99
+ if (typeof defaultLocale !== 'string') {
100
+ throw new Error('i18n.defaultLocale must be a string (e.g. "en")');
101
+ }
102
+ if (locales && !locales.includes(defaultLocale)) {
103
+ throw new Error(`i18n.defaultLocale "${defaultLocale}" must be one of the configured locales: ${JSON.stringify(locales)}`);
104
+ }
105
+ }
106
+ if (provider !== undefined && typeof provider !== 'string') {
107
+ throw new Error('i18n.provider must be a string (e.g. "local", "deepl")');
108
+ }
109
+ }
110
+
111
+ if (config.postTypes) {
112
+ for (const pt of Object.keys(config.postTypes)) {
113
+ if (pt.length > 20) {
114
+ throw new Error(
115
+ `Custom Post Type "${pt}" configured in wp.config.ts exceeds the WordPress limit of 20 characters.`
116
+ );
117
+ }
118
+ }
119
+ }
120
+
121
+ if (!config.frameworkAdapter) {
122
+ config.frameworkAdapter = 'react';
123
+ }
124
+
125
+ // Execute plugin configuration validation hooks
126
+ if (config.plugins && Array.isArray(config.plugins)) {
127
+ for (const plugin of config.plugins) {
128
+ if (typeof plugin.validateConfig === 'function') {
129
+ plugin.validateConfig(config, themeRoot, { fs, path });
130
+ }
131
+ }
132
+ }
133
+
134
+ return config;
135
+ }
136
+
137
+ /**
138
+ * Helper to define theme configurations with TypeScript Intellisense autocompletion.
139
+ * @param {import('./types.js').ForgeWPThemeConfig} config
140
+ * @returns {import('./types.js').ForgeWPThemeConfig}
141
+ */
142
+ export function defineConfig(config) {
27
143
  return config;
28
144
  }