@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
@@ -45,30 +45,16 @@ if (!cleanName) {
45
45
 
46
46
  const projectRoot = process.cwd();
47
47
  const wpDir = path.join(projectRoot, "cms");
48
- const mockDataPath = path.join(wpDir, "mock-data.json");
48
+ const mockDataTsPath = path.join(wpDir, "mock-data.ts");
49
+ const mockDataJsonPath = path.join(wpDir, "mock-data.json");
50
+ const isTs = existsSync(mockDataTsPath) || !existsSync(mockDataJsonPath);
51
+ const activeFile = isTs ? "cms/mock-data.ts" : "cms/mock-data.json";
49
52
 
50
53
  // Ensure cms directory exists
51
54
  if (!existsSync(wpDir)) {
52
55
  mkdirSync(wpDir, { recursive: true });
53
56
  }
54
57
 
55
- let mockData = {};
56
-
57
- if (existsSync(mockDataPath)) {
58
- try {
59
- mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
60
- } catch (err) {
61
- console.error(pc.red(`\n❌ Error: Failed to parse cms/mock-data.json. Enforcing clean file.`));
62
- mockData = {};
63
- }
64
- }
65
-
66
- if (mockData[cleanName]) {
67
- console.warn(pc.yellow(`\n⚠️ Post type "${cleanName}" already exists in cms/mock-data.json.`));
68
- console.log(` You can open the file directly to view or edit existing fields.\n`);
69
- process.exit(0);
70
- }
71
-
72
58
  // Parse custom fields if provided via --customFields, -customFields, --custom-fields, etc.
73
59
  let customFieldsList = [];
74
60
  const fieldsArg = args.find(a => /^-+custom[Ff]ields=/.test(a) || /^-+custom-fields=/.test(a));
@@ -94,7 +80,6 @@ if (customFieldsList.length > 0) {
94
80
  seededCustomFields2[field] = `[Seeded ${field} 2]`;
95
81
  }
96
82
  } else {
97
- // Default fallbacks if no flag is provided
98
83
  seededCustomFields1["client_name"] = "Mock Enterprise";
99
84
  seededCustomFields1["project_budget"] = "$30,000";
100
85
 
@@ -102,37 +87,80 @@ if (customFieldsList.length > 0) {
102
87
  seededCustomFields2["project_budget"] = "$55,000";
103
88
  }
104
89
 
105
- // Generate template seed items for this custom post type
106
- mockData[cleanName] = [
90
+ const cleanTitle = cleanName.charAt(0).toUpperCase() + cleanName.slice(1);
91
+ const dateStr = new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
92
+
93
+ const seedItems = [
107
94
  {
108
95
  id: 1,
109
- title: `Sample ${cleanName.charAt(0).toUpperCase() + cleanName.slice(1)} Item 1`,
96
+ title: `Sample ${cleanTitle} Item 1`,
110
97
  excerpt: `This is a custom ${cleanName} post seeded dynamically via ForgeWP CLI.`,
111
- content: `<p>Welcome to your new custom <strong>${cleanName}</strong> post template! Edit this in cms/mock-data.json.</p>`,
112
- date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
98
+ content: `<p>Welcome to your new custom <strong>${cleanName}</strong> post template! Edit this in ${activeFile}.</p>`,
99
+ date: dateStr,
113
100
  author: "ForgeWP CLI",
114
101
  featuredImage: `https://picsum.photos/seed/${cleanName}1/1200/630`,
115
102
  customFields: seededCustomFields1
116
103
  },
117
104
  {
118
105
  id: 2,
119
- title: `Sample ${cleanName.charAt(0).toUpperCase() + cleanName.slice(1)} Item 2`,
106
+ title: `Sample ${cleanTitle} Item 2`,
120
107
  excerpt: `This is another custom ${cleanName} post seeded dynamically via ForgeWP CLI.`,
121
108
  content: `<p>This is the second custom post for the ${cleanName} post type.</p>`,
122
- date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
109
+ date: dateStr,
123
110
  author: "ForgeWP CLI",
124
111
  featuredImage: `https://picsum.photos/seed/${cleanName}2/1200/630`,
125
112
  customFields: seededCustomFields2
126
113
  }
127
114
  ];
128
115
 
129
- // Write update JSON back to file
130
- writeFileSync(mockDataPath, JSON.stringify(mockData, null, 2), "utf8");
116
+ if (isTs) {
117
+ if (existsSync(mockDataTsPath)) {
118
+ let content = readFileSync(mockDataTsPath, "utf8");
119
+ if (content.includes(`"${cleanName}":`) || content.includes(`${cleanName}:`)) {
120
+ console.warn(pc.yellow(`\n⚠️ Post type "${cleanName}" already exists in cms/mock-data.ts.`));
121
+ console.log(` You can open the file directly to view or edit existing fields.\n`);
122
+ process.exit(0);
123
+ }
124
+
125
+ const snippet = ` ${cleanName}: ${JSON.stringify(seedItems, null, 4).replace(/^/gm, " ").trim()},\n`;
126
+ if (content.includes("defineWpPosts({")) {
127
+ content = content.replace("defineWpPosts({", "defineWpPosts({\n" + snippet);
128
+ } else if (content.lastIndexOf("};") !== -1) {
129
+ const idx = content.lastIndexOf("};");
130
+ content = content.slice(0, idx) + snippet + content.slice(idx);
131
+ } else {
132
+ content += `\n\n// Added custom post type: ${cleanName}\n${snippet}`;
133
+ }
134
+ writeFileSync(mockDataTsPath, content, "utf8");
135
+ } else {
136
+ const defaultTs = `import { defineWpPosts } from '@forgewp/react';\n\nexport const mockData = defineWpPosts({\n post: [],\n ${cleanName}: ${JSON.stringify(seedItems, null, 4).replace(/^/gm, " ").trim()}\n});\n\nexport default mockData;\n`;
137
+ writeFileSync(mockDataTsPath, defaultTs, "utf8");
138
+ }
139
+ } else {
140
+ let mockData = {};
141
+ if (existsSync(mockDataJsonPath)) {
142
+ try {
143
+ mockData = JSON.parse(readFileSync(mockDataJsonPath, "utf8"));
144
+ } catch (err) {
145
+ console.error(pc.red(`\n❌ Error: Failed to parse cms/mock-data.json. Enforcing clean file.`));
146
+ mockData = {};
147
+ }
148
+ }
149
+
150
+ if (mockData[cleanName]) {
151
+ console.warn(pc.yellow(`\n⚠️ Post type "${cleanName}" already exists in cms/mock-data.json.`));
152
+ console.log(` You can open the file directly to view or edit existing fields.\n`);
153
+ process.exit(0);
154
+ }
155
+
156
+ mockData[cleanName] = seedItems;
157
+ writeFileSync(mockDataJsonPath, JSON.stringify(mockData, null, 2), "utf8");
158
+ }
131
159
 
132
160
  const suggestedField = customFieldsList.length > 0 ? customFieldsList[0] : "client_name";
133
161
 
134
162
  console.log(pc.green(`\n⚡ Post Type "${cleanName}" successfully registered!`));
135
- console.log(` Local DB: ${pc.cyan(`cms/mock-data.json`)}`);
163
+ console.log(` Local DB: ${pc.cyan(activeFile)}`);
136
164
  console.log(`\n🎉 Query your seeded fields in React inside:`);
137
165
  console.log(` ${pc.yellow(`<WpQueryLoop postType="${cleanName}" postsPerPage={2}>`)}`);
138
166
  console.log(` ${pc.yellow(`<h3>{useWpTitle()}</h3>`)}`);
@@ -6,6 +6,7 @@ import pc from "picocolors";
6
6
  import { spawnSync } from "node:child_process";
7
7
  import readline from "node:readline";
8
8
  import { fileURLToPath } from "node:url";
9
+ import { addComponent } from "../lib/add-component.js";
9
10
 
10
11
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
11
12
 
@@ -60,7 +61,7 @@ if (type === "ecommerce") {
60
61
 
61
62
  // 1. Add dependency to package.json
62
63
  const isWorkspace = existsSync(path.join(projectRoot, "..", "..", "pnpm-workspace.yaml")) || existsSync(path.join(projectRoot, "..", "pnpm-workspace.yaml"));
63
- const versionToUse = isWorkspace ? "workspace:*" : "^0.4.2";
64
+ const versionToUse = isWorkspace ? "workspace:*" : "^0.1.1";
64
65
 
65
66
  if (!packageJson.dependencies) {
66
67
  packageJson.dependencies = {};
@@ -119,6 +120,13 @@ if (type === "ecommerce") {
119
120
  }
120
121
 
121
122
  function seedEcommerceData() {
123
+ const productsTsPath = path.join(wpDir, "products.ts");
124
+ if (existsSync(productsTsPath)) {
125
+ console.warn(pc.yellow(`\n⚠️ E-Commerce mock data already exists in cms/products.ts.`));
126
+ console.log(` You can open the file directly to view or edit existing mock products.\n`);
127
+ return;
128
+ }
129
+
122
130
  const productsPath = path.join(wpDir, "products.json");
123
131
  let productsData = {
124
132
  "product": [],
@@ -364,9 +372,13 @@ if (type === "auth") {
364
372
  const usersPath = path.join(wpDir, "users.json");
365
373
  const rolesPath = path.join(wpDir, "roles.json");
366
374
  const sessionsPath = path.join(wpDir, "sessions.json");
375
+ const usersTsPath = path.join(wpDir, "users.ts");
376
+ const rolesTsPath = path.join(wpDir, "roles.ts");
377
+ const hasUsers = existsSync(usersPath) || existsSync(usersTsPath);
378
+ const hasRoles = existsSync(rolesPath) || existsSync(rolesTsPath);
367
379
 
368
- // 1. Seed JSON files
369
- if (!existsSync(usersPath) || !existsSync(rolesPath) || !existsSync(sessionsPath)) {
380
+ // 1. Seed JSON files (skip when the typed .ts source already exists)
381
+ if (!hasUsers || !hasRoles || !existsSync(sessionsPath)) {
370
382
  const seededUsers = [
371
383
  {
372
384
  "id": 1,
@@ -416,8 +428,8 @@ if (type === "auth") {
416
428
 
417
429
  const seededSessions = [];
418
430
 
419
- if (!existsSync(usersPath)) writeFileSync(usersPath, JSON.stringify(seededUsers, null, 2), "utf8");
420
- if (!existsSync(rolesPath)) writeFileSync(rolesPath, JSON.stringify(seededRoles, null, 2), "utf8");
431
+ if (!hasUsers) writeFileSync(usersPath, JSON.stringify(seededUsers, null, 2), "utf8");
432
+ if (!hasRoles) writeFileSync(rolesPath, JSON.stringify(seededRoles, null, 2), "utf8");
421
433
  if (!existsSync(sessionsPath)) writeFileSync(sessionsPath, JSON.stringify(seededSessions, null, 2), "utf8");
422
434
 
423
435
  console.log(pc.green(` ✅ Seeded authentication mock data files in cms/`));
@@ -438,6 +450,45 @@ if (type === "auth") {
438
450
  console.log(pc.green(` ✅ Created file: ${path.relative(projectRoot, dest)}`));
439
451
  };
440
452
 
453
+ // 2. Provision UI primitives from canonical auth templates
454
+ const uiSrcDir = path.join(templatesDir, 'ui');
455
+ const uiDestDir = path.join(projectRoot, 'src', 'components', 'ui');
456
+ if (existsSync(uiSrcDir)) {
457
+ const uiFiles = ['button.tsx', 'card.tsx', 'field.tsx', 'input.tsx', 'label.tsx', 'separator.tsx'];
458
+ for (const uiFile of uiFiles) {
459
+ const srcFile = path.join(uiSrcDir, uiFile);
460
+ if (existsSync(srcFile)) {
461
+ copyIfNotExist(srcFile, path.join(uiDestDir, uiFile));
462
+ }
463
+ }
464
+ }
465
+
466
+ // Fallback: If any required UI component is missing, pull via shadcn add
467
+ let projectStyle = "shadcn";
468
+ try {
469
+ const wpConfigPath = path.join(projectRoot, "wp.config.ts");
470
+ if (existsSync(wpConfigPath)) {
471
+ const content = readFileSync(wpConfigPath, "utf8");
472
+ const styleMatch = content.match(/style:\s*['"](forgewp|shadcn)['"]/);
473
+ if (styleMatch && styleMatch[1]) {
474
+ projectStyle = styleMatch[1];
475
+ }
476
+ }
477
+ } catch (e) {}
478
+
479
+ const requiredUi = ["card", "input", "button", "field"];
480
+ for (const uiComp of requiredUi) {
481
+ const compFile = path.join(uiDestDir, `${uiComp}.tsx`);
482
+ if (!existsSync(compFile)) {
483
+ try {
484
+ console.log(pc.cyan(` 📦 Pulling required "${uiComp}" UI component via shadcn...`));
485
+ await addComponent(uiComp, { style: projectStyle });
486
+ } catch (err) {
487
+ console.warn(pc.yellow(` ⚠ Could not auto-add "${uiComp}": ${err.message}`));
488
+ }
489
+ }
490
+ }
491
+
441
492
  const componentsSrcDir = path.join(templatesDir, 'components');
442
493
  const componentsDestDir = path.join(projectRoot, 'src', 'components');
443
494
  if (existsSync(componentsSrcDir)) {
@@ -463,7 +514,7 @@ if (type === "auth") {
463
514
  if (existsSync(layoutPath)) {
464
515
  let layoutContent = readFileSync(layoutPath, 'utf8');
465
516
  if (!layoutContent.includes('WpAuthProvider')) {
466
- layoutContent = 'import { WpAuthProvider } from "../.forgewp/wordpress";\n' + layoutContent;
517
+ layoutContent = 'import { WpAuthProvider } from "@forgewp/auth";\n' + layoutContent;
467
518
  // Robustly wrap JSX children with WpAuthProvider
468
519
  layoutContent = layoutContent.replace(/(>\s*)\{\s*children\s*\}(\s*<)/, '$1<WpAuthProvider>{children}</WpAuthProvider>$2');
469
520
  writeFileSync(layoutPath, layoutContent, 'utf8');
@@ -476,14 +527,14 @@ if (type === "auth") {
476
527
  if (existsSync(routesPath)) {
477
528
  let routesContent = readFileSync(routesPath, 'utf8');
478
529
  if (!routesContent.includes('/forgot-password')) {
479
- const importBlock = `import LoginPage from "./pages/LoginPage";\nimport SignUpPage from "./pages/SignUpPage";\nimport VerifyEmailPage from "./pages/VerifyEmailPage";\nimport ForgotPasswordPage from "./pages/ForgotPasswordPage";\nimport ResetPasswordPage from "./pages/ResetPasswordPage";\n`;
530
+ const importBlock = `import * as LoginPage from "./pages/LoginPage";\nimport * as SignUpPage from "./pages/SignUpPage";\nimport * as VerifyEmailPage from "./pages/VerifyEmailPage";\nimport * as ForgotPasswordPage from "./pages/ForgotPasswordPage";\nimport * as ResetPasswordPage from "./pages/ResetPasswordPage";\n`;
480
531
  routesContent = importBlock + routesContent;
481
532
 
482
- const routesBlock = ` <Route path="/login" component={LoginPage} />\n <Route path="/signup" component={SignUpPage} />\n <Route path="/verify-email" component={VerifyEmailPage} />\n <Route path="/forgot-password" component={ForgotPasswordPage} />\n <Route path="/reset-password" component={ResetPasswordPage} />\n`;
533
+ const routesBlock = ` <Route path="/login" component={withLayout(LoginPage)} />\n <Route path="/signup" component={withLayout(SignUpPage)} />\n <Route path="/verify-email" component={withLayout(VerifyEmailPage)} />\n <Route path="/forgot-password" component={withLayout(ForgotPasswordPage)} />\n <Route path="/reset-password" component={withLayout(ResetPasswordPage)} />\n`;
483
534
  if (routesContent.includes('<Route path="/query-sandbox"')) {
484
535
  routesContent = routesContent.replace('<Route path="/query-sandbox"', routesBlock + ' <Route path="/query-sandbox"');
485
- } else if (routesContent.includes('<Route path="/" component={HomePage} />')) {
486
- routesContent = routesContent.replace('<Route path="/" component={HomePage} />', '<Route path="/" component={HomePage} />\n' + routesBlock);
536
+ } else if (routesContent.includes('<Route path="/" component={withLayout(HomePage)} />') || routesContent.includes('<Route path="/" component={HomePage} />')) {
537
+ routesContent = routesContent.replace(/<Route path="\/" component=\{.*?\} \/>/, (match) => `${match}\n${routesBlock}`);
487
538
  } else {
488
539
  routesContent = routesContent.replace(/<Switch>/i, `<Switch>\n${routesBlock}`);
489
540
  }
@@ -548,7 +599,7 @@ if (type === "auth") {
548
599
  if (!packageJson.dependencies) packageJson.dependencies = {};
549
600
  if (!packageJson.dependencies['@forgewp/auth']) {
550
601
  const isWorkspace = existsSync(path.join(projectRoot, '..', 'pnpm-workspace.yaml'));
551
- packageJson.dependencies['@forgewp/auth'] = isWorkspace ? 'workspace:*' : '^0.1.0';
602
+ packageJson.dependencies['@forgewp/auth'] = isWorkspace ? 'workspace:*' : '^0.1.2';
552
603
  writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n', 'utf8');
553
604
  console.log(pc.green(` ✅ Added @forgewp/auth to package.json dependencies`));
554
605
  }
@@ -0,0 +1,221 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import pc from 'picocolors';
6
+
7
+ const args = process.argv.slice(2);
8
+
9
+ function getOption(name, fallback = '') {
10
+ const exactIndex = args.indexOf(`--${name}`);
11
+ if (exactIndex !== -1 && args[exactIndex + 1]) return args[exactIndex + 1];
12
+ const equal = args.find((arg) => arg.startsWith(`--${name}=`));
13
+ return equal ? equal.slice(name.length + 3) : fallback;
14
+ }
15
+
16
+ function toKebabCase(value) {
17
+ return value
18
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
19
+ .replace(/[\s_]+/g, '-')
20
+ .toLowerCase()
21
+ .replace(/[^a-z0-9-]/g, '')
22
+ .replace(/-+/g, '-')
23
+ .replace(/^-|-$/g, '');
24
+ }
25
+
26
+ function toPascalCase(value) {
27
+ return value
28
+ .split(/[-_\s]+/)
29
+ .filter(Boolean)
30
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
31
+ .join('');
32
+ }
33
+
34
+ function toSnakeCase(value) {
35
+ return value
36
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
37
+ .replace(/[\s-]+/g, '_')
38
+ .toLowerCase();
39
+ }
40
+
41
+ function parseFields() {
42
+ const raw = getOption('fields');
43
+ if (!raw) {
44
+ return [
45
+ { name: 'title', type: 'text' },
46
+ { name: 'description', type: 'richText' },
47
+ ];
48
+ }
49
+
50
+ const validTypes = new Set([
51
+ 'text',
52
+ 'richText',
53
+ 'image',
54
+ 'boolean',
55
+ 'repeater',
56
+ 'color',
57
+ 'url',
58
+ 'select',
59
+ 'number',
60
+ 'icon',
61
+ ]);
62
+
63
+ return raw
64
+ .split(',')
65
+ .map((entry) => entry.trim())
66
+ .filter(Boolean)
67
+ .map((entry) => {
68
+ const [name, requestedType = 'text'] = entry
69
+ .split(':')
70
+ .map((part) => part.trim());
71
+ return {
72
+ name,
73
+ type: validTypes.has(requestedType) ? requestedType : 'text',
74
+ };
75
+ })
76
+ .filter((field) => /^[a-zA-Z_$][\w$]*$/.test(field.name));
77
+ }
78
+
79
+ const rawName = getOption('name') || args.find((arg) => !arg.startsWith('-'));
80
+ if (!rawName) {
81
+ console.error(pc.red('\n❌ Error: Please specify a section name.'));
82
+ console.log(
83
+ pc.cyan(
84
+ ' Example: pnpm forgewp make:section HeroSection --page=front-page --block\n',
85
+ ),
86
+ );
87
+ process.exit(1);
88
+ }
89
+
90
+ const projectRoot = process.cwd();
91
+ if (!existsSync(path.join(projectRoot, 'src'))) {
92
+ console.error(
93
+ pc.red('\n❌ Error: "src" folder not found. Are you in your theme root?\n'),
94
+ );
95
+ process.exit(1);
96
+ }
97
+
98
+ const componentName = toPascalCase(rawName);
99
+ const slug =
100
+ toKebabCase(componentName.replace(/Section$/, '')) ||
101
+ toKebabCase(componentName);
102
+ const pageSlug = toKebabCase(getOption('page', 'front-page'));
103
+ const fields = parseFields();
104
+ const withBlock = args.includes('--block') || args.includes('--block=true');
105
+
106
+ if (fields.length === 0) {
107
+ console.error(pc.red('\n❌ Error: No valid fields were provided.\n'));
108
+ process.exit(1);
109
+ }
110
+
111
+ const schemaDir = path.join(projectRoot, 'cms', 'editables', 'sections');
112
+ const componentDir = path.join(projectRoot, 'src', 'components');
113
+ const schemaFile = path.join(schemaDir, `${slug}.ts`);
114
+ const pageFile = path.join(projectRoot, 'cms', 'editables', `${pageSlug}.ts`);
115
+ const componentFile = path.join(componentDir, `${componentName}.tsx`);
116
+ const pageExists = existsSync(pageFile);
117
+
118
+ for (const target of [schemaFile, componentFile]) {
119
+ if (existsSync(target)) {
120
+ console.error(
121
+ pc.red(
122
+ `\n❌ Error: File already exists: ${path.relative(projectRoot, target)}\n`,
123
+ ),
124
+ );
125
+ process.exit(1);
126
+ }
127
+ }
128
+
129
+ mkdirSync(schemaDir, { recursive: true });
130
+ mkdirSync(componentDir, { recursive: true });
131
+
132
+ const imports = Array.from(
133
+ new Set([
134
+ 'defineEditable',
135
+ 'getEditableDefaults',
136
+ ...fields.map((field) => field.type),
137
+ ]),
138
+ ).join(',\n ');
139
+ const fieldDefinitions = fields
140
+ .map(({ name, type }) => {
141
+ const defaultValue =
142
+ type === 'boolean'
143
+ ? 'false'
144
+ : type === 'number'
145
+ ? '0'
146
+ : type === 'image'
147
+ ? "''"
148
+ : type === 'repeater'
149
+ ? '[]'
150
+ : "'Edit me'";
151
+ return ` ${name}: ${type}({\n label: '${name.replace(/[_-]+/g, ' ')}',\n default: ${defaultValue},\n }),`;
152
+ })
153
+ .join('\n');
154
+
155
+ const pageFields = fields
156
+ .map(({ name }) => ` ${name}: '${slug}_${toSnakeCase(name)}',`)
157
+ .join('\n');
158
+ const renameFields = fields
159
+ .map(({ name }) => ` ${name}: '${toSnakeCase(name)}',`)
160
+ .join('\n');
161
+
162
+ const pageSchemaSource = `/**\n * ${pageSlug} — page editable contract composed from sections.\n */\nimport { buildPageEditable, getEditableDefaults } from '@forgewp/react';\nimport { editable as ${slug}Editable } from './sections/${slug}';\n\nexport const pageEditableSections = [\n {\n section: '${slug}',\n prefix: '${slug}_',\n rename: {\n${renameFields}\n },\n },\n];\n\nexport const editable = buildPageEditable([\n {\n schema: ${slug}Editable,\n prefix: '${slug}_',\n rename: {\n${renameFields}\n },\n },\n]);\n\nexport const defaults = getEditableDefaults(editable);\n`;
163
+
164
+ const schemaSource = `/**\n * ${componentName} — canonical section content contract.\n *\n * Compose this schema into cms/editables/${pageSlug}.ts for baked-page ACF\n * fields, then reuse it from the section component and generated block.\n */\nimport {\n ${imports},\n} from '@forgewp/react';\n\nexport const editable = defineEditable({\n${fieldDefinitions}\n});\n\nexport const defaults = getEditableDefaults(editable);\n`;
165
+
166
+ const fieldTypes = {
167
+ text: 'string',
168
+ richText: 'string',
169
+ image: 'string',
170
+ color: 'string',
171
+ url: 'string',
172
+ select: 'string',
173
+ icon: 'string',
174
+ boolean: 'boolean',
175
+ number: 'number',
176
+ repeater: 'unknown[]',
177
+ };
178
+ const props = fields
179
+ .map(({ name, type }) => ` ${name}?: ${fieldTypes[type]};`)
180
+ .join('\n');
181
+ const resolvedValues = fields
182
+ .map(
183
+ ({ name }) =>
184
+ ` const ${name}Meta = useWpMeta('${slug}_${toSnakeCase(name)}', defaults.${slug}_${toSnakeCase(name)});\n const ${name} = ${name}Prop ?? ${name}Meta;`,
185
+ )
186
+ .join('\n');
187
+ const renderedFields = fields
188
+ .map(({ name, type }) => {
189
+ if (type !== 'text' && type !== 'richText') {
190
+ return ` <div data-field='${name}'>{String(${name})}</div>`;
191
+ }
192
+ const tagName = type === 'richText' ? 'p' : 'h2';
193
+ return ` {setAttributes ? (\n <WpEditable\n tagName='${tagName}'\n value={${name}}\n onChange={(value) => setAttributes({ ${name}: value })}\n />\n ) : (\n <${tagName}>{${name}}</${tagName}>\n )}`;
194
+ })
195
+ .join('\n');
196
+ const propDestructuring = fields
197
+ .map(({ name }) => ` ${name}: ${name}Prop,`)
198
+ .join('\n');
199
+ const blockAnnotation = withBlock
200
+ ? `/**\n * @forgewp-block\n * title: ${componentName.replace(/([A-Z])/g, ' $1').trim()}\n * category: theme\n * description: Editable ${slug} section.\n */\n`
201
+ : '';
202
+
203
+ const componentSource = `import { pickEditable, useWpMeta, WpEditable } from '@forgewp/react';\nimport { editable as pageEditable, defaults } from '../../cms/editables/${pageSlug}';\n\nexport const editable = pickEditable(pageEditable, {\n${pageFields}\n});\n\nexport interface ${componentName}Props {\n${props}\n setAttributes?: (attributes: Partial<${componentName}Props>) => void;\n}\n\n${blockAnnotation}export function ${componentName}({\n${propDestructuring}\n setAttributes,\n}: ${componentName}Props) {\n${resolvedValues}\n\n return (\n <section>\n${renderedFields}\n </section>\n );\n}\n\nexport default ${componentName};\n`;
204
+
205
+ writeFileSync(schemaFile, schemaSource, 'utf8');
206
+ if (!existsSync(pageFile)) {
207
+ writeFileSync(pageFile, pageSchemaSource, 'utf8');
208
+ }
209
+ writeFileSync(componentFile, componentSource, 'utf8');
210
+
211
+ console.log(pc.green(`\n⚡ Section "${componentName}" created.`));
212
+ console.log(` Schema: ${pc.cyan(path.relative(projectRoot, schemaFile))}`);
213
+ console.log(` Page: ${pc.cyan(path.relative(projectRoot, pageFile))}`);
214
+ console.log(
215
+ ` Component: ${pc.cyan(path.relative(projectRoot, componentFile))}`,
216
+ );
217
+ console.log(
218
+ pageExists
219
+ ? '\nThe existing page contract was preserved; add this section to its composition if needed.'
220
+ : '\nThe page contract was created and composed with this section.',
221
+ );