@forgewp/compiler 0.2.0 → 0.4.1

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 (45) hide show
  1. package/README.md +24 -5
  2. package/bin/analyze.js +158 -0
  3. package/bin/cli.js +29 -4
  4. package/bin/doctor.js +125 -11
  5. package/bin/export.js +20 -0
  6. package/bin/fresh.js +32 -343
  7. package/bin/i18n-extract.js +121 -0
  8. package/bin/i18n-translate.js +112 -0
  9. package/bin/make-block.js +27 -60
  10. package/bin/make-island.js +72 -0
  11. package/bin/make-post-type.js +6 -6
  12. package/bin/make-template.js +145 -0
  13. package/bin/repair.js +2 -2
  14. package/bin/sync-routes.js +28 -158
  15. package/define-config.d.ts +1 -0
  16. package/define-config.js +1 -0
  17. package/lib/adapters/html-adapter.js +65 -0
  18. package/lib/adapters/stub-adapter.js +49 -0
  19. package/lib/add-component.js +290 -73
  20. package/lib/asset-loader.js +27 -0
  21. package/lib/block-compiler.js +552 -0
  22. package/lib/blueprints.js +1459 -501
  23. package/lib/define-config.d.ts +3 -0
  24. package/lib/define-config.js +8 -0
  25. package/lib/diagnostics.js +798 -0
  26. package/lib/export-theme.js +81 -18
  27. package/lib/framework-adapter.js +34 -0
  28. package/lib/functions-builder.js +1801 -0
  29. package/lib/generate-theme.js +1019 -1143
  30. package/lib/hydration-scanner.js +674 -0
  31. package/lib/i18n/extractor.js +60 -0
  32. package/lib/i18n/providers.js +165 -0
  33. package/lib/index.d.ts +119 -1
  34. package/lib/index.js +20 -3
  35. package/lib/load-config.js +122 -6
  36. package/lib/markup-processor.js +584 -0
  37. package/lib/php-builders.js +381 -0
  38. package/lib/react-adapter.js +1336 -0
  39. package/lib/render-static.js +9 -82
  40. package/lib/render-theme.mts +526 -232
  41. package/lib/screenshot-fallback.png +0 -0
  42. package/lib/types.js +1 -0
  43. package/lib/validate-export.js +183 -0
  44. package/package.json +14 -3
  45. package/bin/make-component.js +0 -200
