@forgewp/compiler 0.1.8 → 0.2.0

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.
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
4
+ import path from "node:path";
5
+ import pc from "picocolors";
6
+
7
+ console.log(`\n⚡ ${pc.bold(pc.bgCyan(pc.black(" FORGEWP SITEMAP COMPILER (SYNC:ROUTES) ")))}\n`);
8
+
9
+ const projectRoot = process.cwd();
10
+ const args = process.argv.slice(2);
11
+ const isForce = args.includes("--force") || args.includes("--override");
12
+
13
+ // 1. Locate menus configuration file
14
+ let menusPath = path.join(projectRoot, "wordpress", "menus.json");
15
+ let menus = null;
16
+
17
+ if (!existsSync(menusPath)) {
18
+ // Try fallback in mock-data.json
19
+ const mockDataPath = path.join(projectRoot, "wordpress", "mock-data.json");
20
+ if (existsSync(mockDataPath)) {
21
+ try {
22
+ const mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
23
+ if (mockData.menu) {
24
+ menus = mockData.menu;
25
+ console.log(` ℹ️ Using legacy menus block inside: wordpress/mock-data.json`);
26
+ }
27
+ } catch (e) {
28
+ // Ignored
29
+ }
30
+ }
31
+ if (!menus) {
32
+ menus = {
33
+ _comment: "⚡ ForgeWP Navigation Menus — Edit this file to add/remove links in local dev. Run 'pnpm forgewp sync:routes' to auto-scaffold corresponding React pages!",
34
+ primary: [
35
+ { title: "Home", url: "/" },
36
+ { title: "New", url: "/new" },
37
+ { title: "Men", url: "/men" },
38
+ { title: "Women", url: "/women" }
39
+ ],
40
+ utility: [
41
+ { title: "Help", url: "/help" },
42
+ { title: "Sign In", url: "/login" }
43
+ ]
44
+ };
45
+
46
+ const dir = path.dirname(menusPath);
47
+ if (!existsSync(dir)) {
48
+ mkdirSync(dir, { recursive: true });
49
+ }
50
+ writeFileSync(menusPath, JSON.stringify(menus, null, 2), "utf8");
51
+ console.log(` 🎉 ${pc.green("Created dedicated sitemap source")}: wordpress/menus.json`);
52
+ }
53
+ } else {
54
+ try {
55
+ menus = JSON.parse(readFileSync(menusPath, "utf8"));
56
+ console.log(` 📖 ${pc.green("Loaded sitemap source")}: wordpress/menus.json`);
57
+ } catch (err) {
58
+ console.error(pc.red(`\n❌ Error: Failed to parse wordpress/menus.json.\nReason: ${err.message}`));
59
+ process.exit(1);
60
+ }
61
+ }
62
+
63
+ // 2. Extract unique local paths and sanitize them
64
+ const routesToScaffold = [];
65
+ const seenUrls = new Set(["/", ""]);
66
+
67
+ for (const [location, items] of Object.entries(menus)) {
68
+ if (!Array.isArray(items)) continue;
69
+ for (const item of items) {
70
+ if (!item.url || typeof item.url !== "string") continue;
71
+ let url = item.url.trim();
72
+
73
+ // Skip external, anchors, mailto, etc.
74
+ if (
75
+ url.startsWith("http://") ||
76
+ url.startsWith("https://") ||
77
+ url.startsWith("#") ||
78
+ url.startsWith("mailto:") ||
79
+ url.startsWith("tel:")
80
+ ) {
81
+ continue;
82
+ }
83
+
84
+ // Normalize starting slash
85
+ if (!url.startsWith("/")) {
86
+ url = "/" + url;
87
+ }
88
+
89
+ if (seenUrls.has(url)) continue;
90
+ seenUrls.add(url);
91
+
92
+ routesToScaffold.push({
93
+ path: url,
94
+ title: item.title || url.replace("/", "")
95
+ });
96
+ }
97
+ }
98
+
99
+ if (routesToScaffold.length === 0) {
100
+ console.log(pc.yellow(`\nℹ️ No local pages to synchronize inside your sitemap menu config.`));
101
+ process.exit(0);
102
+ }
103
+
104
+ // Helper to convert path / slug to PascalCase ComponentName
105
+ function toPascalCase(str) {
106
+ return str
107
+ .replace(/[^a-zA-Z0-9]/g, " ")
108
+ .trim()
109
+ .split(/\s+/)
110
+ .map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
111
+ .join("") + "Page";
112
+ }
113
+
114
+ // 3. Ensure Pages output directory exists
115
+ const pagesDir = path.join(projectRoot, "src", "app", "pages");
116
+ if (!existsSync(pagesDir)) {
117
+ mkdirSync(pagesDir, { recursive: true });
118
+ }
119
+
120
+ // 4. Scaffold components non-destructively
121
+ let scaffoldedCount = 0;
122
+ let skippedCount = 0;
123
+
124
+ for (const route of routesToScaffold) {
125
+ const componentName = toPascalCase(route.title);
126
+ const componentPath = path.join(pagesDir, `${componentName}.tsx`);
127
+
128
+ const componentContent = `/**
129
+ * ⚡ Auto-Generated Page Component by ForgeWP
130
+ *
131
+ * This file was generated automatically from your sitemap configuration (wordpress/menus.json).
132
+ * You can safely edit this file to customize the visual layout, styles, and logic.
133
+ * Subsequent runs of 'pnpm forgewp sync:routes' will NOT overwrite your changes.
134
+ *
135
+ * To force reset this page back to boilerplate defaults, run:
136
+ * 'pnpm forgewp sync:routes --force'
137
+ */
138
+ import { SEO } from "../../.forgewp/SEO";
139
+ import { WpQueryLoop, useWpTitle, useWpExcerpt, useWpFeaturedImage } from "../../.forgewp/wordpress";
140
+
141
+ export function ${componentName}() {
142
+ return (
143
+ <main className="container mx-auto px-6 py-12">
144
+ {/* Dynamic SEO Injector */}
145
+ <SEO
146
+ title="${route.title}"
147
+ description="Explore our exclusive ${route.title} section, dynamically loaded in Headless React."
148
+ />
149
+
150
+ {/* Hero Header Area */}
151
+ <header className="border-b-4 border-black pb-6 mb-12">
152
+ <h1 className="text-5xl font-black tracking-tight uppercase">${route.title}</h1>
153
+ <p className="text-zinc-500 mt-2 text-lg">
154
+ Auto-generated template. Edit <code className="bg-zinc-100 px-1 py-0.5 rounded text-sm text-red-600 font-mono">src/app/pages/${componentName}.tsx</code> to customize this page.
155
+ </p>
156
+ </header>
157
+
158
+ {/* Grid Starter - WordPress Mock Loop */}
159
+ <section className="grid grid-cols-1 md:grid-cols-3 gap-8">
160
+ <WpQueryLoop postType="post" postsPerPage={3}>
161
+ <article className="border-2 border-black p-6 bg-white shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] hover:translate-y-[-2px] hover:shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] transition-all">
162
+ <div className="w-full h-48 bg-zinc-100 mb-4 border border-zinc-200 overflow-hidden">
163
+ <img
164
+ src={useWpFeaturedImage()}
165
+ alt={useWpTitle()}
166
+ className="w-full h-full object-cover"
167
+ />
168
+ </div>
169
+ <h2 className="text-xl font-bold uppercase tracking-tight mb-2">
170
+ {useWpTitle()}
171
+ </h2>
172
+ <p className="text-zinc-600 text-sm mb-4">
173
+ {useWpExcerpt()}
174
+ </p>
175
+ <a
176
+ href="#"
177
+ className="inline-block px-4 py-2 border-2 border-black bg-zinc-100 font-bold uppercase text-xs hover:bg-black hover:text-white transition-colors"
178
+ >
179
+ Read More
180
+ </a>
181
+ </article>
182
+ </WpQueryLoop>
183
+ </section>
184
+ </main>
185
+ );
186
+ }
187
+ `;
188
+
189
+ if (existsSync(componentPath) && !isForce) {
190
+ console.log(` ${pc.gray("ℹ️ [Skip] Component already exists:")} src/app/pages/${componentName}.tsx`);
191
+ skippedCount++;
192
+ } else {
193
+ writeFileSync(componentPath, componentContent, "utf8");
194
+ console.log(` ${pc.green("✅ Scaffolded component")}: src/app/pages/${componentName}.tsx`);
195
+ scaffoldedCount++;
196
+ }
197
+ }
198
+
199
+ // 5. Inject pages into src/app/routes.tsx
200
+ const routesFilePath = path.join(projectRoot, "src/app/routes.tsx");
201
+ if (existsSync(routesFilePath)) {
202
+ let routesContent = readFileSync(routesFilePath, "utf8");
203
+ let modified = false;
204
+
205
+ for (const route of routesToScaffold) {
206
+ const componentName = toPascalCase(route.title);
207
+
208
+ // Check if the component is imported
209
+ const importRegex = new RegExp(`import\\s+\\{\\s*${componentName}\\s*\\}\\s+from\\s+["']\\./pages/${componentName}["']`);
210
+ if (!importRegex.test(routesContent)) {
211
+ // Find a clean place to inject imports
212
+ // Right above "export default function" or under other imports
213
+ const defaultExportIndex = routesContent.indexOf("export default function");
214
+ if (defaultExportIndex !== -1) {
215
+ routesContent =
216
+ routesContent.slice(0, defaultExportIndex) +
217
+ `import { ${componentName} } from "./pages/${componentName}";\n` +
218
+ routesContent.slice(defaultExportIndex);
219
+ modified = true;
220
+ }
221
+ }
222
+
223
+ // Check if the Route path is registered
224
+ const routeRegex = new RegExp(`path\\s*=\\s*["']${route.path}["']`);
225
+ if (!routeRegex.test(routesContent)) {
226
+ // Find the fallback route or closing Switch tag to inject
227
+ const fallbackMarker = "{/* Fallback route */}";
228
+ const fallbackIndex = routesContent.indexOf(fallbackMarker);
229
+ if (fallbackIndex !== -1) {
230
+ routesContent =
231
+ routesContent.slice(0, fallbackIndex) +
232
+ `<Route path="${route.path}" component={${componentName}} />\n\n ` +
233
+ routesContent.slice(fallbackIndex);
234
+ modified = true;
235
+ } else {
236
+ // Fallback to closing Switch tag
237
+ const switchCloseIndex = routesContent.indexOf("</Switch>");
238
+ if (switchCloseIndex !== -1) {
239
+ routesContent =
240
+ routesContent.slice(0, switchCloseIndex) +
241
+ ` <Route path="${route.path}" component={${componentName}} />\n ` +
242
+ routesContent.slice(switchCloseIndex);
243
+ modified = true;
244
+ }
245
+ }
246
+ }
247
+ }
248
+
249
+ if (modified) {
250
+ writeFileSync(routesFilePath, routesContent, "utf8");
251
+ console.log(` ${pc.green("✅ Synced routing paths in")}: src/app/routes.tsx`);
252
+ } else {
253
+ console.log(` ${pc.gray("ℹ️ Routes are already fully up to date in")}: src/app/routes.tsx`);
254
+ }
255
+ } else {
256
+ console.log(pc.yellow(` ⚠️ Warning: routes.tsx not found. Skipped route linking.`));
257
+ }
258
+
259
+ console.log("\n" + "─".repeat(60));
260
+ console.log(pc.green(`\n🎉 ${pc.bold("SITEMAP SYNC COMPLETE:")} Generated ${scaffoldedCount} new pages (skipped ${skippedCount}).\n`));
@@ -14,10 +14,10 @@ export async function addComponent(component, options) {
14
14
  try {
15
15
  const { createRequire } = await import("node:module");
16
16
  const require = createRequire(import.meta.url);
17
- registryPath = path.join(path.dirname(require.resolve("@forgewp/registry/package.json")), "components");
17
+ registryPath = path.join(path.dirname(require.resolve("@forgewp/ui/package.json")), "components");
18
18
  } catch (e) {
19
19
  // Fallback for development/local execution
20
- registryPath = path.resolve(path.dirname(new URL(import.meta.url).pathname), "../../registry/components");
20
+ registryPath = path.resolve(path.dirname(new URL(import.meta.url).pathname), "../../ui/components");
21
21
  }
22
22
 
23
23
  let localComponentFile = path.join(registryPath, component, `${style}.tsx`);
@@ -41,8 +41,20 @@ export async function addComponent(component, options) {
41
41
  // 2. Run shadcn add (fallback)
42
42
  console.log(pc.dim(` Fetching ${component} from shadcn/ui...`));
43
43
  try {
44
+ // Auto-detect the package manager being used by the developer
45
+ const userAgent = process.env.npm_config_user_agent || "";
46
+ let shadcnCmd = "npx shadcn@latest"; // Default fallback
47
+
48
+ if (userAgent.includes("pnpm")) {
49
+ shadcnCmd = "pnpm dlx shadcn@latest";
50
+ } else if (userAgent.includes("bun")) {
51
+ shadcnCmd = "bunx --bun shadcn@latest";
52
+ } else if (userAgent.includes("yarn")) {
53
+ shadcnCmd = "yarn dlx shadcn@latest";
54
+ }
55
+
44
56
  // We use --yes to skip prompts
45
- execSync(`npx shadcn@latest add ${component} --yes`, {
57
+ execSync(`${shadcnCmd} add ${component} --yes`, {
46
58
  stdio: "inherit",
47
59
  cwd: projectRoot,
48
60
  shell: process.platform === "win32",