@forgewp/compiler 0.4.3 → 0.4.4

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 (133) hide show
  1. package/README.md +59 -0
  2. package/bin/add.js +20 -14
  3. package/bin/cli.js +145 -70
  4. package/bin/doctor.js +21 -12
  5. package/bin/export.js +69 -20
  6. package/bin/fresh.js +5 -0
  7. package/bin/i18n-extract.js +3 -10
  8. package/bin/i18n-translate.js +15 -24
  9. package/bin/make-block.js +13 -0
  10. package/bin/make-editable.js +166 -0
  11. package/bin/make-form.js +131 -0
  12. package/bin/make-loop.js +40 -43
  13. package/bin/make-mail.js +27 -0
  14. package/bin/make-post-type.js +57 -29
  15. package/bin/make-sandbox.js +62 -11
  16. package/bin/make-section.js +221 -0
  17. package/bin/make-shell.js +375 -0
  18. package/bin/repair.js +14 -26
  19. package/bin/seed.js +119 -0
  20. package/bin/sync-routes.js +107 -85
  21. package/lib/adapters/html-adapter.js +5 -0
  22. package/lib/adapters/stub-adapter.js +4 -0
  23. package/lib/add-component.js +153 -92
  24. package/lib/asset-loader.js +313 -3
  25. package/lib/assets/asset-graph.js +432 -0
  26. package/lib/assets/asset-pipeline.js +125 -0
  27. package/lib/assets/diagnostics-report.js +345 -0
  28. package/lib/assets/external-fetcher.js +173 -0
  29. package/lib/assets/font-orchestrator.js +348 -0
  30. package/lib/assets/font-usage-scanner.js +242 -0
  31. package/lib/assets/image-optimizer.js +229 -0
  32. package/lib/assets/index.js +51 -0
  33. package/lib/assets/preload-generator.js +70 -0
  34. package/lib/assets/public-url.js +153 -0
  35. package/lib/block-authoring-help.js +11 -0
  36. package/lib/blocks/ast-parser.js +67 -0
  37. package/lib/blocks/discover-blocks.js +146 -0
  38. package/lib/blocks/editor-scope.js +733 -0
  39. package/lib/blocks/editor-transpiler.js +1229 -0
  40. package/lib/blocks/index.js +2838 -0
  41. package/lib/blocks/php-transpiler.js +4928 -0
  42. package/lib/blocks/scanner.js +1487 -0
  43. package/lib/blocks/shared-utils.js +290 -0
  44. package/lib/blocks/source-sanitize.js +1449 -0
  45. package/lib/blueprints.js +31 -91
  46. package/lib/build-assets.js +38 -33
  47. package/lib/collect-page-template-routes.js +102 -0
  48. package/lib/collect-static-routes.js +175 -0
  49. package/lib/diagnostics.js +58 -33
  50. package/lib/export-theme.js +84 -5
  51. package/lib/extract-template-content.js +90 -0
  52. package/lib/forms-preview.js +42 -0
  53. package/lib/functions/cpt-routing.js +69 -0
  54. package/lib/functions/forms.js +2461 -0
  55. package/lib/functions/hydration-enqueuer.js +400 -0
  56. package/lib/functions/index.js +1623 -0
  57. package/lib/functions/load-menus.js +112 -0
  58. package/lib/functions/load-translations.js +148 -0
  59. package/lib/functions/rest-endpoints.js +2923 -0
  60. package/lib/functions/routing.js +765 -0
  61. package/lib/functions/seed-mock-data.js +392 -0
  62. package/lib/functions/seed-products.js +481 -0
  63. package/lib/functions/settings-page.js +273 -0
  64. package/lib/functions/theme-setup.js +494 -0
  65. package/lib/generate-theme.js +1916 -339
  66. package/lib/hydration/editable-schemas.js +332 -0
  67. package/lib/hydration/enter-hidden-initial.js +65 -0
  68. package/lib/hydration/form-schemas.js +227 -0
  69. package/lib/hydration/index.js +12 -0
  70. package/lib/hydration/is-interactive.js +951 -0
  71. package/lib/hydration/island-split.js +1231 -0
  72. package/lib/hydration/islands-scanner.js +599 -0
  73. package/lib/hydration/resolve-island-chunk.js +103 -0
  74. package/lib/hydration/resolve-island-component.js +52 -0
  75. package/lib/hydration/rollup-inputs.js +81 -0
  76. package/lib/hydration/root-class-extractor.js +220 -0
  77. package/lib/hydration/scan-app-providers.js +154 -0
  78. package/lib/hydration/static-lint.js +382 -0
  79. package/lib/hydration/transform.js +257 -0
  80. package/lib/hydration/uses-block-area.js +49 -0
  81. package/lib/hydration/utils.js +119 -0
  82. package/lib/i18n/translation-cache.js +141 -0
  83. package/lib/icon-registry.js +72 -0
  84. package/lib/index.d.ts +287 -8
  85. package/lib/index.js +2 -1
  86. package/lib/load-config.js +338 -242
  87. package/lib/mail-templates.js +37 -0
  88. package/lib/markup-processor.js +388 -102
  89. package/lib/node-runtime.js +7 -0
  90. package/lib/page-config-plugin.js +64 -20
  91. package/lib/php-builders.js +383 -44
  92. package/lib/react-adapter.js +983 -235
  93. package/lib/registration-metadata.js +11 -0
  94. package/lib/render-theme.mts +1410 -616
  95. package/lib/route-layout.js +76 -0
  96. package/lib/template-discovery.js +58 -0
  97. package/lib/theme-compatibility.js +32 -0
  98. package/lib/validate-export.js +2 -2
  99. package/lib/validate.js +27 -5
  100. package/lib/virtual-plugin.js +319 -0
  101. package/lib/walkthrough.md +26 -0
  102. package/package.json +16 -5
  103. package/templates/auth/cms/email-logs.json +9 -0
  104. package/templates/auth/cms/menus.json +11 -0
  105. package/templates/auth/cms/mock-data.json +123 -0
  106. package/templates/auth/cms/roles.json +7 -0
  107. package/templates/auth/cms/sessions.json +1 -0
  108. package/templates/auth/cms/site-settings.json +28 -0
  109. package/templates/auth/cms/translations.json +4 -0
  110. package/templates/auth/cms/users.json +46 -0
  111. package/templates/auth/components/forgot-password-form-wrapper.tsx +10 -2
  112. package/templates/auth/components/login-form-wrapper.tsx +118 -21
  113. package/templates/auth/components/reset-password-form-wrapper.tsx +10 -2
  114. package/templates/auth/components/signup-form-wrapper.tsx +2 -2
  115. package/templates/auth/components/verify-email-view-wrapper.tsx +5 -5
  116. package/templates/auth/pages/DashboardPage.tsx +1 -4
  117. package/templates/auth/pages/ForgotPasswordPage.tsx +1 -4
  118. package/templates/auth/pages/LoginPage.tsx +1 -4
  119. package/templates/auth/pages/ResetPasswordPage.tsx +1 -4
  120. package/templates/auth/pages/SignUpPage.tsx +1 -4
  121. package/templates/auth/pages/VerifyEmailPage.tsx +1 -4
  122. package/templates/auth/ui/button.tsx +57 -0
  123. package/templates/auth/ui/card.tsx +76 -0
  124. package/templates/auth/ui/field.tsx +242 -0
  125. package/templates/auth/ui/input.tsx +22 -0
  126. package/templates/auth/ui/label.tsx +24 -0
  127. package/templates/auth/ui/separator.tsx +31 -0
  128. package/templates/menus.json +12 -10
  129. package/templates/users.json +8 -4
  130. package/templates/wordpress.tsx +690 -245
  131. package/lib/block-compiler.js +0 -552
  132. package/lib/functions-builder.js +0 -2970
  133. package/lib/hydration-scanner.js +0 -833
