@forgewp/compiler 0.4.1 → 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.
package/bin/cli.js CHANGED
@@ -15,6 +15,7 @@ const subcommands = {
15
15
  "make:component": path.join(__dirname, "make-template.js"), // Backward compatible alias mapping
16
16
  "make:island": path.join(__dirname, "make-island.js"),
17
17
  "sync:routes": path.join(__dirname, "sync-routes.js"),
18
+ "sync:hooks": path.join(__dirname, "sync-hooks.js"),
18
19
  "i18n:extract": path.join(__dirname, "i18n-extract.js"),
19
20
  "i18n:translate": path.join(__dirname, "i18n-translate.js"),
20
21
  export: path.join(__dirname, "export.js"),
@@ -49,6 +50,8 @@ if (!targetScript) {
49
50
  targetScript = subcommands["make:island"];
50
51
  } else if (command === "sync-routes" || command === "sync" || command === "sync:routes") {
51
52
  targetScript = subcommands["sync:routes"];
53
+ } else if (command === "sync-hooks" || command === "sync:hooks") {
54
+ targetScript = subcommands["sync:hooks"];
52
55
  } else if (command === "i18n-extract" || command === "i18n:extract") {
53
56
  targetScript = subcommands["i18n:extract"];
54
57
  } else if (command === "i18n-translate" || command === "i18n:translate") {
@@ -96,6 +99,7 @@ function printHelp() {
96
99
  ${pc.cyan("make:template <Name>")} Scaffold a custom post-type loop template
97
100
  ${pc.cyan("make:island <Name>")} Scaffold an interactive selective hydration island
98
101
  ${pc.cyan("sync:routes")} Synchronize sitemap menus with routes and scaffold pages
102
+ ${pc.cyan("sync:hooks")} Propagate wordpress.tsx hooks to all workspace projects
99
103
  ${pc.cyan("i18n:extract")} Extract translation strings to translations.json
100
104
  ${pc.cyan("i18n:translate")} Translate missing strings via the configured engine
101
105
  ${pc.cyan("export")} Package your theme into an installable WP zip
@@ -0,0 +1,221 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * forgewp sync-hooks
4
+ *
5
+ * Propagates the canonical src/.forgewp/wordpress.tsx template to every
6
+ * ForgeWP project in the workspace that contains a src/.forgewp/ directory.
7
+ *
8
+ * Usage:
9
+ * pnpm forgewp sync-hooks # sync all projects
10
+ * pnpm forgewp sync-hooks --dry-run # preview without writing
11
+ * pnpm forgewp sync-hooks --verbose # show skipped projects too
12
+ */
13
+
14
+ import {
15
+ existsSync,
16
+ readFileSync,
17
+ writeFileSync,
18
+ readdirSync,
19
+ statSync,
20
+ } from "node:fs";
21
+ import { createHash } from "node:crypto";
22
+ import path from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ import pc from "picocolors";
25
+
26
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
27
+
28
+ // ── CLI flags ──────────────────────────────────────────────────────────────────
29
+ const argv = process.argv.slice(2);
30
+ const isDryRun = argv.includes("--dry-run") || argv.includes("-n");
31
+ const isVerbose = argv.includes("--verbose") || argv.includes("-v");
32
+
33
+ // ── Banner ─────────────────────────────────────────────────────────────────────
34
+ console.log(
35
+ `\n🔄 ${pc.bold(pc.bgCyan(pc.black(" FORGEWP SYNC-HOOKS ")))} ${
36
+ isDryRun ? pc.yellow("[DRY RUN — no files will be written]") : ""
37
+ }\n`
38
+ );
39
+
40
+ // ── Locate the canonical template (source of truth) ───────────────────────────
41
+ const canonicalTemplatePath = path.resolve(
42
+ __dirname,
43
+ "..",
44
+ "templates",
45
+ "wordpress.tsx"
46
+ );
47
+
48
+ if (!existsSync(canonicalTemplatePath)) {
49
+ console.error(
50
+ pc.red(
51
+ `\n❌ Cannot find canonical template at:\n ${canonicalTemplatePath}\n`
52
+ )
53
+ );
54
+ process.exit(1);
55
+ }
56
+
57
+ const canonicalContent = readFileSync(canonicalTemplatePath, "utf8");
58
+ const canonicalHash = md5(canonicalContent);
59
+
60
+ console.log(
61
+ ` ${pc.bold("Source:")} ${pc.cyan("packages/compiler/templates/wordpress.tsx")}`
62
+ );
63
+ console.log(` ${pc.bold("Hash:")} ${pc.dim(canonicalHash.slice(0, 12))}...\n`);
64
+
65
+ // ── Find workspace root (directory containing pnpm-workspace.yaml) ─────────────
66
+ function findWorkspaceRoot(startDir) {
67
+ let dir = startDir;
68
+ for (let i = 0; i < 10; i++) {
69
+ if (existsSync(path.join(dir, "pnpm-workspace.yaml"))) return dir;
70
+ const parent = path.dirname(dir);
71
+ if (parent === dir) break;
72
+ dir = parent;
73
+ }
74
+ return null;
75
+ }
76
+
77
+ const projectRoot = process.cwd();
78
+ const workspaceRoot = findWorkspaceRoot(projectRoot) || projectRoot;
79
+
80
+ console.log(` ${pc.bold("Workspace:")} ${pc.dim(workspaceRoot)}\n`);
81
+
82
+ // ── Collect candidate project directories ─────────────────────────────────────
83
+ function collectProjectDirs(workspaceRoot) {
84
+ const dirs = new Set();
85
+
86
+ // 1. Parse pnpm-workspace.yaml for declared packages
87
+ const workspaceYaml = path.join(workspaceRoot, "pnpm-workspace.yaml");
88
+ if (existsSync(workspaceYaml)) {
89
+ const raw = readFileSync(workspaceYaml, "utf8");
90
+ // Simple line-by-line parse — handles " - "pattern-or-glob" entries
91
+ const lines = raw.split(/\r?\n/);
92
+ for (const line of lines) {
93
+ const match = line.match(/^\s+-\s+"?([^"#\s]+)"?\s*$/);
94
+ if (!match) continue;
95
+ const pattern = match[1].trim();
96
+ if (pattern.startsWith("!")) continue; // exclusion — handled below
97
+
98
+ if (pattern.endsWith("/*")) {
99
+ // Glob: enumerate immediate children
100
+ const base = path.join(workspaceRoot, pattern.slice(0, -2));
101
+ if (existsSync(base)) {
102
+ for (const entry of readdirSync(base)) {
103
+ const full = path.join(base, entry);
104
+ if (statSync(full).isDirectory()) dirs.add(full);
105
+ }
106
+ }
107
+ } else {
108
+ // Literal path
109
+ const full = path.join(workspaceRoot, pattern);
110
+ if (existsSync(full)) dirs.add(full);
111
+ }
112
+ }
113
+ }
114
+
115
+ // 2. Always include template scaffold directories (excluded from workspace installs
116
+ // but still need to be kept in sync as they seed new projects)
117
+ const extraTemplates = [
118
+ path.join(workspaceRoot, "packages", "create-forgewp", "template"),
119
+ path.join(workspaceRoot, "packages", "create-forgewp", "template-html"),
120
+ ];
121
+ for (const t of extraTemplates) {
122
+ if (existsSync(t)) dirs.add(t);
123
+ }
124
+
125
+ return [...dirs];
126
+ }
127
+
128
+ const candidateDirs = collectProjectDirs(workspaceRoot);
129
+
130
+ // ── Sync logic ─────────────────────────────────────────────────────────────────
131
+ const TARGET_RELATIVE = path.join("src", ".forgewp", "wordpress.tsx");
132
+
133
+ let updatedCount = 0;
134
+ let alreadyCurrentCount = 0;
135
+ let skippedCount = 0;
136
+
137
+ for (const dir of candidateDirs) {
138
+ const targetPath = path.join(dir, TARGET_RELATIVE);
139
+ const relativeDir = path.relative(workspaceRoot, dir);
140
+
141
+ // Skip if this dir doesn't have a src/.forgewp/ at all — it's not a ForgeWP theme
142
+ if (!existsSync(path.dirname(targetPath))) {
143
+ if (isVerbose) {
144
+ console.log(
145
+ ` ${pc.dim("⊘ Skipped")} ${pc.dim(relativeDir)} ${pc.dim("(no src/.forgewp/)")}`
146
+ );
147
+ }
148
+ skippedCount++;
149
+ continue;
150
+ }
151
+
152
+ // Skip the compiler's own templates directory to avoid self-overwrite
153
+ if (dir === path.resolve(__dirname, "..")) {
154
+ if (isVerbose) {
155
+ console.log(` ${pc.dim("⊘ Skipped")} ${pc.dim(relativeDir)} ${pc.dim("(source package)")}`);
156
+ }
157
+ skippedCount++;
158
+ continue;
159
+ }
160
+
161
+ if (existsSync(targetPath)) {
162
+ const existingContent = readFileSync(targetPath, "utf8");
163
+ const existingHash = md5(existingContent);
164
+
165
+ if (existingHash === canonicalHash) {
166
+ if (isVerbose) {
167
+ console.log(
168
+ ` ${pc.green("✓ Up-to-date")} ${pc.cyan(relativeDir)}`
169
+ );
170
+ }
171
+ alreadyCurrentCount++;
172
+ continue;
173
+ }
174
+ }
175
+
176
+ // Write update
177
+ if (!isDryRun) {
178
+ writeFileSync(targetPath, canonicalContent, "utf8");
179
+ }
180
+
181
+ console.log(
182
+ ` ${isDryRun ? pc.yellow("~ Would update") : pc.green("✅ Updated")} ${pc.cyan(relativeDir + "/" + TARGET_RELATIVE.replace(/\\/g, "/"))}`
183
+ );
184
+ updatedCount++;
185
+ }
186
+
187
+ // ── Summary ────────────────────────────────────────────────────────────────────
188
+ console.log("\n" + "─".repeat(60));
189
+
190
+ if (updatedCount === 0 && alreadyCurrentCount > 0) {
191
+ console.log(
192
+ pc.green(
193
+ `\n✨ ${pc.bold("All projects are already up-to-date.")} (${alreadyCurrentCount} checked)\n`
194
+ )
195
+ );
196
+ } else if (isDryRun) {
197
+ console.log(
198
+ pc.yellow(
199
+ `\n🔍 ${pc.bold("Dry run complete.")} ${updatedCount} file(s) would be updated, ${alreadyCurrentCount} already current.\n`
200
+ )
201
+ );
202
+ } else {
203
+ const total = updatedCount + alreadyCurrentCount + skippedCount;
204
+ console.log(
205
+ pc.green(
206
+ `\n🎉 ${pc.bold("Sync complete!")} Updated ${pc.bold(String(updatedCount))} project(s). ${alreadyCurrentCount} already current. ${skippedCount} non-theme packages skipped.\n`
207
+ )
208
+ );
209
+ if (updatedCount > 0) {
210
+ console.log(
211
+ pc.cyan(
212
+ ` All projects now share the same wordpress.tsx hooks — zero drift.\n`
213
+ )
214
+ );
215
+ }
216
+ }
217
+
218
+ // ── Helpers ───────────────────────────────────────────────────────────────────
219
+ function md5(content) {
220
+ return createHash("md5").update(content).digest("hex");
221
+ }