@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,1231 @@
1
+ import {
2
+ readFileSync,
3
+ writeFileSync,
4
+ mkdirSync,
5
+ existsSync,
6
+ readdirSync,
7
+ } from 'node:fs';
8
+ import path from 'node:path';
9
+ import {
10
+ ts,
11
+ createInteractivityChecker,
12
+ setContentOverride,
13
+ clearContentOverrides,
14
+ CLIENT_ANIMATION_PACKAGES,
15
+ } from './is-interactive.js';
16
+
17
+ // Well-known JS/browser globals that need no import and are never a prop or
18
+ // local declaration — referencing one of these must not force a bail-out.
19
+ const KNOWN_GLOBALS = new Set([
20
+ 'console',
21
+ 'window',
22
+ 'document',
23
+ 'navigator',
24
+ 'localStorage',
25
+ 'sessionStorage',
26
+ 'Math',
27
+ 'JSON',
28
+ 'Array',
29
+ 'Object',
30
+ 'String',
31
+ 'Number',
32
+ 'Boolean',
33
+ 'Date',
34
+ 'RegExp',
35
+ 'Map',
36
+ 'Set',
37
+ 'Promise',
38
+ 'Symbol',
39
+ 'Error',
40
+ 'TypeError',
41
+ 'RangeError',
42
+ 'parseInt',
43
+ 'parseFloat',
44
+ 'isNaN',
45
+ 'isFinite',
46
+ 'encodeURIComponent',
47
+ 'decodeURIComponent',
48
+ 'setTimeout',
49
+ 'clearTimeout',
50
+ 'setInterval',
51
+ 'clearInterval',
52
+ 'fetch',
53
+ 'undefined',
54
+ 'NaN',
55
+ 'Infinity',
56
+ 'globalThis',
57
+ 'URLSearchParams',
58
+ 'URL',
59
+ 'FormData',
60
+ 'Headers',
61
+ 'AbortController',
62
+ 'Intl',
63
+ ]);
64
+
65
+ /** True for JsxElement/JsxSelfClosingElement/JsxFragment nodes. */
66
+ function isJsxNode(node) {
67
+ return (
68
+ node &&
69
+ (node.kind === ts.SyntaxKind.JsxElement ||
70
+ node.kind === ts.SyntaxKind.JsxSelfClosingElement ||
71
+ node.kind === ts.SyntaxKind.JsxFragment)
72
+ );
73
+ }
74
+
75
+ // Mirrors islands-scanner.js's scan roots — new islands land in a dedicated
76
+ // subfolder of src/components so Smart Discovery picks them up with zero
77
+ // additional wiring, same as a hand-written child component today.
78
+ const SCAN_DIRS = ['src/app', 'src/components', 'src/blocks'];
79
+ export const GENERATED_ISLANDS_DIRNAME = '.forgewp-islands';
80
+
81
+ function collectCandidateFiles(themeRoot) {
82
+ const files = [];
83
+ function walk(dir) {
84
+ let entries;
85
+ try {
86
+ entries = readdirSync(dir, { withFileTypes: true });
87
+ } catch {
88
+ return;
89
+ }
90
+ for (const entry of entries) {
91
+ if (
92
+ entry.name === GENERATED_ISLANDS_DIRNAME ||
93
+ entry.name === 'generated'
94
+ )
95
+ continue;
96
+ const full = path.join(dir, entry.name);
97
+ if (entry.isDirectory()) {
98
+ walk(full);
99
+ } else if (entry.name.endsWith('.tsx')) {
100
+ files.push(full);
101
+ }
102
+ }
103
+ }
104
+ for (const dir of SCAN_DIRS) {
105
+ const abs = path.join(themeRoot, dir);
106
+ if (existsSync(abs)) walk(abs);
107
+ }
108
+ return files;
109
+ }
110
+
111
+ function collectBindingNames(nameNode, out = []) {
112
+ if (ts.isIdentifier(nameNode)) {
113
+ out.push(nameNode.text);
114
+ } else if (
115
+ ts.isObjectBindingPattern(nameNode) ||
116
+ ts.isArrayBindingPattern(nameNode)
117
+ ) {
118
+ for (const el of nameNode.elements) {
119
+ if (ts.isBindingElement(el)) collectBindingNames(el.name, out);
120
+ }
121
+ }
122
+ return out;
123
+ }
124
+
125
+ /** Every var/let/const/parameter/catch-binding name declared anywhere within `node` (including inside further-nested functions) — see collectFreeIdentifiers' nested-function handling for why this is collected upfront rather than scope-by-scope. */
126
+ function collectAllBoundNamesDeep(node) {
127
+ const names = new Set();
128
+ function walk(n) {
129
+ if (!n) return;
130
+ if (ts.isVariableDeclaration(n) || ts.isParameter(n)) {
131
+ collectBindingNames(n.name).forEach((x) => names.add(x));
132
+ } else if (ts.isCatchClause(n) && n.variableDeclaration) {
133
+ collectBindingNames(n.variableDeclaration.name).forEach((x) =>
134
+ names.add(x),
135
+ );
136
+ }
137
+ ts.forEachChild(n, walk);
138
+ }
139
+ walk(node);
140
+ return names;
141
+ }
142
+
143
+ /** Finds the component's own top-level `return (<jsx>)`, never descending into nested callbacks/functions. */
144
+ function findReturnJsx(block) {
145
+ let found = null;
146
+ function visit(node) {
147
+ if (found) return;
148
+ if (ts.isFunctionLike(node)) return;
149
+ if (ts.isReturnStatement(node) && node.expression) {
150
+ let expr = node.expression;
151
+ while (ts.isParenthesizedExpression(expr)) expr = expr.expression;
152
+ if (isJsxNode(expr)) {
153
+ found = { jsxRoot: expr, returnStatement: node };
154
+ return;
155
+ }
156
+ }
157
+ ts.forEachChild(node, visit);
158
+ }
159
+ ts.forEachChild(block, visit);
160
+ return found;
161
+ }
162
+
163
+ /** Locates the single exported component function in a source file (v1: destructured single-param components only). */
164
+ function findComponentFunction(sourceFile) {
165
+ let result = null;
166
+ function visit(node) {
167
+ if (result) return;
168
+ if (ts.isFunctionDeclaration(node) && node.name && node.body) {
169
+ const found = findReturnJsx(node.body);
170
+ if (found) {
171
+ result = {
172
+ fnNode: node,
173
+ fnBody: node.body,
174
+ componentName: node.name.text,
175
+ ...found,
176
+ };
177
+ return;
178
+ }
179
+ }
180
+ if (
181
+ ts.isVariableDeclaration(node) &&
182
+ node.name &&
183
+ ts.isIdentifier(node.name) &&
184
+ node.initializer
185
+ ) {
186
+ const init = node.initializer;
187
+ if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) {
188
+ if (ts.isBlock(init.body)) {
189
+ const found = findReturnJsx(init.body);
190
+ if (found) {
191
+ result = {
192
+ fnNode: init,
193
+ fnBody: init.body,
194
+ componentName: node.name.text,
195
+ ...found,
196
+ };
197
+ return;
198
+ }
199
+ } else if (isJsxNode(init.body)) {
200
+ result = {
201
+ fnNode: init,
202
+ fnBody: null,
203
+ componentName: node.name.text,
204
+ jsxRoot: init.body,
205
+ returnStatement: null,
206
+ };
207
+ return;
208
+ }
209
+ }
210
+ }
211
+ ts.forEachChild(node, visit);
212
+ }
213
+ visit(sourceFile);
214
+ return result;
215
+ }
216
+
217
+ /** v1 supports only a single destructured-object parameter (the shape every real component in this codebase uses). */
218
+ function collectComponentParamNames(fnNode) {
219
+ if (!fnNode.parameters || fnNode.parameters.length === 0)
220
+ return { names: new Set(), supported: true };
221
+ if (fnNode.parameters.length > 1)
222
+ return { names: new Set(), supported: false };
223
+ const param = fnNode.parameters[0];
224
+ if (ts.isObjectBindingPattern(param.name)) {
225
+ return { names: new Set(collectBindingNames(param.name)), supported: true };
226
+ }
227
+ return { names: new Set(), supported: false };
228
+ }
229
+
230
+ function collectLocalDeclarations(fnBody, returnStatement) {
231
+ const decls = [];
232
+ if (!fnBody || !ts.isBlock(fnBody)) return decls;
233
+ for (const stmt of fnBody.statements) {
234
+ if (stmt === returnStatement) break;
235
+ if (ts.isVariableStatement(stmt)) {
236
+ for (const decl of stmt.declarationList.declarations) {
237
+ decls.push({
238
+ names: collectBindingNames(decl.name),
239
+ node: decl,
240
+ statement: stmt,
241
+ initializer: decl.initializer,
242
+ });
243
+ }
244
+ } else {
245
+ // Any other statement shape before return (if-blocks, plain function
246
+ // declarations, etc.) is unmodeled in v1 — signal via a synthetic
247
+ // "unsupported" declaration name so callers can bail conservatively
248
+ // rather than silently ignoring code that might matter.
249
+ decls.push({
250
+ names: [],
251
+ node: stmt,
252
+ statement: stmt,
253
+ initializer: null,
254
+ unsupportedStatement: true,
255
+ });
256
+ }
257
+ }
258
+ return decls;
259
+ }
260
+
261
+ /**
262
+ * Free (unbound) identifier references within `node` — excludes property-access
263
+ * `.name` targets, JSX attribute names, import specifiers, and names bound by
264
+ * nested function parameters within `node` itself (so a `.map(item => ...)`
265
+ * callback's own `item` never leaks out as a false "free variable").
266
+ */
267
+ function collectFreeIdentifiers(node, opts = {}) {
268
+ const { stopAtJsxBoundary = false, excludeNodes = null } = opts;
269
+ const free = new Set();
270
+ if (!node) return free;
271
+
272
+ function visit(n, bound) {
273
+ if (!n) return;
274
+ if (stopAtJsxBoundary && n !== node && isJsxNode(n)) return;
275
+ if (excludeNodes && n !== node && excludeNodes.has(n)) return;
276
+ if (ts.isIdentifier(n)) {
277
+ const parent = n.parent;
278
+ if (parent) {
279
+ if (ts.isPropertyAccessExpression(parent) && parent.name === n) return;
280
+ if (ts.isJsxAttribute(parent) && parent.name === n) return;
281
+ if (ts.isImportSpecifier(parent) || ts.isImportClause(parent)) return;
282
+ if (ts.isPropertyAssignment(parent) && parent.name === n) return;
283
+ if (ts.isBindingElement(parent) && parent.propertyName === n) return;
284
+ // Lowercase JSX tag names (`<div>`, `<span>`) are intrinsic HTML
285
+ // elements, not identifier references — skip them, but NOT uppercase
286
+ // component tag names (`<WpLink>`), which really do reference a
287
+ // binding in scope (a module import, prop, or local) that must still
288
+ // be resolved/copied for the extraction to be valid.
289
+ if (
290
+ (ts.isJsxOpeningElement(parent) ||
291
+ ts.isJsxClosingElement(parent) ||
292
+ ts.isJsxSelfClosingElement(parent)) &&
293
+ parent.tagName === n &&
294
+ n.text[0] === n.text[0].toLowerCase()
295
+ ) {
296
+ return;
297
+ }
298
+ }
299
+ if (!bound.has(n.text)) free.add(n.text);
300
+ return;
301
+ }
302
+ if (
303
+ ts.isArrowFunction(n) ||
304
+ ts.isFunctionExpression(n) ||
305
+ ts.isFunctionDeclaration(n)
306
+ ) {
307
+ // Not just parameters — a handler body commonly declares its own
308
+ // locals (`const params = new URLSearchParams();` inside a submit
309
+ // handler). Without collecting those too, a reference to `params`
310
+ // inside that SAME handler would incorrectly look like a free
311
+ // variable needing external resolution, when it's entirely
312
+ // self-contained. Collecting every var/let/const/param name anywhere
313
+ // within this function (including inside further-nested callbacks) is
314
+ // a safe over-approximation for this purpose — it only risks masking
315
+ // a genuinely free variable in the rare case of intentional shadowing.
316
+ const nested = new Set(bound);
317
+ collectAllBoundNamesDeep(n).forEach((x) => nested.add(x));
318
+ ts.forEachChild(n, (c) => visit(c, nested));
319
+ return;
320
+ }
321
+ ts.forEachChild(n, (c) => visit(c, bound));
322
+ }
323
+
324
+ visit(node, new Set());
325
+ return free;
326
+ }
327
+
328
+ /** Dependency-closure hook-taint propagation over the component's local declarations. */
329
+ function computeHookTaint(localDecls, isNodeInteractive) {
330
+ const taint = new Map();
331
+ const declByName = new Map();
332
+ for (const d of localDecls) {
333
+ for (const n of d.names) declByName.set(n, d);
334
+ }
335
+
336
+ function resolve(name, stack) {
337
+ if (taint.has(name)) return taint.get(name);
338
+ if (stack.has(name)) {
339
+ taint.set(name, true);
340
+ return true;
341
+ }
342
+ stack.add(name);
343
+ const decl = declByName.get(name);
344
+ if (!decl || decl.unsupportedStatement) {
345
+ taint.set(name, false);
346
+ return false;
347
+ }
348
+ let result = decl.initializer ? isNodeInteractive(decl.initializer) : false;
349
+ if (!result && decl.initializer) {
350
+ for (const f of collectFreeIdentifiers(decl.initializer)) {
351
+ if (declByName.has(f) && resolve(f, stack)) {
352
+ result = true;
353
+ break;
354
+ }
355
+ }
356
+ }
357
+ taint.set(name, result);
358
+ return result;
359
+ }
360
+
361
+ for (const d of localDecls) {
362
+ for (const n of d.names) resolve(n, new Set());
363
+ }
364
+ return { taint, declByName };
365
+ }
366
+
367
+ /** Immediate JSX-element descendants of `node` — nearest JsxElement/JsxSelfClosingElement/JsxFragment nodes, not descending past one once found (so ternary/logical-and branches count as immediate children even through intervening non-JSX expressions). */
368
+ function findImmediateJsxChildren(node) {
369
+ const children = [];
370
+ function visit(n) {
371
+ if (n !== node && isJsxNode(n)) {
372
+ children.push(n);
373
+ return;
374
+ }
375
+ ts.forEachChild(n, visit);
376
+ }
377
+ ts.forEachChild(node, visit);
378
+ return children;
379
+ }
380
+
381
+ /**
382
+ * True when `node` has interactivity attributable to ITSELF — its own tag's
383
+ * attributes (e.g. an onSubmit handler) or a hook-tainted identifier
384
+ * referenced directly in its own text/expression children — as opposed to
385
+ * interactivity that only exists because a NESTED JSX child element is
386
+ * interactive. Nested JSX elements are treated as opaque boundaries here
387
+ * (their own interactivity is evaluated separately, as their own candidate).
388
+ *
389
+ * This distinction matters: a `<form onSubmit={...}>` containing an
390
+ * `<input onChange={...}>` is interactive both ways at once — without this
391
+ * check, a naive "does any child need to move" test would extract only the
392
+ * `<input>` and strand the form's own onSubmit handler behind in the
393
+ * now-static shell, producing broken/dead code.
394
+ */
395
+ function hasOwnInteractivity(node, isNodeInteractiveWithBoundary, hookTaint) {
396
+ if (isNodeInteractiveWithBoundary(node, (n) => isJsxNode(n))) return true;
397
+ for (const name of collectFreeIdentifiers(node, {
398
+ stopAtJsxBoundary: true,
399
+ })) {
400
+ if (hookTaint.get(name)) return true;
401
+ }
402
+ return false;
403
+ }
404
+
405
+ /**
406
+ * Finds the maximal (highest, smallest-possible) JSX subtrees whose own
407
+ * content requires interactivity — either directly (per isSubtreeInteractive,
408
+ * which folds hooks/handlers/browser globals together with hook-taint free-
409
+ * variable references) — walking top-down and stopping as soon as a node's
410
+ * OWN content (not just a nested child's) explains its interactivity. Sibling
411
+ * subtrees are kept separate by default (Astro-style small islands) — merging
412
+ * happens later if they turn out to share a hook-tainted dependency.
413
+ */
414
+ function findMaximalInteractiveSubtrees(
415
+ rootJsxNode,
416
+ isSubtreeInteractive,
417
+ isNodeInteractiveWithBoundary,
418
+ hookTaint,
419
+ ) {
420
+ const results = [];
421
+ function visit(node) {
422
+ if (!isSubtreeInteractive(node)) return;
423
+ if (hasOwnInteractivity(node, isNodeInteractiveWithBoundary, hookTaint)) {
424
+ results.push(node);
425
+ return;
426
+ }
427
+ const jsxChildren = findImmediateJsxChildren(node);
428
+ const interactiveChildren = jsxChildren.filter((c) =>
429
+ isSubtreeInteractive(c),
430
+ );
431
+ if (interactiveChildren.length === 0) {
432
+ // Shouldn't normally happen (isSubtreeInteractive(node) was true with
433
+ // no own-content cause and no interactive children) — bail
434
+ // conservatively by treating this node as the boundary rather than
435
+ // silently dropping the interactivity signal.
436
+ results.push(node);
437
+ return;
438
+ }
439
+ for (const child of jsxChildren) visit(child);
440
+ }
441
+ visit(rootJsxNode);
442
+ return results;
443
+ }
444
+
445
+ function collectModuleLevelNames(sourceFile, componentFnNode) {
446
+ const names = new Set();
447
+ for (const stmt of sourceFile.statements) {
448
+ if (
449
+ stmt === componentFnNode ||
450
+ (ts.isVariableStatement(stmt) &&
451
+ stmt.declarationList.declarations.includes(componentFnNode))
452
+ )
453
+ continue;
454
+ if (ts.isImportDeclaration(stmt) && stmt.importClause) {
455
+ if (stmt.importClause.name) names.add(stmt.importClause.name.text);
456
+ const nb = stmt.importClause.namedBindings;
457
+ if (nb && ts.isNamedImports(nb))
458
+ nb.elements.forEach((el) =>
459
+ names.add(
460
+ (el.propertyName ?? el.name).text === el.name.text
461
+ ? el.name.text
462
+ : el.name.text,
463
+ ),
464
+ );
465
+ if (nb && ts.isNamespaceImport(nb)) names.add(nb.name.text);
466
+ } else if (ts.isVariableStatement(stmt)) {
467
+ for (const decl of stmt.declarationList.declarations) {
468
+ collectBindingNames(decl.name).forEach((n) => names.add(n));
469
+ }
470
+ } else if (ts.isFunctionDeclaration(stmt) && stmt.name) {
471
+ names.add(stmt.name.text);
472
+ } else if (
473
+ ts.isInterfaceDeclaration(stmt) ||
474
+ ts.isTypeAliasDeclaration(stmt)
475
+ ) {
476
+ names.add(stmt.name.text);
477
+ }
478
+ }
479
+ return names;
480
+ }
481
+
482
+ /**
483
+ * Classifies one extraction candidate's free variables and computes its
484
+ * required relocated-declaration closure. Returns { props, relocatedNames,
485
+ * unresolved } — `unresolved: true` means an identifier couldn't be resolved
486
+ * to a prop, a local declaration, or a module-level name, so the caller must
487
+ * bail conservatively rather than guess.
488
+ */
489
+ function classifyExtraction(
490
+ jsxNodes,
491
+ propNames,
492
+ hookTaint,
493
+ declByName,
494
+ moduleLevelNames,
495
+ ) {
496
+ const props = new Set();
497
+ const relocatedNames = new Set();
498
+ let unresolved = false;
499
+
500
+ const toResolve = [];
501
+ for (const node of jsxNodes)
502
+ for (const n of collectFreeIdentifiers(node)) toResolve.push(n);
503
+ const seen = new Set();
504
+
505
+ while (toResolve.length > 0) {
506
+ const name = toResolve.pop();
507
+ if (seen.has(name)) continue;
508
+ seen.add(name);
509
+
510
+ if (moduleLevelNames.has(name)) continue; // import/module-level — copied wholesale, not a prop
511
+ if (KNOWN_GLOBALS.has(name)) continue; // well-known JS/browser global — needs no resolution
512
+ if (propNames.has(name)) {
513
+ props.add(name);
514
+ continue;
515
+ }
516
+ if (declByName.has(name)) {
517
+ const decl = declByName.get(name);
518
+ if (decl.unsupportedStatement) {
519
+ unresolved = true;
520
+ continue;
521
+ }
522
+ relocatedNames.add(name);
523
+ if (decl.initializer) {
524
+ for (const f of collectFreeIdentifiers(decl.initializer))
525
+ if (!seen.has(f)) toResolve.push(f);
526
+ }
527
+ continue;
528
+ }
529
+ unresolved = true;
530
+ }
531
+
532
+ return { props, relocatedNames, unresolved };
533
+ }
534
+
535
+ /**
536
+ * Full pipeline for one component file: detect candidates, classify, merge
537
+ * siblings that share a hook-tainted dependency, and run the safety gates
538
+ * (reverse-dependency, size-heuristic, unresolved-identifier). Returns
539
+ * `{ success: false, reason }` on any bail-out (leave the component exactly
540
+ * as today — hydrates as one unit if isComponentInteractive says so), or
541
+ * `{ success: true, sourceFile, componentInfo, groups }` where each group is
542
+ * `{ nodes, props, relocatedNames }` — one group per island to generate.
543
+ * Pure/no I/O: callers handle writing files.
544
+ */
545
+ function computeIslandSplit(filePath, sourceText) {
546
+ if (!ts) return { success: false, reason: 'typescript module unavailable' };
547
+
548
+ let sourceFile;
549
+ try {
550
+ sourceFile = ts.createSourceFile(
551
+ filePath,
552
+ sourceText,
553
+ ts.ScriptTarget.Latest,
554
+ true,
555
+ ts.ScriptKind.TSX,
556
+ );
557
+ } catch (e) {
558
+ return { success: false, reason: `parse error: ${e.message}` };
559
+ }
560
+
561
+ const { isNodeInteractive, isNodeInteractiveWithBoundary } =
562
+ createInteractivityChecker(sourceFile, ts);
563
+ if (!isNodeInteractive(sourceFile))
564
+ return { success: false, reason: 'component is not interactive' };
565
+
566
+ // Check if component uses motion animation libraries/wrappers (framer-motion, motion helpers, etc.)
567
+ // Splitting motion-animated components into partial islands tears apart scroll/entrance
568
+ // animation timelines and CSS grid/flex containers. They must hydrate as cohesive islands.
569
+ const usesMotionModule =
570
+ CLIENT_ANIMATION_PACKAGES.some(
571
+ (pkg) =>
572
+ sourceText.includes(`"${pkg}"`) || sourceText.includes(`'${pkg}'`),
573
+ ) ||
574
+ /from\s+['"][^'"]*\/motion\/[^'"]*['"]/.test(sourceText) ||
575
+ /from\s+['"][^'"]*reveal['"]/.test(sourceText);
576
+ if (usesMotionModule) {
577
+ return {
578
+ success: false,
579
+ reason:
580
+ 'component uses client motion animations; component must hydrate as a cohesive island',
581
+ };
582
+ }
583
+
584
+ const componentInfo = findComponentFunction(sourceFile);
585
+ if (!componentInfo || !componentInfo.jsxRoot)
586
+ return {
587
+ success: false,
588
+ reason: 'no component function with a JSX return found',
589
+ };
590
+ if (!componentInfo.fnBody)
591
+ return {
592
+ success: false,
593
+ reason: 'implicit-return arrow components are not supported in v1',
594
+ };
595
+
596
+ const { supported, names: propNames } = collectComponentParamNames(
597
+ componentInfo.fnNode,
598
+ );
599
+ if (!supported)
600
+ return {
601
+ success: false,
602
+ reason:
603
+ 'unsupported parameter shape (v1 requires a single destructured props parameter)',
604
+ };
605
+
606
+ const localDecls = collectLocalDeclarations(
607
+ componentInfo.fnBody,
608
+ componentInfo.returnStatement,
609
+ );
610
+ const { taint, declByName } = computeHookTaint(localDecls, isNodeInteractive);
611
+ const moduleLevelNames = collectModuleLevelNames(
612
+ sourceFile,
613
+ componentInfo.fnNode,
614
+ );
615
+
616
+ function isSubtreeInteractive(node) {
617
+ if (isNodeInteractive(node)) return true;
618
+ for (const name of collectFreeIdentifiers(node))
619
+ if (taint.get(name)) return true;
620
+ return false;
621
+ }
622
+
623
+ const candidates = findMaximalInteractiveSubtrees(
624
+ componentInfo.jsxRoot,
625
+ isSubtreeInteractive,
626
+ isNodeInteractiveWithBoundary,
627
+ taint,
628
+ );
629
+ if (candidates.length === 0)
630
+ return {
631
+ success: false,
632
+ reason: 'no extractable interactive subtree found',
633
+ };
634
+
635
+ let groups = candidates.map((node) => {
636
+ const result = classifyExtraction(
637
+ [node],
638
+ propNames,
639
+ taint,
640
+ declByName,
641
+ moduleLevelNames,
642
+ );
643
+ return {
644
+ nodes: [node],
645
+ props: result.props,
646
+ relocatedNames: result.relocatedNames,
647
+ unresolved: result.unresolved,
648
+ };
649
+ });
650
+
651
+ if (groups.some((g) => g.unresolved)) {
652
+ return {
653
+ success: false,
654
+ reason: 'unresolved free variable in at least one candidate subtree',
655
+ };
656
+ }
657
+
658
+ function collectHookRootStatements(names) {
659
+ const roots = new Set();
660
+ const seen = new Set();
661
+ const stack = [...names];
662
+ while (stack.length) {
663
+ const name = stack.pop();
664
+ if (!name || seen.has(name)) continue;
665
+ seen.add(name);
666
+ const decl = declByName.get(name);
667
+ if (!decl) continue;
668
+ if (decl.initializer && isNodeInteractive(decl.initializer)) {
669
+ roots.add(decl.statement || decl.node);
670
+ }
671
+ if (decl.initializer) {
672
+ for (const f of collectFreeIdentifiers(decl.initializer)) stack.push(f);
673
+ }
674
+ }
675
+ return roots;
676
+ }
677
+
678
+ function nodesAreSiblings(nodes) {
679
+ if (!nodes || nodes.length <= 1) return true;
680
+ const parent = nodes[0].parent;
681
+ if (!parent) return false;
682
+ return nodes.every((n) => n.parent === parent);
683
+ }
684
+
685
+ // Merge groups sharing a relocated hook-tainted dependency — extracting
686
+ // both separately would duplicate the hook call (double-fetch/double-render).
687
+ let merged = true;
688
+ while (merged) {
689
+ merged = false;
690
+ outer: for (let i = 0; i < groups.length; i++) {
691
+ for (let j = i + 1; j < groups.length; j++) {
692
+ const shares = [...groups[i].relocatedNames].some((n) =>
693
+ groups[j].relocatedNames.has(n),
694
+ );
695
+ const iRoots = collectHookRootStatements(groups[i].relocatedNames);
696
+ const jRoots = collectHookRootStatements(groups[j].relocatedNames);
697
+ const sharesHookRoot = [...iRoots].some((r) => jRoots.has(r));
698
+ if (shares || sharesHookRoot) {
699
+ const combinedNodes = [...groups[i].nodes, ...groups[j].nodes];
700
+ const result = classifyExtraction(
701
+ combinedNodes,
702
+ propNames,
703
+ taint,
704
+ declByName,
705
+ moduleLevelNames,
706
+ );
707
+ if (result.unresolved)
708
+ return {
709
+ success: false,
710
+ reason:
711
+ 'merging sibling islands produced an unresolved free variable',
712
+ };
713
+ groups.splice(j, 1);
714
+ groups.splice(i, 1, {
715
+ nodes: combinedNodes,
716
+ props: result.props,
717
+ relocatedNames: result.relocatedNames,
718
+ unresolved: false,
719
+ });
720
+ merged = true;
721
+ break outer;
722
+ }
723
+ }
724
+ }
725
+ }
726
+
727
+ // Splitting into multiple separate islands fragments the component tree and
728
+ // injects multiple disjoint hydration boundaries across grid/flex layouts.
729
+ // When a component has multiple interactive/motion regions, it must hydrate
730
+ // as a single cohesive unit to preserve layout and animation synchronization.
731
+ if (groups.length > 1) {
732
+ return {
733
+ success: false,
734
+ reason:
735
+ 'multiple disjoint interactive subtrees; component must hydrate as a cohesive island',
736
+ };
737
+ }
738
+
739
+ // Non-sibling extractions get concatenated into a fragment. That tears
740
+ // the original layout apart (two cells of a grid becoming one fragment).
741
+ for (const g of groups) {
742
+ if (!nodesAreSiblings(g.nodes)) {
743
+ return {
744
+ success: false,
745
+ reason:
746
+ 'extracted nodes are not siblings; splitting would break layout',
747
+ };
748
+ }
749
+ }
750
+
751
+ // No benefit to splitting if an island would swallow the large majority of
752
+ // the component's own JSX.
753
+ const totalJsxLength =
754
+ componentInfo.jsxRoot.getEnd() - componentInfo.jsxRoot.getStart(sourceFile);
755
+ for (const g of groups) {
756
+ const groupLength = g.nodes.reduce(
757
+ (sum, n) => sum + (n.getEnd() - n.getStart(sourceFile)),
758
+ 0,
759
+ );
760
+ if (totalJsxLength > 0 && groupLength / totalJsxLength > 0.9) {
761
+ return {
762
+ success: false,
763
+ reason:
764
+ 'extraction candidate would contain the large majority of the component; no benefit to splitting',
765
+ };
766
+ }
767
+ }
768
+
769
+ // Reverse-dependency check: nothing OUTSIDE the union of all extraction
770
+ // targets (remaining JSX + surviving local declarations) may reference a
771
+ // relocated declaration — that would be shared state across islands, which
772
+ // v1 does not support (bail to today's manual-split status quo).
773
+ const allRelocatedNames = new Set();
774
+ const allExtractedNodes = new Set();
775
+ for (const g of groups) {
776
+ for (const n of g.relocatedNames) allRelocatedNames.add(n);
777
+ for (const node of g.nodes) allExtractedNodes.add(node);
778
+ }
779
+
780
+ const remainingIsInteractive = isNodeInteractiveWithBoundary(
781
+ componentInfo.jsxRoot,
782
+ (n) => allExtractedNodes.has(n),
783
+ );
784
+ if (remainingIsInteractive) {
785
+ return {
786
+ success: false,
787
+ reason:
788
+ 'surviving JSX still contains interactive or motion elements; cannot safely split',
789
+ };
790
+ }
791
+
792
+ const remainingJsxFree = collectFreeIdentifiers(componentInfo.jsxRoot, {
793
+ excludeNodes: allExtractedNodes,
794
+ });
795
+ for (const name of remainingJsxFree) {
796
+ if (allRelocatedNames.has(name)) {
797
+ return {
798
+ success: false,
799
+ reason: `"${name}" is still referenced outside the extracted subtree(s) (shared state) — cannot safely split`,
800
+ };
801
+ }
802
+ }
803
+ for (const decl of localDecls) {
804
+ if (decl.names.some((n) => allRelocatedNames.has(n))) continue; // this decl is itself being relocated
805
+ if (decl.unsupportedStatement) {
806
+ // A bare statement before return (e.g. a standalone `useEffect(...)`
807
+ // call with no assignment) declares no names, so it's invisible to the
808
+ // decl.names check above — but it can still read relocated bindings
809
+ // (e.g. an effect that closes over a ref/setter used only inside the
810
+ // extracted JSX). Left in place, it would reference names that no
811
+ // longer exist in the parent's scope. Must be checked like any other
812
+ // surviving statement, not skipped.
813
+ for (const name of collectFreeIdentifiers(decl.node)) {
814
+ if (allRelocatedNames.has(name)) {
815
+ return {
816
+ success: false,
817
+ reason: `"${name}" is still referenced by a surviving statement (e.g. an effect) — cannot safely split`,
818
+ };
819
+ }
820
+ }
821
+ continue;
822
+ }
823
+ if (!decl.initializer) continue;
824
+ for (const name of collectFreeIdentifiers(decl.initializer)) {
825
+ if (allRelocatedNames.has(name)) {
826
+ return {
827
+ success: false,
828
+ reason: `"${name}" is still referenced by a surviving local declaration — cannot safely split`,
829
+ };
830
+ }
831
+ }
832
+ }
833
+
834
+ // A statement can bind multiple names in one `const {a, b} = x()`. If only
835
+ // SOME of its names are being relocated while others survive, removing the
836
+ // whole statement would silently delete the surviving names' declarations
837
+ // too — bail rather than attempt partial-destructuring codegen (v1 scope).
838
+ const statementsToRemove = new Set();
839
+ for (const name of allRelocatedNames) {
840
+ const decl = declByName.get(name);
841
+ if (decl) statementsToRemove.add(decl.statement);
842
+ }
843
+ for (const stmt of statementsToRemove) {
844
+ const decl = localDecls.find((d) => d.statement === stmt);
845
+ if (!decl) continue;
846
+ if (decl.names.some((n) => !allRelocatedNames.has(n))) {
847
+ return {
848
+ success: false,
849
+ reason:
850
+ 'a relocated declaration shares a binding statement with a name that must stay in the parent — cannot safely split',
851
+ };
852
+ }
853
+ }
854
+
855
+ return {
856
+ success: true,
857
+ sourceFile,
858
+ componentInfo,
859
+ groups,
860
+ statementsToRemove,
861
+ localDecls,
862
+ };
863
+ }
864
+
865
+ function deriveIslandName(componentName, index) {
866
+ return `${componentName}Island${index + 1}`;
867
+ }
868
+
869
+ const GENERATED_BANNER = (componentName) =>
870
+ `/**\n * AUTO-GENERATED BY FORGEWP. DO NOT EDIT.\n * Extracted interactive island from ${componentName} by the auto-split\n * hydration compiler pass (packages/compiler/lib/hydration/island-split.js).\n */\n`;
871
+
872
+ /**
873
+ * Builds the source text for one generated island component. Everything
874
+ * copied from the original file — imports, relocated declaration statements,
875
+ * extracted JSX — is text-sliced verbatim from the original source, never
876
+ * re-printed via an AST printer (Correction 2: an AST-reprinted first tag
877
+ * would break blocks/index.js's regex-based padding-token detection
878
+ * elsewhere in the pipeline).
879
+ */
880
+ /**
881
+ * The generated island file lives at `.forgewp-islands/<ComponentName>/`,
882
+ * two directory levels deeper than the original component — so a relative
883
+ * import specifier (`./x`, `../x`) copied verbatim would resolve to the
884
+ * wrong location. Surgically rewrites just the specifier substring (text-
885
+ * slice philosophy, not an AST reprint) by prepending `../../`; bare
886
+ * package specifiers (`react`, `lucide-react`) are untouched.
887
+ */
888
+ function rewriteImportForIslandDepth(importDecl, sourceFile, sourceText) {
889
+ const raw = sourceText.slice(
890
+ importDecl.getStart(sourceFile),
891
+ importDecl.getEnd(),
892
+ );
893
+ const spec = importDecl.moduleSpecifier;
894
+ if (!spec || !ts.isStringLiteral(spec) || !spec.text.startsWith('.'))
895
+ return raw;
896
+ const specStart = spec.getStart(sourceFile) - importDecl.getStart(sourceFile);
897
+ const specEnd = spec.getEnd() - importDecl.getStart(sourceFile);
898
+ const quote = raw[specStart];
899
+ return (
900
+ raw.slice(0, specStart) +
901
+ `${quote}../../${spec.text}${quote}` +
902
+ raw.slice(specEnd)
903
+ );
904
+ }
905
+
906
+ function buildIslandSource(
907
+ sourceFile,
908
+ sourceText,
909
+ group,
910
+ localDecls,
911
+ componentInfo,
912
+ islandName,
913
+ ) {
914
+ const declByName = new Map();
915
+ for (const d of localDecls) for (const n of d.names) declByName.set(n, d);
916
+
917
+ const stmtSet = new Set();
918
+ for (const name of group.relocatedNames) {
919
+ const decl = declByName.get(name);
920
+ if (decl) stmtSet.add(decl.statement);
921
+ }
922
+ const stmts = [...stmtSet].sort(
923
+ (a, b) => a.getStart(sourceFile) - b.getStart(sourceFile),
924
+ );
925
+ const bodyLines = stmts.map((s) =>
926
+ sourceText.slice(s.getStart(sourceFile), s.getEnd()),
927
+ );
928
+
929
+ const jsxParts = group.nodes
930
+ .slice()
931
+ .sort((a, b) => a.getStart(sourceFile) - b.getStart(sourceFile))
932
+ .map((n) => sourceText.slice(n.getStart(sourceFile), n.getEnd()));
933
+ const returnExpr =
934
+ jsxParts.length === 1 ? jsxParts[0] : `<>\n${jsxParts.join('\n')}\n</>`;
935
+
936
+ const propsList = [...group.props];
937
+ const propsInterfaceName = `${islandName}Props`;
938
+ const propsInterface =
939
+ propsList.length > 0
940
+ ? `export interface ${propsInterfaceName} {\n${propsList.map((p) => ` ${p}?: any;`).join('\n')}\n}\n\n`
941
+ : '';
942
+ const propsParam =
943
+ propsList.length > 0
944
+ ? `{ ${propsList.join(', ')} }: ${propsInterfaceName}`
945
+ : '';
946
+
947
+ // Copy every top-level import verbatim rather than selectively trimming —
948
+ // unused imports cost nothing here (this file is compiler-generated, never
949
+ // hand-edited) and avoids a whole extra class of "did I copy the right
950
+ // subset" bugs. Relative specifiers DO need adjusting though: the island
951
+ // lands two directories deeper than the original file (.forgewp-islands/
952
+ // <ComponentName>/), so a relative import copied byte-for-byte would
953
+ // resolve to the wrong place (or fail to resolve at all).
954
+ const importLines = sourceFile.statements
955
+ .filter((s) => ts.isImportDeclaration(s))
956
+ .map((s) => rewriteImportForIslandDepth(s, sourceFile, sourceText))
957
+ .join('\n');
958
+
959
+ // Module-level consts / helpers / types the island JSX closes over.
960
+ // classifyExtraction treats these as "copied wholesale" — so copy them,
961
+ // or the island throws ReferenceError on hydrate.
962
+ const moduleLevelLines = sourceFile.statements
963
+ .filter((s) => {
964
+ if (
965
+ ts.isImportDeclaration(s) ||
966
+ ts.isExportDeclaration(s) ||
967
+ ts.isExportAssignment(s)
968
+ )
969
+ return false;
970
+ if (s === componentInfo.fnNode) return false;
971
+ if (
972
+ ts.isFunctionDeclaration(s) &&
973
+ s.name &&
974
+ s.name.text === componentInfo.componentName
975
+ )
976
+ return false;
977
+ if (
978
+ ts.isVariableStatement(s) &&
979
+ s.declarationList.declarations.some(
980
+ (d) => d.initializer === componentInfo.fnNode,
981
+ )
982
+ ) {
983
+ return false;
984
+ }
985
+ return true;
986
+ })
987
+ .map((s) => sourceText.slice(s.getStart(sourceFile), s.getEnd()))
988
+ .join('\n\n');
989
+
990
+ return (
991
+ `${GENERATED_BANNER(componentInfo.componentName)}${importLines}\n\n${moduleLevelLines ? moduleLevelLines + '\n\n' : ''}${propsInterface}` +
992
+ `export function ${islandName}(${propsParam}) {\n${bodyLines.join('\n')}\n return (\n ${returnExpr}\n );\n}\n\n` +
993
+ `export default ${islandName};\n`
994
+ );
995
+ }
996
+
997
+ /**
998
+ * Text-splices the shell: removes each relocated declaration statement and
999
+ * replaces each extraction target with a plain `<IslandName {...props} />`
1000
+ * JSX reference (for a merged group, only the first node's position gets the
1001
+ * replacement tag; the rest are simply removed — their content moved into
1002
+ * the same island). All edits applied in descending start-offset order so
1003
+ * earlier edits never shift the positions of later ones. Everything outside
1004
+ * an edited range — crucially the block's own padding-bearing root tag — is
1005
+ * untouched byte-for-byte.
1006
+ */
1007
+ function buildShellSource(sourceFile, sourceText, splitResult, islandNames) {
1008
+ const { groups, localDecls } = splitResult;
1009
+ const declByName = new Map();
1010
+ for (const d of localDecls) for (const n of d.names) declByName.set(n, d);
1011
+
1012
+ const edits = [];
1013
+
1014
+ groups.forEach((g, i) => {
1015
+ const islandName = islandNames[i];
1016
+ const propsAttrs = [...g.props].map((p) => ` ${p}={${p}}`).join('');
1017
+ const replacementTag = `<${islandName}${propsAttrs} />`;
1018
+ const sortedNodes = g.nodes
1019
+ .slice()
1020
+ .sort((a, b) => a.getStart(sourceFile) - b.getStart(sourceFile));
1021
+ sortedNodes.forEach((node, idx) => {
1022
+ edits.push({
1023
+ start: node.getStart(sourceFile),
1024
+ end: node.getEnd(),
1025
+ text: idx === 0 ? replacementTag : '',
1026
+ });
1027
+ });
1028
+
1029
+ const stmtSet = new Set();
1030
+ for (const name of g.relocatedNames) {
1031
+ const decl = declByName.get(name);
1032
+ if (decl) stmtSet.add(decl.statement);
1033
+ }
1034
+ for (const stmt of stmtSet) {
1035
+ edits.push({
1036
+ start: stmt.getStart(sourceFile),
1037
+ end: stmt.getEnd(),
1038
+ text: '',
1039
+ });
1040
+ }
1041
+ });
1042
+
1043
+ edits.sort((a, b) => b.start - a.start);
1044
+
1045
+ let result = sourceText;
1046
+ for (const edit of edits) {
1047
+ result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
1048
+ }
1049
+
1050
+ const importLines = islandNames
1051
+ .map(
1052
+ (name) =>
1053
+ `import { ${name} } from './${GENERATED_ISLANDS_DIRNAME}/${splitResult.componentInfo.componentName}/${name}';`,
1054
+ )
1055
+ .join('\n');
1056
+ return `${importLines}\n${result}`;
1057
+ }
1058
+
1059
+ /**
1060
+ * Full per-themeRoot pass: scans every candidate component file (same roots
1061
+ * islands-scanner.js's Smart Discovery already uses), computes an island
1062
+ * split for each, and for every success: writes the generated island file(s)
1063
+ * to disk (a real file is required — islands-scanner.js's Smart Discovery
1064
+ * and Vite's Rollup entry resolution both need one, and compileBlocks reads
1065
+ * component source via raw fs, independent of Vite) and registers the
1066
+ * shell's rewritten source as a content override for the ORIGINAL file's
1067
+ * absolute path — the dev's own file on disk is never modified; consumers
1068
+ * (compileBlocks, the Vite transform) look up the override instead of
1069
+ * reading the file verbatim.
1070
+ *
1071
+ * Idempotent-ish: recomputes on every call rather than caching across calls,
1072
+ * since these files are small and this only runs at build/export time, not
1073
+ * per-request. Errors on any single file are caught and logged, never
1074
+ * propagated — one bad file must not abort the whole scan.
1075
+ *
1076
+ * This runs from four separate integration points in one `forgewp export`
1077
+ * (vite.config.ts's config-load-time getHydrationRollupInputs call, the Vite
1078
+ * plugin's buildStart, compileBlocks, and export-theme.js's pre-build step —
1079
+ * each needs its own fresh scan since they run at genuinely different times
1080
+ * relative to Vite's build lifecycle). Without deduping, the same bail-out
1081
+ * reasons would print once per integration point per build. bailWarnedOnce
1082
+ * tracks "have we already told the user about this exact file+reason,"
1083
+ * scoped to the process, so each is printed only once no matter how many of
1084
+ * the four call sites trigger it. Full per-file detail is behind
1085
+ * FORGEWP_VERBOSE=1; the default is a single summary line so a clean build
1086
+ * with (say) 17 non-splittable components doesn't bury the real output.
1087
+ *
1088
+ * @returns {number} count of components successfully auto-split.
1089
+ */
1090
+ const bailWarnedOnce = new Set();
1091
+ let tsUnavailableWarned = false;
1092
+
1093
+ // Reasons that mean "there was nothing to gain here" rather than "we found
1094
+ // a real splitting opportunity but had to play it safe" — a component that
1095
+ // is interactive from top to bottom (e.g. Navbar) or where the only
1096
+ // candidate island would swallow the whole component isn't a missed
1097
+ // opportunity, it's just not shaped for this pass. Not worth reporting even
1098
+ // in verbose mode; only the genuine safety-gate bail-outs are.
1099
+ const NON_ACTIONABLE_REASONS = [
1100
+ 'component is not interactive',
1101
+ 'no extractable interactive subtree found',
1102
+ 'extraction candidate would contain the large majority of the component; no benefit to splitting',
1103
+ ];
1104
+
1105
+ function splitInteractiveIslands(themeRoot) {
1106
+ clearContentOverrides();
1107
+
1108
+ if (!ts) {
1109
+ if (!tsUnavailableWarned) {
1110
+ tsUnavailableWarned = true;
1111
+ console.warn(
1112
+ '[ForgeWP Auto-Island-Split] typescript module unavailable — skipping auto-split for this project (components will hydrate as-is, same as before this pass existed).',
1113
+ );
1114
+ }
1115
+ return 0;
1116
+ }
1117
+
1118
+ const files = collectCandidateFiles(themeRoot);
1119
+ let splitCount = 0;
1120
+ const newBailouts = [];
1121
+
1122
+ for (const filePath of files) {
1123
+ let content;
1124
+ try {
1125
+ content = readFileSync(filePath, 'utf8');
1126
+ } catch {
1127
+ continue;
1128
+ }
1129
+
1130
+ let result;
1131
+ try {
1132
+ result = computeIslandSplit(filePath, content);
1133
+ } catch (err) {
1134
+ console.warn(
1135
+ `[ForgeWP Auto-Island-Split] Error analyzing ${filePath}:`,
1136
+ err.message,
1137
+ );
1138
+ continue;
1139
+ }
1140
+
1141
+ if (!result.success) {
1142
+ if (result.reason && !NON_ACTIONABLE_REASONS.includes(result.reason)) {
1143
+ const relPath = path.relative(themeRoot, filePath);
1144
+ const key = `${relPath}::${result.reason}`;
1145
+ if (!bailWarnedOnce.has(key)) {
1146
+ bailWarnedOnce.add(key);
1147
+ newBailouts.push({ relPath, reason: result.reason });
1148
+ }
1149
+ }
1150
+ continue;
1151
+ }
1152
+
1153
+ try {
1154
+ const islandNames = result.groups.map((g, i) =>
1155
+ deriveIslandName(result.componentInfo.componentName, i),
1156
+ );
1157
+ const islandDir = path.join(
1158
+ path.dirname(filePath),
1159
+ GENERATED_ISLANDS_DIRNAME,
1160
+ result.componentInfo.componentName,
1161
+ );
1162
+ mkdirSync(islandDir, { recursive: true });
1163
+
1164
+ result.groups.forEach((g, i) => {
1165
+ const islandCode = buildIslandSource(
1166
+ result.sourceFile,
1167
+ content,
1168
+ g,
1169
+ result.localDecls,
1170
+ result.componentInfo,
1171
+ islandNames[i],
1172
+ );
1173
+ const islandPath = path.join(islandDir, `${islandNames[i]}.tsx`);
1174
+ const existing = existsSync(islandPath)
1175
+ ? readFileSync(islandPath, 'utf8')
1176
+ : null;
1177
+ if (existing !== islandCode) {
1178
+ writeFileSync(islandPath, islandCode, 'utf8');
1179
+ }
1180
+ });
1181
+
1182
+ const shellCode = buildShellSource(
1183
+ result.sourceFile,
1184
+ content,
1185
+ result,
1186
+ islandNames,
1187
+ );
1188
+ setContentOverride(filePath, shellCode);
1189
+ splitCount++;
1190
+ } catch (err) {
1191
+ console.warn(
1192
+ `[ForgeWP Auto-Island-Split] Error generating split output for ${filePath}:`,
1193
+ err.message,
1194
+ );
1195
+ }
1196
+ }
1197
+
1198
+ if (newBailouts.length > 0) {
1199
+ if (process.env.FORGEWP_VERBOSE) {
1200
+ for (const { relPath, reason } of newBailouts) {
1201
+ console.warn(
1202
+ `[ForgeWP Auto-Island-Split] Could not auto-split ${relPath}: ${reason}. ` +
1203
+ `Consider extracting the interactive part into its own component by hand (see HeroSearchBoard.tsx / HeroSpotlight.tsx for the pattern).`,
1204
+ );
1205
+ }
1206
+ } else if (process.env.FORGEWP_VERBOSE === '1') {
1207
+ console.warn(
1208
+ `[ForgeWP Auto-Island-Split] ${newBailouts.length} component(s) could not be auto-split (they hydrate as-is, same as before this pass existed) — set FORGEWP_VERBOSE=1 for the per-file reasons.`,
1209
+ );
1210
+ }
1211
+ }
1212
+
1213
+ return splitCount;
1214
+ }
1215
+
1216
+ export {
1217
+ computeIslandSplit,
1218
+ collectCandidateFiles,
1219
+ findComponentFunction,
1220
+ collectComponentParamNames,
1221
+ collectLocalDeclarations,
1222
+ collectFreeIdentifiers,
1223
+ computeHookTaint,
1224
+ findMaximalInteractiveSubtrees,
1225
+ collectModuleLevelNames,
1226
+ classifyExtraction,
1227
+ deriveIslandName,
1228
+ buildIslandSource,
1229
+ buildShellSource,
1230
+ splitInteractiveIslands,
1231
+ };