@forgewp/compiler 0.4.2 → 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 (144) hide show
  1. package/README.md +70 -3
  2. package/bin/add.js +30 -15
  3. package/bin/analyze.js +66 -1
  4. package/bin/cli.js +149 -70
  5. package/bin/doctor.js +21 -12
  6. package/bin/export.js +69 -20
  7. package/bin/fresh.js +6 -1
  8. package/bin/i18n-extract.js +3 -10
  9. package/bin/i18n-translate.js +15 -24
  10. package/bin/make-block.js +24 -0
  11. package/bin/make-editable.js +166 -0
  12. package/bin/make-form.js +131 -0
  13. package/bin/make-island.js +11 -0
  14. package/bin/make-loop.js +147 -0
  15. package/bin/make-mail.js +27 -0
  16. package/bin/make-page.js +83 -0
  17. package/bin/make-post-type.js +68 -29
  18. package/bin/make-sandbox.js +609 -0
  19. package/bin/make-section.js +221 -0
  20. package/bin/make-shell.js +375 -0
  21. package/bin/repair.js +14 -26
  22. package/bin/seed.js +119 -0
  23. package/bin/sync-routes.js +107 -85
  24. package/lib/adapters/html-adapter.js +13 -3
  25. package/lib/adapters/stub-adapter.js +10 -2
  26. package/lib/add-component.js +153 -92
  27. package/lib/asset-loader.js +333 -1
  28. package/lib/assets/asset-graph.js +432 -0
  29. package/lib/assets/asset-pipeline.js +125 -0
  30. package/lib/assets/diagnostics-report.js +345 -0
  31. package/lib/assets/external-fetcher.js +173 -0
  32. package/lib/assets/font-orchestrator.js +348 -0
  33. package/lib/assets/font-usage-scanner.js +242 -0
  34. package/lib/assets/image-optimizer.js +229 -0
  35. package/lib/assets/index.js +51 -0
  36. package/lib/assets/preload-generator.js +70 -0
  37. package/lib/assets/public-url.js +153 -0
  38. package/lib/block-authoring-help.js +11 -0
  39. package/lib/blocks/ast-parser.js +67 -0
  40. package/lib/blocks/discover-blocks.js +146 -0
  41. package/lib/blocks/editor-scope.js +733 -0
  42. package/lib/blocks/editor-transpiler.js +1229 -0
  43. package/lib/blocks/index.js +2838 -0
  44. package/lib/blocks/php-transpiler.js +4928 -0
  45. package/lib/blocks/scanner.js +1487 -0
  46. package/lib/blocks/shared-utils.js +290 -0
  47. package/lib/blocks/source-sanitize.js +1449 -0
  48. package/lib/blueprints.js +77 -5
  49. package/lib/build-assets.js +38 -33
  50. package/lib/collect-page-template-routes.js +102 -0
  51. package/lib/collect-static-routes.js +175 -0
  52. package/lib/diagnostics.js +58 -33
  53. package/lib/export-theme.js +84 -5
  54. package/lib/extract-template-content.js +90 -0
  55. package/lib/forms-preview.js +42 -0
  56. package/lib/functions/cpt-routing.js +69 -0
  57. package/lib/functions/forms.js +2461 -0
  58. package/lib/functions/hydration-enqueuer.js +400 -0
  59. package/lib/functions/index.js +1623 -0
  60. package/lib/functions/load-menus.js +112 -0
  61. package/lib/functions/load-translations.js +148 -0
  62. package/lib/functions/rest-endpoints.js +2923 -0
  63. package/lib/functions/routing.js +765 -0
  64. package/lib/functions/seed-mock-data.js +392 -0
  65. package/lib/functions/seed-products.js +481 -0
  66. package/lib/functions/settings-page.js +273 -0
  67. package/lib/functions/theme-setup.js +494 -0
  68. package/lib/generate-theme.js +2076 -303
  69. package/lib/hydration/editable-schemas.js +332 -0
  70. package/lib/hydration/enter-hidden-initial.js +65 -0
  71. package/lib/hydration/form-schemas.js +227 -0
  72. package/lib/hydration/index.js +12 -0
  73. package/lib/hydration/is-interactive.js +951 -0
  74. package/lib/hydration/island-split.js +1231 -0
  75. package/lib/hydration/islands-scanner.js +599 -0
  76. package/lib/hydration/resolve-island-chunk.js +103 -0
  77. package/lib/hydration/resolve-island-component.js +52 -0
  78. package/lib/hydration/rollup-inputs.js +81 -0
  79. package/lib/hydration/root-class-extractor.js +220 -0
  80. package/lib/hydration/scan-app-providers.js +154 -0
  81. package/lib/hydration/static-lint.js +382 -0
  82. package/lib/hydration/transform.js +257 -0
  83. package/lib/hydration/uses-block-area.js +49 -0
  84. package/lib/hydration/utils.js +119 -0
  85. package/lib/i18n/translation-cache.js +141 -0
  86. package/lib/icon-registry.js +72 -0
  87. package/lib/index.d.ts +324 -8
  88. package/lib/index.js +3 -2
  89. package/lib/load-config.js +338 -144
  90. package/lib/mail-templates.js +37 -0
  91. package/lib/markup-processor.js +483 -92
  92. package/lib/node-runtime.js +7 -0
  93. package/lib/page-config-plugin.js +84 -0
  94. package/lib/php-builders.js +383 -42
  95. package/lib/react-adapter.js +1053 -246
  96. package/lib/registration-metadata.js +11 -0
  97. package/lib/render-theme.mts +1410 -543
  98. package/lib/route-layout.js +76 -0
  99. package/lib/template-discovery.js +58 -0
  100. package/lib/theme-compatibility.js +32 -0
  101. package/lib/validate-export.js +51 -2
  102. package/lib/validate.js +27 -5
  103. package/lib/virtual-plugin.js +319 -0
  104. package/lib/walkthrough.md +26 -0
  105. package/package.json +17 -5
  106. package/templates/PresetsStyle.tsx +1 -1
  107. package/templates/auth/cms/email-logs.json +9 -0
  108. package/templates/auth/cms/menus.json +11 -0
  109. package/templates/auth/cms/mock-data.json +123 -0
  110. package/templates/auth/cms/roles.json +7 -0
  111. package/templates/auth/cms/sessions.json +1 -0
  112. package/templates/auth/cms/site-settings.json +28 -0
  113. package/templates/auth/cms/translations.json +4 -0
  114. package/templates/auth/cms/users.json +46 -0
  115. package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
  116. package/templates/auth/components/forgot-password-form-wrapper.tsx +141 -0
  117. package/templates/auth/components/login-form-wrapper.tsx +300 -0
  118. package/templates/auth/components/reset-password-form-wrapper.tsx +190 -0
  119. package/templates/auth/components/signup-form-wrapper.tsx +257 -0
  120. package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
  121. package/templates/auth/pages/DashboardPage.tsx +12 -0
  122. package/templates/auth/pages/ForgotPasswordPage.tsx +11 -0
  123. package/templates/auth/pages/LoginPage.tsx +11 -0
  124. package/templates/auth/pages/ResetPasswordPage.tsx +11 -0
  125. package/templates/auth/pages/SignUpPage.tsx +11 -0
  126. package/templates/auth/pages/VerifyEmailPage.tsx +11 -0
  127. package/templates/auth/ui/button.tsx +57 -0
  128. package/templates/auth/ui/card.tsx +76 -0
  129. package/templates/auth/ui/field.tsx +242 -0
  130. package/templates/auth/ui/input.tsx +22 -0
  131. package/templates/auth/ui/label.tsx +24 -0
  132. package/templates/auth/ui/separator.tsx +31 -0
  133. package/templates/forgewp-config.ts +70 -3
  134. package/templates/menus.json +12 -10
  135. package/templates/mock-data.json +122 -433
  136. package/templates/products.json +5 -0
  137. package/templates/roles.json +7 -0
  138. package/templates/sessions.json +1 -0
  139. package/templates/users.json +38 -0
  140. package/templates/wordpress.tsx +1835 -1297
  141. package/bin/make-template.js +0 -145
  142. package/lib/block-compiler.js +0 -552
  143. package/lib/functions-builder.js +0 -2044
  144. package/lib/hydration-scanner.js +0 -821