@@ -0,0 +1,392 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { parseSource, traverse } from '../blocks/ast-parser.js';
5
+
6
+ export function validateMockSeedStrategy(value) {
7
+ const valid = (strategy) => [true, false, 'once', 'upsert', 'force'].includes(strategy);
8
+ if (value === undefined || valid(value)) return;
9
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
10
+ throw new Error('Invalid seed.mockData: expected a seed strategy or a post-type strategy map.');
11
+ }
12
+ for (const [postType, strategy] of Object.entries(value)) {
13
+ if (!/^[a-z0-9_-]{1,20}$/.test(postType) || !valid(strategy)) {
14
+ throw new Error(`Invalid seed.mockData entry "${postType}": expected a post-type key and false, true, "once", "upsert", or "force".`);
15
+ }
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Converts a Babel AST literal/object/array node to a JS value.
21
+ */
22
+ function astToValue(node) {
23
+ if (!node) return null;
24
+ switch (node.type) {
25
+ case 'StringLiteral':
26
+ return node.value;
27
+ case 'NumericLiteral':
28
+ return node.value;
29
+ case 'BooleanLiteral':
30
+ return node.value;
31
+ case 'NullLiteral':
32
+ return null;
33
+ case 'ArrayExpression':
34
+ return node.elements.map((el) => astToValue(el));
35
+ case 'ObjectExpression': {
36
+ const obj = {};
37
+ for (const prop of node.properties) {
38
+ if (prop.type === 'ObjectProperty') {
39
+ const key = prop.key.name || prop.key.value;
40
+ obj[key] = astToValue(prop.value);
41
+ }
42
+ }
43
+ return obj;
44
+ }
45
+ case 'UnaryExpression': {
46
+ if (node.operator === '-' && node.argument?.type === 'NumericLiteral') {
47
+ return -node.argument.value;
48
+ }
49
+ return null;
50
+ }
51
+ case 'CallExpression': {
52
+ // Handles defineWpPosts({...}) wrapper
53
+ if (node.arguments && node.arguments[0]) {
54
+ return astToValue(node.arguments[0]);
55
+ }
56
+ return null;
57
+ }
58
+ default:
59
+ return null;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Loads mock content from cms/mock-data.ts or cms/mock-data.json.
65
+ * @param {string} themeRoot
66
+ * @returns {Record<string, Array<any>>}
67
+ */
68
+ export function loadMockData(themeRoot) {
69
+ const tsPath = path.join(themeRoot, 'cms', 'mock-data.ts');
70
+ const jsonPath = path.join(themeRoot, 'cms', 'mock-data.json');
71
+
72
+ if (fs.existsSync(tsPath)) {
73
+ try {
74
+ const code = fs.readFileSync(tsPath, 'utf8');
75
+ const ast = parseSource(code);
76
+ let extracted = null;
77
+
78
+ traverse(ast, {
79
+ ExportNamedDeclaration(astPath) {
80
+ const decl = astPath.node.declaration;
81
+ if (decl && decl.declarations) {
82
+ for (const d of decl.declarations) {
83
+ if (d.id?.name === 'mockData' && d.init) {
84
+ extracted = astToValue(d.init);
85
+ }
86
+ }
87
+ }
88
+ },
89
+ ExportDefaultDeclaration(astPath) {
90
+ if (!extracted && astPath.node.declaration) {
91
+ extracted = astToValue(astPath.node.declaration);
92
+ }
93
+ },
94
+ });
95
+
96
+ if (extracted && typeof extracted === 'object' && !Array.isArray(extracted)) return extracted;
97
+ } catch (e) {
98
+ console.warn(`⚠️ [ForgeWP Seed] Could not load ${tsPath}: ${e.message}`);
99
+ }
100
+ }
101
+
102
+ if (fs.existsSync(jsonPath)) {
103
+ try {
104
+ const raw = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
105
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw;
106
+ } catch (e) {
107
+ console.warn(`⚠️ [ForgeWP Seed] Could not parse ${jsonPath}: ${e.message}`);
108
+ }
109
+ }
110
+
111
+ return {};
112
+ }
113
+
114
+ /**
115
+ * Shared fixture normalization for generated PHP and the read-only CLI preview.
116
+ */
117
+ export function normalizeMockSeedData(rawMockData, mockStrategy) {
118
+ const postTypesToSeed = Object.keys(rawMockData);
119
+ const strategyMap = mockStrategy && typeof mockStrategy === 'object' ? mockStrategy : null;
120
+ if (!mockStrategy) return {};
121
+ const normalizedData = {};
122
+
123
+ for (const postType of postTypesToSeed) {
124
+ // Maps opt in explicitly: omitted/disabled types never enter the payload,
125
+ // including when the WordPress command is run with --force.
126
+ if (strategyMap && (!Object.hasOwn(strategyMap, postType) || strategyMap[postType] === false)) continue;
127
+ const items = rawMockData[postType];
128
+ if (!Array.isArray(items) || items.length === 0) continue;
129
+
130
+ normalizedData[postType] = items.map((item, idx) => {
131
+ const title = item.title || item.name || `Sample ${postType} ${idx + 1}`;
132
+ const slug = item.slug || `sample-${postType}-${item.id || idx + 1}`;
133
+ const content = item.content || '';
134
+ const excerpt = item.excerpt || item.description || '';
135
+ const date = item.date || '';
136
+ const featuredImage = item.featuredImage || (Array.isArray(item.images) ? item.images[0] : '');
137
+ const customFields = item.customFields || item.meta || {};
138
+
139
+ // Terms
140
+ let terms = {};
141
+ if (item._terms && typeof item._terms === 'object') {
142
+ terms = item._terms;
143
+ } else {
144
+ if (item.category) {
145
+ terms.category = [item.category];
146
+ } else if (Array.isArray(item.categories)) {
147
+ terms.category = item.categories;
148
+ }
149
+ if (Array.isArray(item.tags)) {
150
+ terms.post_tag = item.tags;
151
+ }
152
+ }
153
+
154
+ return {
155
+ title,
156
+ slug,
157
+ content,
158
+ excerpt,
159
+ date,
160
+ featuredImage,
161
+ customFields,
162
+ terms,
163
+ };
164
+ });
165
+ }
166
+
167
+ return normalizedData;
168
+ }
169
+
170
+ /** Build configured WordPress seed routines without connecting to a database. */
171
+ export function buildSeedMockDataPhp(config, themeRoot) {
172
+ const seedConfig = config.seed;
173
+ validateMockSeedStrategy(seedConfig?.mockData);
174
+ if (!seedConfig || !seedConfig.mockData) {
175
+ return '';
176
+ }
177
+
178
+ const rawMockData = loadMockData(themeRoot);
179
+ const postTypesToSeed = Object.keys(rawMockData);
180
+
181
+ if (postTypesToSeed.length === 0) {
182
+ return '';
183
+ }
184
+
185
+ const defaultStrategy = typeof seedConfig.mockData === 'string' ? seedConfig.mockData : 'once';
186
+ const strategyMap = typeof seedConfig.mockData === 'object' ? seedConfig.mockData : null;
187
+ const developmentOnly = seedConfig.developmentOnly !== false;
188
+ const sideloadImages = seedConfig.sideloadImages !== false;
189
+
190
+ const normalizedData = normalizeMockSeedData(rawMockData, seedConfig.mockData);
191
+
192
+ if (Object.keys(normalizedData).length === 0) {
193
+ return '';
194
+ }
195
+
196
+ const mockDataJson = JSON.stringify(normalizedData, null, 2);
197
+ const dataHash = crypto.createHash('sha256').update(mockDataJson).digest('hex');
198
+ const typeState = {};
199
+ if (strategyMap) {
200
+ for (const [postType, posts] of Object.entries(normalizedData)) {
201
+ const strategy = strategyMap[postType] === true ? 'once' : strategyMap[postType];
202
+ typeState[postType] = {
203
+ strategy,
204
+ hash: crypto.createHash('sha256').update(JSON.stringify({ strategy, posts })).digest('hex'),
205
+ };
206
+ }
207
+ }
208
+
209
+ return `
210
+ /**
211
+ * ==============================================================================
212
+ * ForgeWP Mock Content Data Seeder
213
+ * Post Types: ${Object.keys(normalizedData).join(', ')} | Hash: ${dataHash.substring(0, 12)}
214
+ * ==============================================================================
215
+ */
216
+ function forgewp_seed_mock_content($force = false) {
217
+ ${developmentOnly ? `
218
+ // Production Safety Guard: only run in WP_DEBUG mode unless forced
219
+ if (!$force && (!defined('WP_DEBUG') || !WP_DEBUG)) {
220
+ return;
221
+ }
222
+ ` : ''}
223
+ $current_hash = '${dataHash}';
224
+ $saved_hash = get_option('forgewp_seeded_mock_data_hash', '');
225
+ $default_strategy = '${defaultStrategy}';
226
+
227
+ // Scalar strategies retain their existing global marker semantics.
228
+ if (${strategyMap ? 'false' : 'true'} && !$force && $default_strategy === 'once' && !empty($saved_hash)) {
229
+ return;
230
+ }
231
+
232
+ // In 'upsert' mode, skip if content hash matches
233
+ if (${strategyMap ? 'false' : 'true'} && !$force && $default_strategy === 'upsert' && $saved_hash === $current_hash) {
234
+ return;
235
+ }
236
+
237
+ $raw_json = <<<'FORGEWP_MOCK_DATA_JSON'
238
+ ${mockDataJson}
239
+ FORGEWP_MOCK_DATA_JSON;
240
+
241
+ $mock_data = json_decode($raw_json, true);
242
+ if (!is_array($mock_data)) {
243
+ return;
244
+ }
245
+ $type_state = json_decode(base64_decode('${Buffer.from(JSON.stringify(typeState)).toString('base64')}'), true);
246
+ $saved_type_hashes = get_option('forgewp_seeded_mock_data_type_hashes', array());
247
+ if (!is_array($saved_type_hashes)) $saved_type_hashes = array();
248
+
249
+ // Ensure media handling helpers exist if sideloading images
250
+ if (${sideloadImages ? 'true' : 'false'} && !function_exists('media_sideload_image')) {
251
+ require_once ABSPATH . 'wp-admin/includes/media.php';
252
+ require_once ABSPATH . 'wp-admin/includes/file.php';
253
+ require_once ABSPATH . 'wp-admin/includes/image.php';
254
+ }
255
+
256
+ // Determine default author (administrator)
257
+ $default_author_id = 1;
258
+ $admin_users = get_users(array('role' => 'administrator', 'number' => 1));
259
+ if (!empty($admin_users) && isset($admin_users[0]->ID)) {
260
+ $default_author_id = $admin_users[0]->ID;
261
+ }
262
+
263
+ foreach ($mock_data as $post_type => $posts) {
264
+ if (!is_array($posts)) {
265
+ continue;
266
+ }
267
+ $strategy = isset($type_state[$post_type]) ? $type_state[$post_type]['strategy'] : $default_strategy;
268
+ $type_hash = isset($type_state[$post_type]) ? $type_state[$post_type]['hash'] : '';
269
+ $saved_type_hash = isset($saved_type_hashes[$post_type]) ? $saved_type_hashes[$post_type] : '';
270
+ if (!$force && $type_hash !== '' && (($strategy === 'once' && $saved_type_hash !== '') || ($strategy === 'upsert' && $saved_type_hash === $type_hash))) continue;
271
+ $type_succeeded = true;
272
+
273
+ // In 'once' mode, check if any posts of this post_type already exist in WP
274
+ if (!$force && $strategy === 'once') {
275
+ $existing_count = wp_count_posts($post_type);
276
+ if (!empty($existing_count->publish) && intval($existing_count->publish) > 0) {
277
+ continue;
278
+ }
279
+ }
280
+
281
+ foreach ($posts as $item) {
282
+ $title = !empty($item['title']) ? sanitize_text_field($item['title']) : '';
283
+ $slug = !empty($item['slug']) ? sanitize_title($item['slug']) : '';
284
+ if (empty($title)) {
285
+ continue;
286
+ }
287
+
288
+ // Check if post already exists by slug and post_type
289
+ $existing_post = get_page_by_path($slug, OBJECT, $post_type);
290
+ $post_id = $existing_post ? $existing_post->ID : 0;
291
+
292
+ if ($post_id && $strategy === 'once' && !$force) {
293
+ continue;
294
+ }
295
+
296
+ $post_args = array(
297
+ 'post_title' => $title,
298
+ 'post_name' => $slug,
299
+ 'post_type' => $post_type,
300
+ 'post_status' => 'publish',
301
+ 'post_content' => !empty($item['content']) ? $item['content'] : '',
302
+ 'post_excerpt' => !empty($item['excerpt']) ? $item['excerpt'] : '',
303
+ 'post_author' => $default_author_id,
304
+ );
305
+
306
+ if (!empty($item['date'])) {
307
+ $parsed_date = date('Y-m-d H:i:s', strtotime($item['date']));
308
+ if ($parsed_date) {
309
+ $post_args['post_date'] = $parsed_date;
310
+ }
311
+ }
312
+
313
+ if ($post_id) {
314
+ $post_args['ID'] = $post_id;
315
+ $saved_post_id = wp_update_post($post_args, true);
316
+ } else {
317
+ $saved_post_id = wp_insert_post($post_args, true);
318
+ }
319
+
320
+ if (!$saved_post_id || is_wp_error($saved_post_id)) {
321
+ $type_succeeded = false;
322
+ continue;
323
+ }
324
+ if ($saved_post_id && !is_wp_error($saved_post_id)) {
325
+ // Save custom fields
326
+ if (!empty($item['customFields']) && is_array($item['customFields'])) {
327
+ foreach ($item['customFields'] as $meta_key => $meta_val) {
328
+ update_post_meta($saved_post_id, sanitize_key($meta_key), $meta_val);
329
+ }
330
+ }
331
+
332
+ // Assign Taxonomies and Terms
333
+ if (!empty($item['terms']) && is_array($item['terms'])) {
334
+ foreach ($item['terms'] as $tax_name => $tax_terms) {
335
+ if (taxonomy_exists($tax_name) && !empty($tax_terms)) {
336
+ $term_names = array();
337
+ if (is_array($tax_terms)) {
338
+ foreach ($tax_terms as $t) {
339
+ $term_names[] = is_array($t) ? ($t['name'] ?? $t['slug'] ?? '') : strval($t);
340
+ }
341
+ } else {
342
+ $term_names[] = strval($tax_terms);
343
+ }
344
+ $term_names = array_filter($term_names);
345
+ if (!empty($term_names)) {
346
+ wp_set_post_terms($saved_post_id, $term_names, $tax_name, false);
347
+ }
348
+ }
349
+ }
350
+ }
351
+
352
+ // Sideload Featured Image
353
+ ${sideloadImages ? `
354
+ if (!empty($item['featuredImage']) && filter_var($item['featuredImage'], FILTER_VALIDATE_URL) && !has_post_thumbnail($saved_post_id)) {
355
+ $attach_id = media_sideload_image($item['featuredImage'], $saved_post_id, $title, 'id');
356
+ if (!is_wp_error($attach_id) && is_numeric($attach_id)) {
357
+ set_post_thumbnail($saved_post_id, intval($attach_id));
358
+ }
359
+ }
360
+ ` : ''}
361
+ }
362
+ }
363
+ if ($type_hash !== '' && $type_succeeded) {
364
+ $saved_type_hashes[$post_type] = $type_hash;
365
+ }
366
+ }
367
+
368
+ ${strategyMap ? "update_option('forgewp_seeded_mock_data_type_hashes', $saved_type_hashes);" : "update_option('forgewp_seeded_mock_data_hash', $current_hash);"}
369
+ }
370
+
371
+ // Hook into theme activation and admin initialization
372
+ add_action('after_switch_theme', function() {
373
+ // WordPress passes the old theme name here; it must not become $force.
374
+ forgewp_seed_mock_content();
375
+ });
376
+ add_action('admin_init', function() {
377
+ if (current_user_can('edit_posts')) {
378
+ forgewp_seed_mock_content();
379
+ }
380
+ });
381
+
382
+ // WP-CLI command registration: wp forgewp seed-mock-data
383
+ if (defined('WP_CLI') && WP_CLI) {
384
+ WP_CLI::add_command('forgewp seed-mock-data', function($args, $assoc_args) {
385
+ $force = isset($assoc_args['force']);
386
+ WP_CLI::log('🌱 Seeding mock content (posts, pages, CPTs) from ForgeWP CMS mock-data...');
387
+ forgewp_seed_mock_content($force);
388
+ WP_CLI::success('Mock content successfully synchronized!');
389
+ });
390
+ }
391
+ `;
392
+ }