@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,375 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * forgewp make:shell
5
+ *
6
+ * Scaffold a parent shell block (InnerBlocks layout wrapper).
7
+ * Interactively lists project blocks so you can pick default children.
8
+ *
9
+ * Usage:
10
+ * pnpm forgewp make:shell AboutSplitSection
11
+ * pnpm forgewp make:shell AboutSplitSection --children=about-mission,about-values --layout=2-col
12
+ */
13
+
14
+ import { existsSync } from "node:fs";
15
+ import path from "node:path";
16
+ import readline from "node:readline/promises";
17
+ import { stdin as input, stdout as output } from "node:process";
18
+ import pc from "picocolors";
19
+ import { loadConfig } from "../lib/load-config.js";
20
+ import { loadFrameworkAdapter } from "../lib/framework-adapter.js";
21
+ import {
22
+ discoverProjectBlocks,
23
+ SHELL_LAYOUT_PRESETS,
24
+ DEFAULT_SHELL_CLASSNAME,
25
+ } from "../lib/blocks/discover-blocks.js";
26
+ import { blockAuthoringHelp } from "../lib/block-authoring-help.js";
27
+
28
+ const args = process.argv.slice(2);
29
+
30
+ function getFlag(name) {
31
+ const eq = args.find((a) => a.startsWith(`--${name}=`));
32
+ if (eq) return eq.slice(name.length + 3);
33
+ const idx = args.indexOf(`--${name}`);
34
+ if (idx !== -1 && args[idx + 1] && !args[idx + 1].startsWith("-")) {
35
+ return args[idx + 1];
36
+ }
37
+ return undefined;
38
+ }
39
+
40
+ function hasFlag(name) {
41
+ return args.includes(`--${name}`) || args.some((a) => a.startsWith(`--${name}=`));
42
+ }
43
+
44
+ function printHelp() {
45
+ console.log(`
46
+ ${pc.bold("forgewp make:shell")} — scaffold a parent shell (InnerBlocks layout)
47
+
48
+ ${pc.bold("Usage:")}
49
+ pnpm forgewp make:shell <Name>
50
+ pnpm forgewp make:shell <Name> --children=block-a,block-b --layout=2-col
51
+
52
+ ${pc.bold("Options:")}
53
+ --name <Name> Shell block name (PascalCase or kebab)
54
+ --children <slugs> Comma-separated child block names (no forgewp/ prefix)
55
+ --layout <preset> ${Object.keys(SHELL_LAYOUT_PRESETS).join(" | ")} | custom
56
+ --grid-class <classes> Override grid className (implies custom layout)
57
+ --class <classes> Outer shell className (default: max-w-7xl + padding)
58
+ --template-lock <mode> false | insert | all | true (default: false)
59
+ --category <slug> Block category (default: theme)
60
+ --icon <dashicon> Dashicon slug (default: columns)
61
+ --description <text> Block description
62
+ --yes Skip interactive prompts when flags provide enough info
63
+ -h, --help Show help
64
+
65
+ ${pc.bold("Examples:")}
66
+ pnpm forgewp make:shell AboutSplitSection
67
+ pnpm forgewp make:shell AboutSplitSection --children=about-mission,about-values --layout=2-col
68
+ pnpm forgewp make:shell FeatureRow --layout=3-col --template-lock=insert
69
+ ${blockAuthoringHelp}
70
+ `);
71
+ }
72
+
73
+ if (hasFlag("help") || args.includes("-h")) {
74
+ printHelp();
75
+ process.exit(0);
76
+ }
77
+
78
+ let rawShellName =
79
+ args.find((a) => !a.startsWith("-")) || getFlag("name") || "";
80
+
81
+ const projectRoot = process.cwd();
82
+ if (!existsSync(path.join(projectRoot, "src"))) {
83
+ console.error(
84
+ pc.red(
85
+ `\n❌ Error: "src" folder not found. Are you in your theme's root directory?\n`,
86
+ ),
87
+ );
88
+ process.exit(1);
89
+ }
90
+
91
+ const available = discoverProjectBlocks(projectRoot, { includeShells: false });
92
+
93
+ const rl = readline.createInterface({ input, output });
94
+
95
+ async function ask(prompt, fallback = "") {
96
+ const suffix = fallback !== "" ? pc.dim(` (${fallback})`) : "";
97
+ try {
98
+ const answer = await rl.question(pc.cyan(`? ${prompt}${suffix}: `));
99
+ const t = answer.trim();
100
+ return t || fallback;
101
+ } catch {
102
+ return fallback;
103
+ }
104
+ }
105
+
106
+ try {
107
+ if (!rawShellName) {
108
+ rawShellName = await ask("Shell block name (e.g. AboutSplitSection)");
109
+ }
110
+
111
+ if (!rawShellName) {
112
+ console.error(pc.red("\n❌ Error: Please specify a shell name."));
113
+ console.log(
114
+ pc.cyan(" Example: pnpm forgewp make:shell AboutSplitSection\n"),
115
+ );
116
+ process.exit(1);
117
+ }
118
+
119
+ const cleanName = rawShellName.replace(/[^a-zA-Z0-9_-]/g, "");
120
+ if (!cleanName) {
121
+ console.error(pc.red("\n❌ Error: Invalid shell name.\n"));
122
+ process.exit(1);
123
+ }
124
+
125
+ const pascalCase = cleanName
126
+ .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => word.toUpperCase())
127
+ .replace(/[^a-zA-Z0-9]/g, "");
128
+
129
+ const nameSlug = pascalCase
130
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
131
+ .toLowerCase()
132
+ .replace(/[^a-z0-9]+/g, "-");
133
+
134
+ const readableTitle = pascalCase
135
+ .replace(/([A-Z])/g, " $1")
136
+ .trim();
137
+
138
+ // ── Children ────────────────────────────────────────────────────────────
139
+ let childrenSlugs = [];
140
+ const childrenFlag = getFlag("children");
141
+ if (childrenFlag !== undefined) {
142
+ childrenSlugs = childrenFlag
143
+ .split(",")
144
+ .map((s) => s.trim().replace(/^forgewp\//, ""))
145
+ .filter(Boolean);
146
+ } else if (!hasFlag("yes")) {
147
+ console.log("");
148
+ if (available.length === 0) {
149
+ console.log(
150
+ pc.yellow(
151
+ " No leaf blocks found yet. Scaffold with make:block / @forgewp-block first,",
152
+ ),
153
+ );
154
+ console.log(
155
+ pc.yellow(
156
+ " or continue with an empty shell (children can be added later).\n",
157
+ ),
158
+ );
159
+ } else {
160
+ console.log(pc.bold(" Available blocks (children candidates):\n"));
161
+ available.forEach((b, i) => {
162
+ console.log(
163
+ ` ${pc.cyan(String(i + 1).padStart(2))}. ${pc.bold(b.name)} ${pc.dim(`— ${b.title}`)} ${pc.dim(`(${b.file})`)}`,
164
+ );
165
+ });
166
+ console.log(
167
+ pc.dim(
168
+ "\n Enter numbers or names, comma-separated. Leave empty for none.\n",
169
+ ),
170
+ );
171
+ const pick = await ask(
172
+ "Child blocks",
173
+ "",
174
+ );
175
+ if (pick) {
176
+ childrenSlugs = resolveChildPicks(pick, available);
177
+ }
178
+ }
179
+ }
180
+
181
+ // Validate children against discovered set (warn only — allows pre-declared slugs)
182
+ const known = new Set(available.map((b) => b.name));
183
+ for (const c of childrenSlugs) {
184
+ if (!known.has(c)) {
185
+ console.log(
186
+ pc.yellow(
187
+ ` ⚠️ "${c}" is not a discovered leaf block — included anyway (ensure it exists at export).`,
188
+ ),
189
+ );
190
+ }
191
+ }
192
+
193
+ // ── Layout ──────────────────────────────────────────────────────────────
194
+ let layoutKey = getFlag("layout") || "";
195
+ let gridClassName = getFlag("grid-class") || getFlag("gridClassName") || "";
196
+ let orientation = "horizontal";
197
+
198
+ if (gridClassName) {
199
+ layoutKey = "custom";
200
+ } else if (!layoutKey && !hasFlag("yes")) {
201
+ console.log(pc.bold("\n Layout presets:\n"));
202
+ const keys = Object.keys(SHELL_LAYOUT_PRESETS);
203
+ keys.forEach((k, i) => {
204
+ console.log(
205
+ ` ${pc.cyan(String(i + 1))}. ${k} — ${SHELL_LAYOUT_PRESETS[k].label}`,
206
+ );
207
+ });
208
+ console.log(` ${pc.cyan(String(keys.length + 1))}. custom — type your own grid classes`);
209
+ const choice = await ask("Layout", "2-col");
210
+ if (/^\d+$/.test(choice)) {
211
+ const n = Number(choice);
212
+ if (n >= 1 && n <= keys.length) layoutKey = keys[n - 1];
213
+ else if (n === keys.length + 1) layoutKey = "custom";
214
+ else layoutKey = "2-col";
215
+ } else {
216
+ layoutKey = choice in SHELL_LAYOUT_PRESETS || choice === "custom"
217
+ ? choice
218
+ : "2-col";
219
+ }
220
+ } else if (!layoutKey) {
221
+ layoutKey = "2-col";
222
+ }
223
+
224
+ if (layoutKey === "custom" && !gridClassName) {
225
+ gridClassName = await ask(
226
+ "Grid className",
227
+ "grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",
228
+ );
229
+ orientation = "horizontal";
230
+ } else if (layoutKey !== "custom") {
231
+ const preset =
232
+ SHELL_LAYOUT_PRESETS[layoutKey] || SHELL_LAYOUT_PRESETS["2-col"];
233
+ gridClassName = preset.gridClassName;
234
+ orientation = preset.orientation || "horizontal";
235
+ }
236
+
237
+ // ── Outer chrome ────────────────────────────────────────────────────────
238
+ let className = getFlag("class") || getFlag("className") || "";
239
+ if (!className && !hasFlag("yes")) {
240
+ className = await ask("Outer shell className", DEFAULT_SHELL_CLASSNAME);
241
+ } else if (!className) {
242
+ className = DEFAULT_SHELL_CLASSNAME;
243
+ }
244
+
245
+ // ── Template lock ───────────────────────────────────────────────────────
246
+ let templateLockRaw =
247
+ getFlag("template-lock") || getFlag("templateLock") || "";
248
+ if (!templateLockRaw && !hasFlag("yes")) {
249
+ templateLockRaw = await ask(
250
+ "templateLock (false | insert | all | true)",
251
+ "false",
252
+ );
253
+ } else if (!templateLockRaw) {
254
+ templateLockRaw = "false";
255
+ }
256
+ const templateLock = parseTemplateLock(templateLockRaw);
257
+
258
+ // ── Meta ────────────────────────────────────────────────────────────────
259
+ let category = getFlag("category") || "";
260
+ if (!category && !hasFlag("yes")) {
261
+ category = await ask("Category", "theme");
262
+ } else if (!category) {
263
+ category = "theme";
264
+ }
265
+
266
+ let icon = getFlag("icon") || "";
267
+ if (!icon && !hasFlag("yes")) {
268
+ icon = await ask("Dashicon", "columns");
269
+ } else if (!icon) {
270
+ icon = "columns";
271
+ }
272
+
273
+ let description =
274
+ getFlag("description") ||
275
+ `Layout shell: ${readableTitle}${childrenSlugs.length ? ` (${childrenSlugs.join(" + ")})` : ""}`;
276
+
277
+ if (!hasFlag("yes") && !getFlag("description")) {
278
+ description = await ask("Description", description);
279
+ }
280
+
281
+ rl.close();
282
+
283
+ // Load adapter
284
+ let frameworkAdapter = "react";
285
+ try {
286
+ const config = await loadConfig(projectRoot);
287
+ frameworkAdapter = config.frameworkAdapter || "react";
288
+ } catch {
289
+ // default
290
+ }
291
+
292
+ const adapterModule = await loadFrameworkAdapter(frameworkAdapter);
293
+ const adapter = adapterModule.default || adapterModule;
294
+
295
+ if (typeof adapter.onMakeShell !== "function") {
296
+ console.error(
297
+ pc.red(
298
+ `\n❌ Error: Framework adapter "${frameworkAdapter}" does not support make:shell.\n`,
299
+ ),
300
+ );
301
+ process.exit(1);
302
+ }
303
+
304
+ await adapter.onMakeShell(projectRoot, {
305
+ pascalCase,
306
+ nameSlug,
307
+ readableTitle,
308
+ childrenSlugs,
309
+ shell: {
310
+ className,
311
+ gridClassName,
312
+ },
313
+ innerBlocks: {
314
+ allowedBlocks: childrenSlugs.length > 0 ? childrenSlugs : undefined,
315
+ template: childrenSlugs.map((slug) => [slug]),
316
+ templateLock,
317
+ orientation,
318
+ },
319
+ category,
320
+ icon,
321
+ description,
322
+ pc,
323
+ });
324
+ } catch (err) {
325
+ try {
326
+ rl.close();
327
+ } catch {
328
+ // ignore
329
+ }
330
+ console.error(
331
+ pc.red(
332
+ `\n❌ Failed to execute make:shell: ${err instanceof Error ? err.message : err}\n`,
333
+ ),
334
+ );
335
+ process.exit(1);
336
+ }
337
+
338
+ /**
339
+ * @param {string} pick
340
+ * @param {import('../lib/blocks/discover-blocks.js').DiscoveredBlock[]} available
341
+ */
342
+ function resolveChildPicks(pick, available) {
343
+ const parts = pick.split(/[,\s]+/).map((p) => p.trim()).filter(Boolean);
344
+ const out = [];
345
+ const seen = new Set();
346
+ for (const p of parts) {
347
+ if (/^\d+$/.test(p)) {
348
+ const idx = Number(p) - 1;
349
+ if (idx >= 0 && idx < available.length) {
350
+ const name = available[idx].name;
351
+ if (!seen.has(name)) {
352
+ seen.add(name);
353
+ out.push(name);
354
+ }
355
+ } else {
356
+ console.log(pc.yellow(` ⚠️ Ignoring out-of-range index: ${p}`));
357
+ }
358
+ continue;
359
+ }
360
+ const slug = p.replace(/^forgewp\//, "");
361
+ if (!seen.has(slug)) {
362
+ seen.add(slug);
363
+ out.push(slug);
364
+ }
365
+ }
366
+ return out;
367
+ }
368
+
369
+ function parseTemplateLock(raw) {
370
+ const v = String(raw).trim().toLowerCase();
371
+ if (v === "false" || v === "0" || v === "no" || v === "none") return false;
372
+ if (v === "true" || v === "1" || v === "yes") return true;
373
+ if (v === "all" || v === "insert") return v;
374
+ return false;
375
+ }
package/bin/repair.js CHANGED
@@ -15,6 +15,13 @@ try {
15
15
  for (const [relativePath, blueprintContent] of Object.entries(SYSTEM_BLUEPRINTS)) {
16
16
  const fullPath = path.join(projectRoot, relativePath);
17
17
 
18
+ if (relativePath.startsWith("cms/") && relativePath.endsWith(".json")) {
19
+ const tsVariant = fullPath.replace(/\.json$/, ".ts");
20
+ if (existsSync(tsVariant)) {
21
+ continue; // Typed .ts file exists, do not overwrite with .json blueprint
22
+ }
23
+ }
24
+
18
25
  // Ensure the folder exists
19
26
  const dirPath = path.dirname(fullPath);
20
27
  if (!existsSync(dirPath)) {
@@ -28,35 +35,16 @@ try {
28
35
  }
29
36
 
30
37
  // Ensure default mock data table is recreated if deleted
31
- const mockDataPath = path.join(projectRoot, "cms", "mock-data.json");
32
- if (!existsSync(mockDataPath)) {
33
- const defaultJson = {
34
- menu: {
35
- primary: [
36
- { title: "Home", url: "/" },
37
- { title: "Blog", url: "/post" },
38
- { title: "Archive", url: "/archive" }
39
- ]
40
- },
41
- post: [
42
- {
43
- id: 1,
44
- title: "Welcome to ForgeWP: The Headless Revolution",
45
- excerpt: "Discover how ForgeWP bridges standard WordPress themes with React.",
46
- content: "<p>Welcome to ForgeWP! Modify this in mock-data.json.</p>",
47
- date: "May 10, 2026",
48
- author: "Antigravity",
49
- featuredImage: "https://picsum.photos/seed/forgewp/1200/630",
50
- customFields: {}
51
- }
52
- ]
53
- };
54
- const dirPath = path.dirname(mockDataPath);
38
+ const mockDataTsPath = path.join(projectRoot, "cms", "mock-data.ts");
39
+ const mockDataJsonPath = path.join(projectRoot, "cms", "mock-data.json");
40
+ if (!existsSync(mockDataTsPath) && !existsSync(mockDataJsonPath)) {
41
+ const defaultTs = `import { defineWpPosts } from '@forgewp/react';\n\nexport const mockData = defineWpPosts({\n post: [\n {\n id: 1,\n title: "Welcome to ForgeWP: The Headless Revolution",\n excerpt: "Discover how ForgeWP bridges standard WordPress themes with React.",\n content: "<p>Welcome to ForgeWP! Modify this in cms/mock-data.ts.</p>",\n date: "May 10, 2026",\n author: "Antigravity",\n featuredImage: "https://picsum.photos/seed/forgewp/1200/630",\n customFields: {}\n }\n ]\n});\n\nexport default mockData;\n`;
42
+ const dirPath = path.dirname(mockDataTsPath);
55
43
  if (!existsSync(dirPath)) {
56
44
  mkdirSync(dirPath, { recursive: true });
57
45
  }
58
- writeFileSync(mockDataPath, JSON.stringify(defaultJson, null, 2), "utf8");
59
- console.log(` ${pc.green("✅ Seeded Default Database")}: cms/mock-data.json`);
46
+ writeFileSync(mockDataTsPath, defaultTs, "utf8");
47
+ console.log(` ${pc.green("✅ Seeded Default Database")}: cms/mock-data.ts`);
60
48
  repairedCount++;
61
49
  }
62
50
 
package/bin/seed.js ADDED
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import pc from 'picocolors';
6
+ import { loadProductsData } from '../lib/functions/seed-products.js';
7
+ import { loadMockData, normalizeMockSeedData } from '../lib/functions/seed-mock-data.js';
8
+ import { loadConfig } from '../lib/load-config.js';
9
+
10
+ const projectRoot = process.cwd();
11
+ const args = process.argv.slice(2);
12
+ const target = args[0] || 'all';
13
+
14
+ // Preview only: no configuration writes, export, network request, or database access.
15
+ if (args.includes('--dry-run')) {
16
+ if (args.some((arg) => !['mock-data', 'mock', 'posts', '--dry-run', '--json'].includes(arg))) {
17
+ console.error('Dry-run supports mock-data only: forgewp seed mock-data --dry-run [--json]');
18
+ process.exit(1);
19
+ }
20
+ const config = await loadConfig(projectRoot);
21
+ const raw = loadMockData(projectRoot);
22
+ const seed = config.seed || {};
23
+ const data = normalizeMockSeedData(raw, seed.mockData);
24
+ const strategyMap = seed.mockData && typeof seed.mockData === 'object' ? seed.mockData : null;
25
+ const report = {
26
+ mode: 'preview-only',
27
+ configChanged: false,
28
+ databaseConnected: false,
29
+ developmentOnly: seed.developmentOnly !== false,
30
+ sideloadImages: seed.sideloadImages !== false,
31
+ activation: 'Requires export/install; WordPress debug flag, seed markers, and database state are not inspected.',
32
+ types: Object.entries(raw).map(([postType, entries]) => {
33
+ const strategy = strategyMap ? strategyMap[postType] : seed.mockData;
34
+ return {
35
+ postType,
36
+ fixtureCount: Array.isArray(entries) ? entries.length : 0,
37
+ strategy: data[postType] ? (strategy === true ? 'once' : strategy) : false,
38
+ records: data[postType] || [],
39
+ };
40
+ }),
41
+ };
42
+ if (!args.includes('--json')) console.log('Mock seed preview — no files changed. Disabled types have no seed records.\n');
43
+ console.log(JSON.stringify(report, null, 2));
44
+ process.exit(0);
45
+ }
46
+
47
+ console.log(`\n ${pc.bold(pc.bgGreen(pc.black(' 🌱 FORGEWP DATA SEEDER ')))} ${pc.green('— WordPress & WooCommerce Synchronization')}\n`);
48
+
49
+ const configPath = path.join(projectRoot, 'wp.config.ts');
50
+ if (!fs.existsSync(configPath)) {
51
+ console.error(pc.red(`❌ Error: wp.config.ts not found at ${configPath}`));
52
+ process.exit(1);
53
+ }
54
+
55
+ // 1. Inspect Products
56
+ let productsCount = 0;
57
+ if (target === 'all' || target === 'products' || target === 'product') {
58
+ const products = loadProductsData(projectRoot);
59
+ productsCount = products.length;
60
+ if (productsCount > 0) {
61
+ console.log(` 📦 ${pc.bold('WooCommerce Products')}: Found ${pc.green(productsCount)} item(s) in ${pc.cyan('cms/products.ts')}`);
62
+ } else {
63
+ console.log(` 📦 ${pc.bold('WooCommerce Products')}: No products declared in ${pc.yellow('cms/products.ts')}`);
64
+ }
65
+ }
66
+
67
+ // 2. Inspect Mock Data
68
+ let mockTypesCount = 0;
69
+ let totalMockPosts = 0;
70
+ if (target === 'all' || target === 'mock-data' || target === 'mock' || target === 'posts') {
71
+ const mockData = loadMockData(projectRoot);
72
+ const types = Object.keys(mockData);
73
+ mockTypesCount = types.length;
74
+ if (mockTypesCount > 0) {
75
+ types.forEach((t) => {
76
+ const count = Array.isArray(mockData[t]) ? mockData[t].length : 0;
77
+ totalMockPosts += count;
78
+ console.log(` 📝 ${pc.bold(`Post Type "${t}"`)}: Found ${pc.green(count)} mock entry/entries`);
79
+ });
80
+ } else {
81
+ console.log(` 📝 ${pc.bold('Mock Content')}: No mock content declared in ${pc.yellow('cms/mock-data.ts')}`);
82
+ }
83
+ }
84
+
85
+ // 3. Check wp.config.ts for seed settings
86
+ let configRaw = fs.readFileSync(configPath, 'utf8');
87
+ const hasSeedConfig = configRaw.includes('seed:');
88
+
89
+ if (!hasSeedConfig && (productsCount > 0 || mockTypesCount > 0)) {
90
+ console.log(`\n ⚙️ ${pc.cyan('Enabling data seeding in wp.config.ts')}...`);
91
+ const lines = [' seed: {'];
92
+ if (productsCount > 0) {
93
+ lines.push(" products: 'once',");
94
+ }
95
+ if (mockTypesCount > 0) {
96
+ lines.push(" mockData: 'once',");
97
+ }
98
+ lines.push(' developmentOnly: true,');
99
+ lines.push(' },');
100
+ const seedBlock = lines.join('\n') + '\n';
101
+
102
+ if (configRaw.includes('defineConfig({')) {
103
+ configRaw = configRaw.replace(/defineConfig\(\{/, `defineConfig({\n${seedBlock}`);
104
+ fs.writeFileSync(configPath, configRaw, 'utf8');
105
+ console.log(pc.green(` ✅ Added tailored seed configuration to wp.config.ts`));
106
+ }
107
+ } else if (hasSeedConfig) {
108
+ console.log(`\n ✅ ${pc.bold('wp.config.ts')} has active seed configuration.`);
109
+ }
110
+
111
+ console.log(`
112
+ ${pc.bold('🚀 Synchronization Status:')}
113
+ • Local seed configuration has been inspected. This command has not exported PHP or connected to WordPress.
114
+ • Review wp.config.ts, then export and install the theme to generate its configured seed routines.
115
+ • Automatic execution depends on the configured strategy, WordPress debug guard, and existing seed markers.
116
+ • ${pc.dim('Optional:')} If using WP-CLI, you can also run:
117
+ ${pc.cyan('wp forgewp seed-products')}
118
+ ${pc.cyan('wp forgewp seed-mock-data')}
119
+ `);