@@ -0,0 +1,345 @@
1
+ import { existsSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import pc from 'picocolors';
4
+ import {
5
+ scanFontWeightUsage,
6
+ detectUnusedFontWeights,
7
+ detectUnusedConfiguredWeights,
8
+ } from './font-usage-scanner.js';
9
+
10
+ /**
11
+ * Generate a machine-readable asset manifest and compile diagnostics warnings.
12
+ *
13
+ * @param {string} themeRoot
14
+ * @param {import('./asset-graph.js').AssetGraph} assetGraph
15
+ * @param {Object} [options]
16
+ * @param {string} [options.outDir]
17
+ * @param {Array<Object>} [options.fontRules] - Enriched downloaded font rules
18
+ * @returns {Object} Asset manifest object
19
+ */
20
+ export function generateAssetManifest(themeRoot, assetGraph, options = {}) {
21
+ const outDir = options.outDir || path.join(themeRoot, '.forgewp', 'out');
22
+ const fontRules = options.fontRules || [];
23
+
24
+ const manifest = {
25
+ version: '1.0.0',
26
+ generatedAt: new Date().toISOString(),
27
+ themeRoot,
28
+ summary: {
29
+ totalImages: 0,
30
+ optimizedImages: 0,
31
+ totalVariants: 0,
32
+ totalFonts: fontRules.length,
33
+ preloadedAssets: 0,
34
+ originalSizeBytes: 0,
35
+ optimizedSizeBytes: 0,
36
+ savedBytes: 0,
37
+ savedPercentage: 0,
38
+ },
39
+ images: {},
40
+ fonts: {},
41
+ preloads: [],
42
+ diagnostics: {
43
+ warnings: [],
44
+ unusedFontWeights: [],
45
+ clsNotices: [],
46
+ },
47
+ };
48
+
49
+ if (!assetGraph) {
50
+ return manifest;
51
+ }
52
+
53
+ // 1. Process Images
54
+ const allImages = assetGraph
55
+ .getAllAssets()
56
+ .filter((a) => a.type === 'image' || a.type === 'svg');
57
+ manifest.summary.totalImages = allImages.length;
58
+
59
+ for (const node of allImages) {
60
+ let origSize = 0;
61
+ if (node.resolvedPath && existsSync(node.resolvedPath)) {
62
+ try {
63
+ origSize = statSync(node.resolvedPath).size;
64
+ } catch {}
65
+ }
66
+
67
+ let variantsTotalSize = 0;
68
+ const variantsMeta = [];
69
+ if (node.variants && Array.isArray(node.variants)) {
70
+ manifest.summary.optimizedImages++;
71
+ manifest.summary.totalVariants += node.variants.length;
72
+
73
+ for (const v of node.variants) {
74
+ let vSize = 0;
75
+ if (v.path && existsSync(v.path)) {
76
+ try {
77
+ vSize = statSync(v.path).size;
78
+ } catch {}
79
+ }
80
+ variantsTotalSize += vSize;
81
+ variantsMeta.push({
82
+ width: v.width,
83
+ height: v.height,
84
+ format: v.format,
85
+ publicUrl: v.publicUrl,
86
+ sizeBytes: vSize,
87
+ sizeKb: Number((vSize / 1024).toFixed(1)),
88
+ });
89
+ }
90
+ }
91
+
92
+ manifest.summary.originalSizeBytes += origSize;
93
+ manifest.summary.optimizedSizeBytes += variantsTotalSize || origSize;
94
+
95
+ manifest.images[node.id] = {
96
+ id: node.id,
97
+ source: node.source,
98
+ classification: node.classification,
99
+ width: node.width,
100
+ height: node.height,
101
+ priority: node.priority,
102
+ sizes: node.sizes,
103
+ srcset: node.srcset,
104
+ originalSizeBytes: origSize,
105
+ originalSizeKb: Number((origSize / 1024).toFixed(1)),
106
+ optimizedSizeBytes: variantsTotalSize,
107
+ optimizedSizeKb: Number((variantsTotalSize / 1024).toFixed(1)),
108
+ variants: variantsMeta,
109
+ usageCount: node.usageLocations.length,
110
+ };
111
+
112
+ // Diagnostics checks
113
+ if (!node.width || !node.height) {
114
+ manifest.diagnostics.clsNotices.push({
115
+ assetId: node.id,
116
+ source: node.source,
117
+ message:
118
+ 'Missing explicit width/height (Potential Cumulative Layout Shift risk)',
119
+ });
120
+ }
121
+
122
+ if (node.classification === 'external-url' && node.optimize !== 'build') {
123
+ manifest.diagnostics.warnings.push({
124
+ assetId: node.id,
125
+ source: node.source,
126
+ message:
127
+ 'External image without optimize="build" (served remotely via passthrough)',
128
+ });
129
+ }
130
+
131
+ if (origSize > 1.5 * 1024 * 1024) {
132
+ manifest.diagnostics.warnings.push({
133
+ assetId: node.id,
134
+ source: node.source,
135
+ message: `Heavy original image (${(origSize / (1024 * 1024)).toFixed(2)} MB). Consider resizing or compressing.`,
136
+ });
137
+ }
138
+
139
+ // Check for raw <img> HTML element usage
140
+ const imgUsage = (node.usageLocations || []).find(
141
+ (l) => l.component === 'img',
142
+ );
143
+ if (imgUsage) {
144
+ manifest.diagnostics.rawImgWarnings =
145
+ manifest.diagnostics.rawImgWarnings || [];
146
+ manifest.diagnostics.rawImgWarnings.push({
147
+ assetId: node.id,
148
+ source: node.source,
149
+ file: imgUsage.file,
150
+ line: imgUsage.line,
151
+ message: `Using raw <img> tag in ${imgUsage.file}:${imgUsage.line}. Replace with <WpImage> to enable responsive WebP variants, LCP preloading, and CLS layout protection.`,
152
+ });
153
+ }
154
+ }
155
+
156
+ // 2. Process Fonts & Unused Weight Detection
157
+ const { usedWeights } = scanFontWeightUsage(themeRoot);
158
+ const unusedFromRules = detectUnusedFontWeights(fontRules, usedWeights);
159
+ const fontConfig =
160
+ options.config?.fonts?.google ||
161
+ options.config?.settings?.typography?.googleFonts ||
162
+ null;
163
+ const unusedFromConfig = fontConfig
164
+ ? detectUnusedConfiguredWeights(fontConfig, usedWeights)
165
+ : [];
166
+
167
+ // Merge and deduplicate unused font warnings
168
+ const combinedUnused = [...unusedFromRules];
169
+ for (const u of unusedFromConfig) {
170
+ if (
171
+ !combinedUnused.some(
172
+ (r) => r.family === u.family && Number(r.weight) === Number(u.weight),
173
+ )
174
+ ) {
175
+ combinedUnused.push(u);
176
+ }
177
+ }
178
+ manifest.diagnostics.unusedFontWeights = combinedUnused;
179
+
180
+ for (const rule of fontRules) {
181
+ let fileSize = 0;
182
+ if (rule.localPath && existsSync(rule.localPath)) {
183
+ try {
184
+ fileSize = statSync(rule.localPath).size;
185
+ } catch {}
186
+ }
187
+
188
+ manifest.fonts[rule.filename] = {
189
+ family: rule.family,
190
+ weight: rule.weight,
191
+ style: rule.style,
192
+ publicUrl: rule.publicUrl,
193
+ sizeBytes: fileSize,
194
+ sizeKb: Number((fileSize / 1024).toFixed(1)),
195
+ usedInSource: usedWeights.has(Number(rule.weight)),
196
+ };
197
+ }
198
+
199
+ // 3. Process Preloaded Assets
200
+ const priorityNodes = assetGraph.getPriorityAssets();
201
+ manifest.summary.preloadedAssets = priorityNodes.length;
202
+ manifest.preloads = priorityNodes.map((n) => ({
203
+ id: n.id,
204
+ source: n.source,
205
+ type: n.type,
206
+ classification: n.classification,
207
+ }));
208
+
209
+ // Compute overall savings
210
+ if (
211
+ manifest.summary.originalSizeBytes > 0 &&
212
+ manifest.summary.optimizedSizeBytes < manifest.summary.originalSizeBytes
213
+ ) {
214
+ manifest.summary.savedBytes =
215
+ manifest.summary.originalSizeBytes - manifest.summary.optimizedSizeBytes;
216
+ manifest.summary.savedPercentage = Number(
217
+ (
218
+ (manifest.summary.savedBytes / manifest.summary.originalSizeBytes) *
219
+ 100
220
+ ).toFixed(1),
221
+ );
222
+ }
223
+
224
+ // Save asset-manifest.json to theme outDir and .forgewp
225
+ try {
226
+ if (!existsSync(outDir)) {
227
+ mkdirSync(outDir, { recursive: true });
228
+ }
229
+ writeFileSync(
230
+ path.join(outDir, 'asset-manifest.json'),
231
+ JSON.stringify(manifest, null, 2),
232
+ 'utf8',
233
+ );
234
+
235
+ const forgewpDir = path.join(themeRoot, '.forgewp');
236
+ if (existsSync(forgewpDir)) {
237
+ writeFileSync(
238
+ path.join(forgewpDir, 'asset-manifest.json'),
239
+ JSON.stringify(manifest, null, 2),
240
+ 'utf8',
241
+ );
242
+ }
243
+ } catch {}
244
+
245
+ return manifest;
246
+ }
247
+
248
+ /**
249
+ * Print a polished ASCII Asset & Performance Diagnostics Report in the terminal.
250
+ *
251
+ * @param {Object} manifest
252
+ */
253
+ export function printAssetDiagnosticsReport(manifest) {
254
+ if (process.env.FORGEWP_VERBOSE !== '1') return;
255
+ if (!manifest) return;
256
+
257
+ console.log(pc.cyan('\n🩺 FORGEWP ASSET & PERFORMANCE DIAGNOSTICS'));
258
+
259
+ // 1. Output Optimized Images
260
+ const imageEntries = Object.values(manifest.images || {}).filter(
261
+ (img) => img.variants && img.variants.length > 0,
262
+ );
263
+ for (const img of imageEntries.slice(0, 8)) {
264
+ const name = path.basename(img.source);
265
+ const dots = '.'.repeat(Math.max(2, 28 - name.length));
266
+ const widths = img.variants.map((v) => `${v.width}w`).join(', ');
267
+ const savings =
268
+ img.originalSizeBytes && img.optimizedSizeBytes
269
+ ? `[ -${(((img.originalSizeBytes - img.optimizedSizeBytes) / img.originalSizeBytes) * 100).toFixed(0)}% / ${img.optimizedSizeKb} KB ]`
270
+ : `[ ${widths} ]`;
271
+
272
+ console.log(
273
+ ` ${pc.green('✅')} ${pc.white(name)}${pc.dim(dots)} WebP (${widths}) ${pc.dim(savings)}`,
274
+ );
275
+ }
276
+
277
+ // 2. Output Fonts
278
+ const fontCount = Object.keys(manifest.fonts || {}).length;
279
+ if (fontCount > 0) {
280
+ const families = [
281
+ ...new Set(Object.values(manifest.fonts).map((f) => f.family)),
282
+ ].join(', ');
283
+ const dots = '.'.repeat(Math.max(2, 28 - 'google-fonts'.length));
284
+ console.log(
285
+ ` ${pc.green('✅')} ${pc.white('google-fonts')}${pc.dim(dots)} ${fontCount} WOFF2 file(s) self-hosted (${families})`,
286
+ );
287
+ }
288
+
289
+ // 3. Output Preload Signals
290
+ for (const p of manifest.preloads || []) {
291
+ const name = path.basename(p.source);
292
+ const dots = '.'.repeat(Math.max(2, 28 - 'LCP Preload'.length));
293
+ console.log(
294
+ ` ${pc.green('✅')} ${pc.white('LCP Preload')}${pc.dim(dots)} Injected <link rel="preload"> for ${name}`,
295
+ );
296
+ }
297
+
298
+ // 4. Output Unused Font Weight Warnings
299
+ for (const u of manifest.diagnostics?.unusedFontWeights || []) {
300
+ const label = `${u.family} ${u.weight}`;
301
+ const dots = '.'.repeat(Math.max(2, 28 - 'Unused Font Weight'.length));
302
+ const saveNotice = u.sizeKb > 0 ? ` (saves ~${u.sizeKb} KB)` : '';
303
+ console.log(
304
+ ` ${pc.yellow('⚠️ ')} ${pc.yellow('Unused Font Weight')}${pc.dim(dots)} ${label} configured in wp.config.ts but never used in src/${pc.dim(saveNotice)}`,
305
+ );
306
+ }
307
+
308
+ // 5. Output CLS Notices
309
+ for (const cls of (manifest.diagnostics?.clsNotices || []).slice(0, 3)) {
310
+ const name = path.basename(cls.source);
311
+ const dots = '.'.repeat(Math.max(2, 28 - name.length));
312
+ console.log(
313
+ ` ${pc.yellow('⚠️ ')} ${pc.white(name)}${pc.dim(dots)} Missing width/height in JSX (Inferred for CLS safety)`,
314
+ );
315
+ }
316
+
317
+ // 6. Output Raw <img> Tag Replacement Notices
318
+ for (const imgW of (manifest.diagnostics?.rawImgWarnings || []).slice(0, 3)) {
319
+ const loc = imgW.file
320
+ ? `${path.basename(imgW.file)}:${imgW.line}`
321
+ : path.basename(imgW.source);
322
+ const dots = '.'.repeat(Math.max(2, 28 - 'Raw <img> Tag'.length));
323
+ console.log(
324
+ ` ${pc.yellow('⚠️ ')} ${pc.yellow('Raw <img> Tag')}${pc.dim(dots)} ${loc} (Replace <img> with <WpImage> for auto-WebP & preloads)`,
325
+ );
326
+ }
327
+
328
+ // 7. Summary Footer
329
+ console.log(
330
+ pc.dim('────────────────────────────────────────────────────────────'),
331
+ );
332
+ const savedMb = (manifest.summary.savedBytes / (1024 * 1024)).toFixed(1);
333
+ const totalImg = manifest.summary.totalImages;
334
+ const optImg = manifest.summary.optimizedImages;
335
+
336
+ if (manifest.summary.savedBytes > 0) {
337
+ console.log(
338
+ ` ${pc.bold(pc.green('ASSETS OPTIMIZED:'))} ${optImg}/${totalImg} images optimized (${savedMb} MB saved, ${manifest.summary.savedPercentage}% reduction). Zero render-blocking font hops.\n`,
339
+ );
340
+ } else {
341
+ console.log(
342
+ ` ${pc.bold(pc.green('ASSETS PROCESSED:'))} ${totalImg} asset(s) verified. Zero render-blocking font hops.\n`,
343
+ );
344
+ }
345
+ }
@@ -0,0 +1,173 @@
1
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { generateResponsiveVariants } from './image-optimizer.js';
5
+
6
+ /**
7
+ * Compute URL hash for disk caching.
8
+ */
9
+ export function computeUrlHash(url) {
10
+ return crypto.createHash('sha256').update(url).digest('hex').slice(0, 16);
11
+ }
12
+
13
+ /**
14
+ * Fetch a remote image with timeout and disk caching.
15
+ *
16
+ * @param {string} url - External image URL
17
+ * @param {Object} [options]
18
+ * @param {string} [options.cacheDir] - Directory to persist downloaded images
19
+ * @param {number} [options.timeout=5000] - Request timeout in ms
20
+ * @returns {Promise<{ buffer: Buffer, contentType: string, cached: boolean }>}
21
+ */
22
+ export async function fetchExternalImage(url, options = {}) {
23
+ if (!/^https?:\/\//i.test(url)) {
24
+ throw new Error(`[ForgeWP External Asset] Invalid HTTP/HTTPS URL: ${url}`);
25
+ }
26
+
27
+ const cacheDir = options.cacheDir || null;
28
+ const urlHash = computeUrlHash(url);
29
+ const timeoutMs = options.timeout || 5000;
30
+
31
+ // Check cache
32
+ if (cacheDir) {
33
+ const manifestPath = path.join(cacheDir, 'manifest.json');
34
+ if (existsSync(manifestPath)) {
35
+ try {
36
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
37
+ const entry = manifest[urlHash];
38
+ if (entry && existsSync(entry.filePath)) {
39
+ const buffer = readFileSync(entry.filePath);
40
+ return { buffer, contentType: entry.contentType, cached: true };
41
+ }
42
+ } catch {}
43
+ }
44
+ }
45
+
46
+ const controller = new AbortController();
47
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
48
+
49
+ let response;
50
+ try {
51
+ response = await fetch(url, {
52
+ signal: controller.signal,
53
+ headers: {
54
+ 'User-Agent': 'ForgeWP-Asset-Compiler/1.0',
55
+ Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
56
+ },
57
+ });
58
+ } catch (err) {
59
+ clearTimeout(timer);
60
+ throw new Error(`[ForgeWP External Asset] Network fetch failed for ${url}: ${err.message}`);
61
+ } finally {
62
+ clearTimeout(timer);
63
+ }
64
+
65
+ if (!response.ok) {
66
+ throw new Error(`[ForgeWP External Asset] HTTP ${response.status} fetching ${url}`);
67
+ }
68
+
69
+ const contentType = response.headers.get('content-type') || 'image/jpeg';
70
+ const arrayBuffer = await response.arrayBuffer();
71
+ const buffer = Buffer.from(arrayBuffer);
72
+
73
+ // Write to cache
74
+ if (cacheDir) {
75
+ try {
76
+ if (!existsSync(cacheDir)) {
77
+ mkdirSync(cacheDir, { recursive: true });
78
+ }
79
+ const ext = contentType.includes('png')
80
+ ? '.png'
81
+ : contentType.includes('webp')
82
+ ? '.webp'
83
+ : contentType.includes('svg')
84
+ ? '.svg'
85
+ : '.jpg';
86
+
87
+ const filePath = path.join(cacheDir, `${urlHash}${ext}`);
88
+ writeFileSync(filePath, buffer);
89
+
90
+ const manifestPath = path.join(cacheDir, 'manifest.json');
91
+ let manifest = {};
92
+ if (existsSync(manifestPath)) {
93
+ try {
94
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
95
+ } catch {}
96
+ }
97
+ manifest[urlHash] = { url, filePath, contentType, timestamp: Date.now() };
98
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), 'utf8');
99
+ } catch {}
100
+ }
101
+
102
+ return { buffer, contentType, cached: false };
103
+ }
104
+
105
+ /**
106
+ * Process all external images with optimize="build" in the AssetGraph.
107
+ *
108
+ * @param {string} themeRoot
109
+ * @param {import('./asset-graph.js').AssetGraph} assetGraph
110
+ * @param {Object} [options]
111
+ * @param {string} [options.outDir]
112
+ * @param {string} [options.cacheDir]
113
+ * @param {number} [options.quality=80]
114
+ * @returns {Promise<{ processedCount: number, errors: Array }>}
115
+ */
116
+ export async function processExternalBuildOptimizations(themeRoot, assetGraph, options = {}) {
117
+ if (!assetGraph) return { processedCount: 0, errors: [] };
118
+
119
+ const outDir = options.outDir || path.join(themeRoot, '.forgewp', 'out');
120
+ const targetImagesDir = path.join(outDir, 'assets', 'images');
121
+ const externalCacheDir = options.cacheDir
122
+ ? path.join(options.cacheDir, 'external')
123
+ : path.join(themeRoot, '.forgewp', 'cache', 'external');
124
+ const quality = options.quality || 80;
125
+
126
+ const externalAssets = assetGraph.getExternalAssets();
127
+ const buildOptimizable = externalAssets.filter((node) => node.optimize === 'build');
128
+
129
+ const results = {
130
+ processedCount: 0,
131
+ errors: [],
132
+ };
133
+
134
+ for (const node of buildOptimizable) {
135
+ try {
136
+ const { buffer } = await fetchExternalImage(node.source, {
137
+ cacheDir: externalCacheDir,
138
+ timeout: 6000,
139
+ });
140
+
141
+ const urlHash = computeUrlHash(node.source);
142
+ const baseName = `ext-${urlHash}`;
143
+
144
+ const optimized = await generateResponsiveVariants(
145
+ buffer,
146
+ baseName,
147
+ targetImagesDir,
148
+ {
149
+ quality,
150
+ publicUrlPrefix: 'assets/images',
151
+ },
152
+ );
153
+
154
+ node.width = node.width || optimized.original.width;
155
+ node.height = node.height || optimized.original.height;
156
+ node.variants = optimized.variants;
157
+ node.srcset = optimized.srcset;
158
+ node.blurDataURL = optimized.blurDataURL;
159
+ node.localOptimized = true;
160
+
161
+ results.processedCount++;
162
+ } catch (err) {
163
+ results.errors.push({
164
+ assetId: node.id,
165
+ source: node.source,
166
+ message: err.message,
167
+ });
168
+ console.warn(`⚠️ [ForgeWP Optimizer] Could not download external image ${node.source}: ${err.message}. Falling back to remote passthrough.`);
169
+ }
170
+ }
171
+
172
+ return results;
173
+ }