@@ -0,0 +1,674 @@
1
+ import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ /**
5
+ * Scans the theme's page files (page.tsx, layout.tsx, pages/*.tsx)
6
+ * for <Hydrate> boundaries and extracts their resolved kebab-case component names.
7
+ *
8
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
9
+ * @returns {string[]} An array of discovered kebab-case hydration chunk identifiers.
10
+ */
11
+ export function scanForHydrationIslands(themeRoot) {
12
+ const islands = new Set();
13
+ const filesToScan = [];
14
+
15
+ const dirsToScan = [
16
+ path.join(themeRoot, "src", "app"),
17
+ path.join(themeRoot, "src", "components"),
18
+ path.join(themeRoot, "src", "blocks"),
19
+ ];
20
+
21
+ function collectFilesRecursive(dir) {
22
+ if (!existsSync(dir)) return;
23
+ try {
24
+ const items = readdirSync(dir, { withFileTypes: true });
25
+ for (const item of items) {
26
+ const fullPath = path.join(dir, item.name);
27
+ if (item.isDirectory()) {
28
+ collectFilesRecursive(fullPath);
29
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
30
+ filesToScan.push(fullPath);
31
+ }
32
+ }
33
+ } catch {}
34
+ }
35
+
36
+ for (const dir of dirsToScan) {
37
+ collectFilesRecursive(dir);
38
+ }
39
+
40
+ // Scan each file for <Hydrate> occurrences
41
+ for (const filePath of filesToScan) {
42
+ try {
43
+ const content = readFileSync(filePath, "utf8");
44
+
45
+ // Matches <Hydrate ...> ... </Hydrate>
46
+ const hydrateRegex = /<Hydrate\b([\s\S]*?)>([\s\S]*?)<\/Hydrate>/g;
47
+ let match;
48
+ while ((match = hydrateRegex.exec(content)) !== null) {
49
+ const propsStr = match[1];
50
+ const childrenStr = match[2].trim();
51
+
52
+ // 1. Try to parse explicit 'id' attribute
53
+ const idMatch = propsStr.match(/id\s*=\s*["']([^"']*)["']/);
54
+ if (idMatch) {
55
+ islands.add(idMatch[1]);
56
+ continue;
57
+ }
58
+
59
+ // 2. Fallback: Parse Component Tag name from children (e.g. <FadeUpSection />)
60
+ const componentTagMatch = childrenStr.match(/<([A-Z][a-zA-Z0-9]*)\b/);
61
+ if (componentTagMatch) {
62
+ const compName = componentTagMatch[1];
63
+ const kebabName = compName
64
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
65
+ .toLowerCase();
66
+ islands.add(kebabName);
67
+ }
68
+ }
69
+ } catch (err) {
70
+ console.warn(`[Hydration Scanner] Failed to scan file ${filePath}:`, err.message);
71
+ }
72
+ }
73
+
74
+ // 3. Smart Component Discovery: scan src/components/ for interactive/animated components
75
+ const compDir = path.join(themeRoot, "src", "components");
76
+ const interactiveComponents = new Set();
77
+
78
+ function scanComponentsRecursive(dir) {
79
+ if (!existsSync(dir)) return;
80
+ try {
81
+ const items = readdirSync(dir, { withFileTypes: true });
82
+ for (const item of items) {
83
+ const fullPath = path.join(dir, item.name);
84
+ if (item.isDirectory()) {
85
+ scanComponentsRecursive(fullPath);
86
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
87
+ try {
88
+ const fileContent = readFileSync(fullPath, "utf8");
89
+ const hasState = fileContent.includes("useState") || fileContent.includes("useEffect") || fileContent.includes("useRef");
90
+ const hasMotion = fileContent.includes("framer-motion") || fileContent.includes("gsap") || fileContent.includes("animate") || fileContent.includes("motion.");
91
+ if (hasState || hasMotion) {
92
+ const compName = path.basename(item.name, path.extname(item.name));
93
+ interactiveComponents.add(compName);
94
+ }
95
+ } catch {}
96
+ }
97
+ }
98
+ } catch {}
99
+ }
100
+
101
+ scanComponentsRecursive(compDir);
102
+
103
+ for (const filePath of filesToScan) {
104
+ try {
105
+ const content = readFileSync(filePath, "utf8");
106
+ for (const compName of interactiveComponents) {
107
+ if (content.includes(`<${compName}`)) {
108
+ const kebabName = compName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
109
+ if (!islands.has(kebabName)) {
110
+ islands.add(kebabName);
111
+ console.log(`\x1b[33m[ForgeWP Optimizer] Smart Discovery: Detected "${compName}" uses interactive hooks/animations. Auto-enforcing code-splitting chunk. Wrap it in <Hydrate> in page markup for dynamic browser activation!\x1b[0m`);
112
+ }
113
+ }
114
+ }
115
+ } catch {}
116
+ }
117
+
118
+ return Array.from(islands);
119
+ }
120
+
121
+ /**
122
+ * Searches components directories for a file matching the kebab-case component name.
123
+ *
124
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
125
+ * @param {string} kebabName - The target component's kebab-case identifier.
126
+ * @returns {string|null} The absolute path to the component file, or null if not found.
127
+ */
128
+ export function findComponentPath(themeRoot, kebabName) {
129
+ const compDirs = [
130
+ path.join(themeRoot, "src", "components"),
131
+ path.join(themeRoot, "src", "components", "ui"),
132
+ ];
133
+
134
+ // Convert kebab-case back to PascalCase and check candidates
135
+ const pascalName = kebabName
136
+ .split("-")
137
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
138
+ .join("");
139
+
140
+ const candidates = [
141
+ `${pascalName}.tsx`,
142
+ `${pascalName}.ts`,
143
+ `${kebabName}.tsx`,
144
+ `${kebabName}.ts`,
145
+ ];
146
+
147
+ for (const dir of compDirs) {
148
+ if (!existsSync(dir)) continue;
149
+ try {
150
+ const files = readdirSync(dir);
151
+ for (const file of files) {
152
+ if (candidates.includes(file)) {
153
+ return path.join(dir, file);
154
+ }
155
+ }
156
+ } catch {}
157
+ }
158
+
159
+ return null;
160
+ }
161
+
162
+ /**
163
+ * Resolves Rollup's multi-entry input mapping for Vite based on discovered hydration islands.
164
+ *
165
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
166
+ * @returns {Record<string, string>} Rollup input object.
167
+ */
168
+ export function getHydrationRollupInputs(themeRoot) {
169
+ const inputs = {
170
+ index: path.resolve(themeRoot, "index.html"),
171
+ };
172
+
173
+ const islands = scanForHydrationIslands(themeRoot);
174
+ for (const island of islands) {
175
+ const compPath = findComponentPath(themeRoot, island);
176
+ if (compPath) {
177
+ inputs[island] = compPath;
178
+ }
179
+ }
180
+
181
+ // Scan and inject custom blocks from src/blocks/
182
+ const blocksDir = path.join(themeRoot, "src", "blocks");
183
+ if (existsSync(blocksDir)) {
184
+ try {
185
+ const items = readdirSync(blocksDir);
186
+ for (const item of items) {
187
+ const fullPath = path.join(blocksDir, item);
188
+ const isDir = statSync(fullPath).isDirectory();
189
+ if (isDir) {
190
+ const indexPath = path.join(fullPath, "index.tsx");
191
+ if (existsSync(indexPath)) {
192
+ const blockName = item
193
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
194
+ .toLowerCase()
195
+ .replace(/[^a-z0-9]+/g, "-");
196
+ inputs[`block-${blockName}`] = indexPath;
197
+ }
198
+ } else if (item.endsWith(".tsx") || item.endsWith(".jsx")) {
199
+ const blockName = item
200
+ .replace(/\.(tsx|jsx)$/, "")
201
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
202
+ .toLowerCase()
203
+ .replace(/[^a-z0-9]+/g, "-");
204
+ inputs[`block-${blockName}`] = fullPath;
205
+ }
206
+ }
207
+ } catch (err) {
208
+ console.warn("[Hydration Scanner] Failed to scan src/blocks/:", err.message);
209
+ }
210
+ }
211
+
212
+ return inputs;
213
+ }
214
+
215
+ /**
216
+ * Scans theme pages and layout files for <Hydrate> boundaries and extracts their kebab-case names,
217
+ * source files, and defined properties.
218
+ *
219
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
220
+ * @returns {Array<{ name: string, file: string, trigger: string, preload: string, media: string|null, connection: string|null, clientOnly: boolean, smartDiscovered?: boolean }>}
221
+ */
222
+ export function scanForHydrationIslandsWithProps(themeRoot) {
223
+ const discovered = [];
224
+ const namesFound = new Set();
225
+ const filesToScan = [];
226
+
227
+ const dirsToScan = [
228
+ path.join(themeRoot, "src", "app"),
229
+ path.join(themeRoot, "src", "components"),
230
+ path.join(themeRoot, "src", "blocks"),
231
+ ];
232
+
233
+ function collectFilesRecursive(dir) {
234
+ if (!existsSync(dir)) return;
235
+ try {
236
+ const items = readdirSync(dir, { withFileTypes: true });
237
+ for (const item of items) {
238
+ const fullPath = path.join(dir, item.name);
239
+ if (item.isDirectory()) {
240
+ collectFilesRecursive(fullPath);
241
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
242
+ filesToScan.push(fullPath);
243
+ }
244
+ }
245
+ } catch {}
246
+ }
247
+
248
+ for (const dir of dirsToScan) {
249
+ collectFilesRecursive(dir);
250
+ }
251
+
252
+ // Helper to extract attribute values
253
+ const getAttr = (str, attr) => {
254
+ const regex1 = new RegExp(`${attr}\\s*=\\s*["']([^"']*)["']`);
255
+ const regex2 = new RegExp(`${attr}\\s*=\\s*\\{["']([^"']*)["']\\}`);
256
+ const regex3 = new RegExp(`${attr}\\s*=\\s*\\{([^\\}]*)\\}`);
257
+
258
+ const m1 = str.match(regex1);
259
+ if (m1) return m1[1];
260
+ const m2 = str.match(regex2);
261
+ if (m2) return m2[1];
262
+ const m3 = str.match(regex3);
263
+ if (m3) return m3[1].trim();
264
+
265
+ return null;
266
+ };
267
+
268
+ for (const filePath of filesToScan) {
269
+ const relFile = path.relative(themeRoot, filePath).replace(/\\/g, "/");
270
+ try {
271
+ const content = readFileSync(filePath, "utf8");
272
+ const hydrateRegex = /<Hydrate\b([\s\S]*?)>([\s\S]*?)<\/Hydrate>/g;
273
+ let match;
274
+ while ((match = hydrateRegex.exec(content)) !== null) {
275
+ const propsStr = match[1];
276
+ const childrenStr = match[2].trim();
277
+
278
+ // Resolve component identifier name
279
+ let islandName = null;
280
+ const idMatch = propsStr.match(/id\s*=\s*["']([^"']*)["']/);
281
+ if (idMatch) {
282
+ islandName = idMatch[1];
283
+ } else {
284
+ const componentTagMatch = childrenStr.match(/<([A-Z][a-zA-Z0-9]*)\b/);
285
+ if (componentTagMatch) {
286
+ const compName = componentTagMatch[1];
287
+ islandName = compName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
288
+ }
289
+ }
290
+
291
+ if (islandName) {
292
+ namesFound.add(islandName);
293
+ const trigger = getAttr(propsStr, "trigger") || "visible";
294
+ const preload = getAttr(propsStr, "preload") || "none";
295
+ const media = getAttr(propsStr, "media");
296
+ const connection = getAttr(propsStr, "connection") || "any";
297
+ const clientOnly = propsStr.includes("clientOnly") && !propsStr.includes("clientOnly={false}");
298
+
299
+ discovered.push({
300
+ name: islandName,
301
+ file: relFile,
302
+ trigger,
303
+ preload,
304
+ media,
305
+ connection,
306
+ clientOnly,
307
+ });
308
+ }
309
+ }
310
+ } catch (err) {
311
+ console.warn(`[Hydration Scanner] Failed to scan file ${filePath}:`, err.message);
312
+ }
313
+ }
314
+
315
+ // Smart Discovery matching
316
+ const compDir = path.join(themeRoot, "src", "components");
317
+ const interactiveComponents = new Set();
318
+
319
+ function scanComponentsRecursive(dir) {
320
+ if (!existsSync(dir)) return;
321
+ try {
322
+ const items = readdirSync(dir, { withFileTypes: true });
323
+ for (const item of items) {
324
+ const fullPath = path.join(dir, item.name);
325
+ if (item.isDirectory()) {
326
+ scanComponentsRecursive(fullPath);
327
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
328
+ try {
329
+ const fileContent = readFileSync(fullPath, "utf8");
330
+ const hasState = fileContent.includes("useState") || fileContent.includes("useEffect") || fileContent.includes("useRef");
331
+ const hasMotion = fileContent.includes("framer-motion") || fileContent.includes("gsap") || fileContent.includes("animate") || fileContent.includes("motion.");
332
+ if (hasState || hasMotion) {
333
+ const compName = path.basename(item.name, path.extname(item.name));
334
+ interactiveComponents.add(compName);
335
+ }
336
+ } catch {}
337
+ }
338
+ }
339
+ } catch {}
340
+ }
341
+
342
+ scanComponentsRecursive(compDir);
343
+
344
+ for (const filePath of filesToScan) {
345
+ const relFile = path.relative(themeRoot, filePath).replace(/\\/g, "/");
346
+ try {
347
+ const content = readFileSync(filePath, "utf8");
348
+ for (const compName of interactiveComponents) {
349
+ if (content.includes(`<${compName}`)) {
350
+ const kebabName = compName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
351
+ if (!namesFound.has(kebabName)) {
352
+ namesFound.add(kebabName);
353
+ discovered.push({
354
+ name: kebabName,
355
+ file: relFile,
356
+ trigger: "visible",
357
+ preload: "none",
358
+ media: null,
359
+ connection: "any",
360
+ clientOnly: false,
361
+ smartDiscovered: true,
362
+ });
363
+ }
364
+ }
365
+ }
366
+ } catch {}
367
+ }
368
+
369
+ return discovered;
370
+ }
371
+
372
+ /**
373
+ * Statically analyzes theme templates to detect missing metadata,
374
+ * dynamic event handlers in static WpQueryLoop scopes, and hardcoded relative URLs.
375
+ *
376
+ * @param {string} themeRoot
377
+ * @returns {Array<{ type: 'metadata' | 'loop' | 'url', file: string, message: string, severity: 'warning' | 'error', lineContent?: string }>}
378
+ */
379
+ export function runStaticLintChecks(themeRoot) {
380
+ const violations = [];
381
+ const filesToScan = [];
382
+
383
+ const validSlugs = new Set(["page"]);
384
+ const pagesDir = path.join(themeRoot, "src", "app", "pages");
385
+ if (existsSync(pagesDir)) {
386
+ try {
387
+ const pageFiles = readdirSync(pagesDir).filter(f => f.endsWith(".tsx"));
388
+ for (const pf of pageFiles) {
389
+ const pageName = pf.replace(".tsx", "");
390
+ if (pageName.startsWith("Single")) {
391
+ continue;
392
+ }
393
+ const slug = pageName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
394
+ validSlugs.add(slug);
395
+ }
396
+ } catch {}
397
+ }
398
+
399
+ const dirsToScan = [
400
+ path.join(themeRoot, "src", "app"),
401
+ path.join(themeRoot, "src", "components"),
402
+ path.join(themeRoot, "src", "blocks"),
403
+ ];
404
+
405
+ function collectFilesRecursive(dir) {
406
+ if (!existsSync(dir)) return;
407
+ try {
408
+ const items = readdirSync(dir, { withFileTypes: true });
409
+ for (const item of items) {
410
+ const fullPath = path.join(dir, item.name);
411
+ if (item.isDirectory()) {
412
+ collectFilesRecursive(fullPath);
413
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
414
+ filesToScan.push(fullPath);
415
+ }
416
+ }
417
+ } catch {}
418
+ }
419
+
420
+ for (const dir of dirsToScan) {
421
+ collectFilesRecursive(dir);
422
+ }
423
+
424
+ for (const filePath of filesToScan) {
425
+ const relFile = path.relative(themeRoot, filePath).replace(/\\/g, "/");
426
+ try {
427
+ const content = readFileSync(filePath, "utf8");
428
+ const lines = content.split("\n");
429
+
430
+ // 1. Metadata Checks (Only for page files)
431
+ const isPage = path.basename(filePath).startsWith("page.tsx") || filePath.includes("pages/");
432
+ if (isPage) {
433
+ const hasWpHead = content.includes("<WpHead") || content.includes("<WpHead\b");
434
+ if (!hasWpHead) {
435
+ violations.push({
436
+ type: "metadata",
437
+ file: relFile,
438
+ message: "Missing SEO <WpHead> component on this major page template.",
439
+ severity: "warning"
440
+ });
441
+ } else {
442
+ const wpHeadRegex = /<WpHead\b([\s\S]*?)\/?>/g;
443
+ let headMatch;
444
+ while ((headMatch = wpHeadRegex.exec(content)) !== null) {
445
+ const headProps = headMatch[1];
446
+ const hasTitle = /title\s*=\s*(?:["']|\{)/.test(headProps);
447
+ const hasDescription = /description\s*=\s*(?:["']|\{)/.test(headProps);
448
+
449
+ if (!hasTitle) {
450
+ violations.push({
451
+ type: "metadata",
452
+ file: relFile,
453
+ message: "SEO <WpHead> is missing the required 'title' attribute.",
454
+ severity: "warning"
455
+ });
456
+ }
457
+ if (!hasDescription) {
458
+ violations.push({
459
+ type: "metadata",
460
+ file: relFile,
461
+ message: "SEO <WpHead> is missing the required 'description' attribute.",
462
+ severity: "warning"
463
+ });
464
+ }
465
+ }
466
+ }
467
+ }
468
+
469
+ // 2. WpQueryLoop without Hydration check
470
+ const hydrateBlocks = [];
471
+ const hydrateRegex = /<Hydrate\b([\s\S]*?)>([\s\S]*?)<\/Hydrate>/g;
472
+ let hydMatch;
473
+ while ((hydMatch = hydrateRegex.exec(content)) !== null) {
474
+ hydrateBlocks.push({
475
+ start: hydMatch.index,
476
+ end: hydMatch.index + hydMatch[0].length
477
+ });
478
+ }
479
+
480
+ const loopRegex = /<WpQueryLoop\b([\s\S]*?)>([\s\S]*?)<\/WpQueryLoop>/g;
481
+ let loopMatch;
482
+ while ((loopMatch = loopRegex.exec(content)) !== null) {
483
+ const loopBody = loopMatch[2];
484
+ const loopStart = loopMatch.index;
485
+
486
+ const isHydrated = hydrateBlocks.some(hb => loopStart >= hb.start && loopStart <= hb.end);
487
+
488
+ if (!isHydrated) {
489
+ const hasEventHandlers = /\bon[A-Z][a-zA-Z]*\s*=\s*\{/.test(loopBody);
490
+ if (hasEventHandlers) {
491
+ const eventMatch = loopBody.match(/\b(on[A-Z][a-zA-Z]*)\s*=\s*\{/);
492
+ const eventName = eventMatch ? eventMatch[1] : "event handler";
493
+ violations.push({
494
+ type: "loop",
495
+ file: relFile,
496
+ message: `WpQueryLoop contains active interactive handler (${eventName}) but is not wrapped inside a <Hydrate> boundary. It will render static and non-interactive in production WordPress.`,
497
+ severity: "error"
498
+ });
499
+ }
500
+ }
501
+ }
502
+
503
+ // 3. Hardcoded relative internal links check
504
+ for (let i = 0; i < lines.length; i++) {
505
+ const line = lines[i];
506
+ const hrefRegex = /href\s*=\s*["']([^"']*)["']/g;
507
+ let hrefMatch;
508
+ while ((hrefMatch = hrefRegex.exec(line)) !== null) {
509
+ const val = hrefMatch[1];
510
+ const isRelative = val.startsWith("/") &&
511
+ !val.startsWith("//") &&
512
+ !val.startsWith("/wp-") &&
513
+ !val.startsWith("/feed");
514
+ if (isRelative) {
515
+ violations.push({
516
+ type: "url",
517
+ file: relFile,
518
+ message: `Hardcoded relative URL "${val}" found. Use useWpPermalink() to resolve dynamically from WordPress.`,
519
+ severity: "warning",
520
+ lineContent: line.trim() + ` (line ${i + 1})`
521
+ });
522
+ }
523
+ }
524
+
525
+ const jsxHrefRegex = /href\s*=\s*\{\s*["']([^"']*)["']\s*\}/g;
526
+ let jsxHrefMatch;
527
+ while ((jsxHrefMatch = jsxHrefRegex.exec(line)) !== null) {
528
+ const val = jsxHrefMatch[1];
529
+ const isRelative = val.startsWith("/") &&
530
+ !val.startsWith("//") &&
531
+ !val.startsWith("/wp-") &&
532
+ !val.startsWith("/feed");
533
+ if (isRelative) {
534
+ violations.push({
535
+ type: "url",
536
+ file: relFile,
537
+ message: `Hardcoded relative URL "${val}" found. Use useWpPermalink() to resolve dynamically from WordPress.`,
538
+ severity: "warning",
539
+ lineContent: line.trim() + ` (line ${i + 1})`
540
+ });
541
+ }
542
+ }
543
+ }
544
+
545
+ // 4. useWpPageLink template slug typo check
546
+ const pageLinkRegex = /useWpPageLink\s*\(\s*["']([^"']+)["']/g;
547
+ let pageLinkMatch;
548
+ while ((pageLinkMatch = pageLinkRegex.exec(content)) !== null) {
549
+ const slugUsed = pageLinkMatch[1];
550
+ if (!validSlugs.has(slugUsed)) {
551
+ violations.push({
552
+ type: "pagelink",
553
+ file: relFile,
554
+ message: `useWpPageLink references non-existent page template slug "${slugUsed}". Valid slugs: ${Array.from(validSlugs).join(", ")}`,
555
+ severity: "warning"
556
+ });
557
+ }
558
+ }
559
+
560
+ } catch (err) {
561
+ console.warn(`[Static Lint] Failed to scan file ${filePath}:`, err.message);
562
+ }
563
+ }
564
+
565
+ return violations;
566
+ }
567
+
568
+ /**
569
+ * Scans theme template page files for colocated `defineEditable` exports
570
+ * and parses them into a unified schema dictionary.
571
+ *
572
+ * @param {string} themeRoot
573
+ * @returns {Record<string, Record<string, any>>} A map of template/page slug -> parsed schema
574
+ */
575
+ export function scanForEditableSchemas(themeRoot) {
576
+ const schemas = {};
577
+ const filesToScan = [];
578
+
579
+ const dirsToScan = [
580
+ path.join(themeRoot, "src", "app"),
581
+ ];
582
+
583
+ function collectFilesRecursive(dir) {
584
+ if (!existsSync(dir)) return;
585
+ try {
586
+ const items = readdirSync(dir, { withFileTypes: true });
587
+ for (const item of items) {
588
+ const fullPath = path.join(dir, item.name);
589
+ if (item.isDirectory()) {
590
+ collectFilesRecursive(fullPath);
591
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
592
+ filesToScan.push(fullPath);
593
+ }
594
+ }
595
+ } catch {}
596
+ }
597
+
598
+ for (const dir of dirsToScan) {
599
+ collectFilesRecursive(dir);
600
+ }
601
+
602
+ for (const filePath of filesToScan) {
603
+ try {
604
+ const content = readFileSync(filePath, "utf8");
605
+ if (!content.includes("defineEditable")) continue;
606
+
607
+ const schemaStr = extractDefineEditableContent(content);
608
+ if (schemaStr) {
609
+ const parsed = parseEditableSchema(schemaStr);
610
+ if (parsed) {
611
+ // Resolve template slug based on file name or path
612
+ // e.g. "SingleHotelPage.tsx" -> "single-hotel-page"
613
+ // or "page.tsx" -> "front-page" or similar
614
+ const baseName = path.basename(filePath, path.extname(filePath));
615
+ let slug = baseName
616
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
617
+ .toLowerCase();
618
+
619
+ if (slug === 'page') {
620
+ slug = 'front-page';
621
+ }
622
+
623
+ schemas[slug] = parsed;
624
+ }
625
+ }
626
+ } catch (err) {
627
+ console.warn(`[Schema Scanner] Failed to scan file ${filePath}:`, err.message);
628
+ }
629
+ }
630
+
631
+ return schemas;
632
+ }
633
+
634
+ function extractDefineEditableContent(fileContent) {
635
+ const match = fileContent.match(/export\s+const\s+editable\s*=\s*defineEditable\s*\(/);
636
+ if (!match) return null;
637
+
638
+ const startIndex = match.index + match[0].length;
639
+ let parenCount = 1;
640
+ let currentIndex = startIndex;
641
+
642
+ while (parenCount > 0 && currentIndex < fileContent.length) {
643
+ const char = fileContent[currentIndex];
644
+ if (char === '(') {
645
+ parenCount++;
646
+ } else if (char === ')') {
647
+ parenCount--;
648
+ }
649
+ currentIndex++;
650
+ }
651
+
652
+ if (parenCount === 0) {
653
+ return fileContent.substring(startIndex, currentIndex - 1);
654
+ }
655
+ return null;
656
+ }
657
+
658
+ function parseEditableSchema(schemaStr) {
659
+ const text = (opts) => ({ type: 'text', ...opts });
660
+ const richText = (opts) => ({ type: 'richText', ...opts });
661
+ const image = (opts) => ({ type: 'image', ...opts });
662
+ const boolean = (opts) => ({ type: 'boolean', ...opts });
663
+ const repeater = (opts) => ({ type: 'repeater', ...opts });
664
+
665
+ try {
666
+ const fn = new Function('text', 'richText', 'image', 'boolean', 'repeater', `return (${schemaStr})`);
667
+ return fn(text, richText, image, boolean, repeater);
668
+ } catch (e) {
669
+ console.error('[Schema Parser] Failed to evaluate schema literal:', e.message);
670
+ return null;
671
+ }
672
+ }
673
+
674
+