@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,951 @@
1
+ import { readFileSync, existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+
5
+ /**
6
+ * originalAbsolutePath -> rewritten source text override, populated by
7
+ * island-split.js's splitInteractiveIslands() when it auto-splits a mixed
8
+ * static/interactive component into a static shell + extracted islands.
9
+ * Defined here (not in island-split.js, which imports FROM this file) to
10
+ * avoid a circular import, and so every existing reader of a component's
11
+ * source — isComponentInteractive, and anything else that calls
12
+ * readComponentSource — transparently sees the split shell instead of the
13
+ * dev's original, still-fully-interactive file content, with zero changes
14
+ * needed at each individual call site.
15
+ */
16
+ const contentOverrides = new Map();
17
+
18
+ // Callers normalize paths inconsistently (Vite's transform hook forward-
19
+ // slash-normalizes ids; node:path.join uses the native separator, backslash
20
+ // on Windows) — key the override cache by a canonical forward-slash form so
21
+ // a lookup from ANY caller reliably hits an override set by any OTHER caller.
22
+ function normalizePath(filePath) {
23
+ return filePath.replace(/\\/g, '/');
24
+ }
25
+
26
+ export function setContentOverride(filePath, content) {
27
+ contentOverrides.set(normalizePath(filePath), content);
28
+ }
29
+
30
+ export function clearContentOverrides() {
31
+ contentOverrides.clear();
32
+ }
33
+
34
+ /**
35
+ * True only when THIS path has an actual registered override — never infer
36
+ * one from "a fresh disk read differs from caller-supplied content." A
37
+ * caller (e.g. Vite's transform hook) may already hold content that's been
38
+ * preprocessed by an earlier plugin in the chain; diffing that against a raw
39
+ * readFileSync would misfire on files that were never split at all (any
40
+ * legitimate upstream transformation looks identical to "there must be an
41
+ * override" under a naive diff) and silently revert their code back to the
42
+ * unprocessed original, later failing Rollup's plain-JS import analysis.
43
+ */
44
+ export function hasContentOverride(filePath) {
45
+ return contentOverrides.has(normalizePath(filePath));
46
+ }
47
+
48
+ export function readComponentSource(filePath) {
49
+ const key = normalizePath(filePath);
50
+ if (contentOverrides.has(key)) return contentOverrides.get(key);
51
+ return readFileSync(filePath, 'utf8');
52
+ }
53
+
54
+ /**
55
+ * Regex-fallback-only WpEditable stripper (used when the `ts` module isn't
56
+ * available at all — the AST path uses isAttributeOfWpEditable instead,
57
+ * which doesn't have this problem). A naive `<WpEditable\b[^>]*\/>`-style
58
+ * regex breaks the instant a WpEditable's onChange contains a TypeScript
59
+ * generic cast like `as Partial<Props>` — that `>` ends the `[^>]*` match
60
+ * early, so the tag (and its onChange) never actually gets stripped. This
61
+ * tracks brace depth so a `>` inside a `{...}` expression doesn't count.
62
+ */
63
+ function stripWpEditableBlocksNaive(content) {
64
+ let result = '';
65
+ let pos = 0;
66
+ while (true) {
67
+ const idx = content.indexOf('<WpEditable', pos);
68
+ if (idx === -1) {
69
+ result += content.slice(pos);
70
+ break;
71
+ }
72
+ const afterName = content[idx + '<WpEditable'.length];
73
+ if (afterName !== undefined && /[a-zA-Z0-9_]/.test(afterName)) {
74
+ result += content.slice(pos, idx + '<WpEditable'.length);
75
+ pos = idx + '<WpEditable'.length;
76
+ continue;
77
+ }
78
+ result += content.slice(pos, idx);
79
+
80
+ let braceDepth = 0;
81
+ let inQuote = null;
82
+ let tagEnd = -1;
83
+ for (let i = idx; i < content.length; i++) {
84
+ const c = content[i];
85
+ if (inQuote) {
86
+ if (c === inQuote) inQuote = null;
87
+ continue;
88
+ }
89
+ if (c === "'" || c === '"' || c === '`') {
90
+ inQuote = c;
91
+ } else if (c === '{') {
92
+ braceDepth++;
93
+ } else if (c === '}') {
94
+ if (braceDepth > 0) braceDepth--;
95
+ } else if (c === '>' && braceDepth === 0) {
96
+ tagEnd = i;
97
+ break;
98
+ }
99
+ }
100
+ if (tagEnd === -1) {
101
+ result += content.slice(idx);
102
+ break;
103
+ }
104
+ const isSelfClosing = content[tagEnd - 1] === '/';
105
+ if (isSelfClosing) {
106
+ pos = tagEnd + 1;
107
+ } else {
108
+ const closeIdx = content.indexOf('</WpEditable>', tagEnd + 1);
109
+ pos = closeIdx === -1 ? tagEnd + 1 : closeIdx + '</WpEditable>'.length;
110
+ }
111
+ }
112
+ return result;
113
+ }
114
+
115
+ const require = createRequire(import.meta.url);
116
+ export let ts = null;
117
+ try {
118
+ ts = require('typescript');
119
+ } catch (e) {
120
+ let currentDir = process.cwd();
121
+ while (true) {
122
+ const tsPath = path.join(currentDir, 'node_modules', 'typescript');
123
+ if (existsSync(tsPath)) {
124
+ try {
125
+ const rootRequire = createRequire(
126
+ path.join(currentDir, 'package.json'),
127
+ );
128
+ ts = rootRequire('typescript');
129
+ break;
130
+ } catch (e2) {}
131
+ }
132
+ const parentDir = path.dirname(currentDir);
133
+ if (parentDir === currentDir) break;
134
+ currentDir = parentDir;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * True when `attrNode` (a JsxAttribute, e.g. `onChange={...}`) belongs to a
140
+ * `<WpEditable ...>` / `<WpEditable ... />` tag specifically.
141
+ */
142
+ export function isAttributeOfWpEditable(attrNode, tsModule) {
143
+ let n = attrNode.parent;
144
+ while (
145
+ n &&
146
+ n.kind !== tsModule.SyntaxKind.JsxOpeningElement &&
147
+ n.kind !== tsModule.SyntaxKind.JsxSelfClosingElement
148
+ ) {
149
+ n = n.parent;
150
+ }
151
+ if (!n) return false;
152
+ const tagName = n.tagName;
153
+ return (
154
+ tagName &&
155
+ tagName.kind === tsModule.SyntaxKind.Identifier &&
156
+ tagName.text === 'WpEditable'
157
+ );
158
+ }
159
+
160
+ // Ignore server-safe static queries and translation hooks.
161
+ // NOTE: useWpQuery is deliberately NOT included here. Unlike the hooks below (which
162
+ // read from context/globals available synchronously at SSR time), useWpQuery's
163
+ // production implementation always returns `{ posts: [], loading: true }` during the
164
+ // compile-time SSR pass (see wordpress.tsx's `_forgeWpCompileTime` branch) — it
165
+ // fundamentally requires client-side hydration to ever resolve real data. Treating it
166
+ // as "server-safe" leaves any component that uses only useWpQuery (no other
167
+ // hooks/handlers) permanently stuck on its SSR-baked loading skeleton on the live
168
+ // site, since it never gets a <Hydrate> boundary to mount and re-fetch client-side.
169
+ export const SERVER_SAFE_HOOKS = [
170
+ 'useWpTitle',
171
+ 'useWpExcerpt',
172
+ 'useWpContent',
173
+ 'useWpFeaturedImage',
174
+ 'useWpAuthor',
175
+ 'useWpModifiedDate',
176
+ 'useWpCustomField',
177
+ 'useWpI18n',
178
+ 'useWpThemeUri',
179
+ 'useWpPageLink',
180
+ 'useWpOption',
181
+ 'useWpThemeMod',
182
+ 'useWpMeta',
183
+ 'useWpLanguage',
184
+ 'useWpMenu',
185
+ 'useReducedMotion',
186
+ 'useId',
187
+ 'useMemo',
188
+ 'useCallback',
189
+ 'useTransition',
190
+ 'useDeferredValue',
191
+ 'useDebugValue',
192
+ 'useInsertionEffect',
193
+ ];
194
+
195
+ /**
196
+ * Universal catalog of popular animation, 3D, canvas, and viewport motion libraries.
197
+ * Any component importing from these packages or using their client directives
198
+ * is automatically recognized by Smart Discovery as requiring client execution.
199
+ */
200
+ export const CLIENT_ANIMATION_PACKAGES = [
201
+ 'framer-motion',
202
+ 'motion',
203
+ 'motion/react',
204
+ '@gsap/react',
205
+ 'gsap',
206
+ 'gsap/ScrollTrigger',
207
+ 'gsap/ScrollSmoother',
208
+ 'gsap/Flip',
209
+ 'gsap/SplitText',
210
+ '@react-spring/web',
211
+ '@react-spring/core',
212
+ 'react-spring',
213
+ 'lenis',
214
+ '@studio-freight/lenis',
215
+ 'lenis/react',
216
+ 'lottie-react',
217
+ '@lottiefiles/dotlottie-react',
218
+ '@rive-app/react-canvas',
219
+ 'rive-react',
220
+ '@react-three/fiber',
221
+ '@react-three/drei',
222
+ 'three',
223
+ '@splinetool/react-spline',
224
+ '@splinetool/runtime',
225
+ '@formkit/auto-animate',
226
+ 'swiper',
227
+ 'swiper/react',
228
+ 'embla-carousel-react',
229
+ 'keen-slider/react',
230
+ 'aos',
231
+ 'locomotive-scroll',
232
+ 'animejs',
233
+ 'kute.js',
234
+ ];
235
+
236
+ export const CLIENT_ANIMATION_DIRECTIVES_REGEX =
237
+ /^(whileInView|whileHover|whileTap|whileDrag|whileFocus|animate|exit|layoutId|drag|dragConstraints|scrollTrigger|data-aos|data-scroll|stagger|variants)/;
238
+
239
+ export const CLIENT_ANIMATION_TAGS = new Set([
240
+ 'AnimatePresence',
241
+ 'LazyMotion',
242
+ 'Canvas',
243
+ 'Spline',
244
+ 'Lottie',
245
+ 'DotLottieReact',
246
+ 'Rive',
247
+ 'Swiper',
248
+ 'SwiperSlide',
249
+ 'ReactLenis',
250
+ 'Lenis',
251
+ ]);
252
+
253
+ /**
254
+ * Builds a reusable, per-node interactivity checker for a parsed source file:
255
+ * resolves local `use*` wrapper functions once (Pass 1), then returns a
256
+ * `isNodeInteractive(node)` function that can be called on the whole source
257
+ * file OR on any individual subtree (e.g. a single JSX element) — the same
258
+ * rule set either way. Factored out of isComponentInteractive so
259
+ * hydration/island-split.js can apply the identical rules per-JSX-subtree
260
+ * instead of only whole-component.
261
+ *
262
+ * @param {object} sourceFile - a ts.SourceFile already parsed from the component's text.
263
+ * @param {object} tsModule - the `typescript` module (pass the same `ts` this file resolved).
264
+ * @returns {{ isNodeInteractive: (node: object) => boolean, localHookInteractivity: Map<string, boolean> }}
265
+ */
266
+ export function createInteractivityChecker(
267
+ sourceFile,
268
+ tsModule,
269
+ { ignoreMotionTags = false } = {},
270
+ ) {
271
+ const ts = tsModule;
272
+
273
+ const localHookInteractivity = new Map();
274
+
275
+ function checkInteractivity(rootNode, resolvingLocalHooks, stopPredicate) {
276
+ let interactive = false;
277
+
278
+ function checkNode(node) {
279
+ if (interactive) return;
280
+ if (stopPredicate && node !== rootNode && stopPredicate(node)) return;
281
+
282
+ // 1. Check for Hooks: CallExpression where the expression is an Identifier
283
+ // starting with "use" (`useState(...)`) OR a `React.useX(...)` property
284
+ // access (`React.useState(...)`, `React.useEffect(...)`)
285
+ if (node.kind === ts.SyntaxKind.CallExpression) {
286
+ const expression = node.expression;
287
+ let hookName = null;
288
+ if (expression.kind === ts.SyntaxKind.Identifier) {
289
+ hookName = expression.text;
290
+ } else if (
291
+ expression.kind === ts.SyntaxKind.PropertyAccessExpression &&
292
+ expression.expression.kind === ts.SyntaxKind.Identifier &&
293
+ expression.expression.text === 'React'
294
+ ) {
295
+ hookName = expression.name.text;
296
+ }
297
+ if (hookName !== null) {
298
+ if (hookName.startsWith('use')) {
299
+ if (SERVER_SAFE_HOOKS.includes(hookName)) {
300
+ // safe, fall through to scan children
301
+ } else if (
302
+ !resolvingLocalHooks &&
303
+ localHookInteractivity.has(hookName)
304
+ ) {
305
+ if (localHookInteractivity.get(hookName)) {
306
+ interactive = true;
307
+ return;
308
+ }
309
+ } else {
310
+ interactive = true;
311
+ return;
312
+ }
313
+ }
314
+ }
315
+ }
316
+
317
+ // 2. Check for inline event handlers & client animation directives (whileInView, whileHover, etc.)
318
+ if (node.kind === ts.SyntaxKind.JsxAttribute) {
319
+ const name = node.name;
320
+ if (name.kind === ts.SyntaxKind.Identifier) {
321
+ const attrName = name.text;
322
+ if (/^on[A-Z]/.test(attrName) && !isAttributeOfWpEditable(node, ts)) {
323
+ interactive = true;
324
+ return;
325
+ }
326
+ const openingElement = node.parent?.parent;
327
+ const openingTag = openingElement?.tagName;
328
+ const isMotionAttribute =
329
+ ignoreMotionTags &&
330
+ (openingElement?.kind === ts.SyntaxKind.JsxOpeningElement ||
331
+ openingElement?.kind === ts.SyntaxKind.JsxSelfClosingElement) &&
332
+ openingTag?.kind === ts.SyntaxKind.PropertyAccessExpression &&
333
+ openingTag.expression.kind === ts.SyntaxKind.Identifier &&
334
+ openingTag.expression.text === 'motion';
335
+ if (
336
+ CLIENT_ANIMATION_DIRECTIVES_REGEX.test(attrName) &&
337
+ !isMotionAttribute
338
+ ) {
339
+ interactive = true;
340
+ return;
341
+ }
342
+ }
343
+ }
344
+
345
+ // 3. Check for standalone animation/canvas component tags (<AnimatePresence>, <Canvas>, <motion.div>, etc.)
346
+ if (
347
+ node.kind === ts.SyntaxKind.JsxOpeningElement ||
348
+ node.kind === ts.SyntaxKind.JsxSelfClosingElement
349
+ ) {
350
+ const tagNameNode = node.tagName;
351
+ if (tagNameNode.kind === ts.SyntaxKind.PropertyAccessExpression) {
352
+ const expr = tagNameNode.expression;
353
+ if (
354
+ expr &&
355
+ expr.kind === ts.SyntaxKind.Identifier &&
356
+ (expr.text === 'motion' ||
357
+ expr.text === 'm' ||
358
+ expr.text === 'animated')
359
+ ) {
360
+ if (!ignoreMotionTags || expr.text !== 'motion') {
361
+ interactive = true;
362
+ return;
363
+ }
364
+ }
365
+ }
366
+ if (tagNameNode.kind === ts.SyntaxKind.Identifier) {
367
+ if (CLIENT_ANIMATION_TAGS.has(tagNameNode.text)) {
368
+ interactive = true;
369
+ return;
370
+ }
371
+ }
372
+ }
373
+
374
+ // 5. Check for browser globals: Identifier referencing window/document/etc.
375
+ if (node.kind === ts.SyntaxKind.Identifier) {
376
+ const name = node.text;
377
+ if (
378
+ [
379
+ 'window',
380
+ 'document',
381
+ 'localStorage',
382
+ 'sessionStorage',
383
+ 'navigator',
384
+ ].includes(name)
385
+ ) {
386
+ // Verify it's not a property name or within an import declaration
387
+ let parent = node.parent;
388
+ let isImportOrProperty = false;
389
+ while (parent) {
390
+ if (
391
+ parent.kind === ts.SyntaxKind.ImportDeclaration ||
392
+ parent.kind === ts.SyntaxKind.ImportSpecifier ||
393
+ parent.kind === ts.SyntaxKind.PropertyDeclaration ||
394
+ parent.kind === ts.SyntaxKind.PropertySignature ||
395
+ (parent.kind === ts.SyntaxKind.PropertyAccessExpression &&
396
+ parent.name === node)
397
+ ) {
398
+ isImportOrProperty = true;
399
+ break;
400
+ }
401
+ parent = parent.parent;
402
+ }
403
+ if (!isImportOrProperty) {
404
+ interactive = true;
405
+ return;
406
+ }
407
+ }
408
+ }
409
+
410
+ ts.forEachChild(node, checkNode);
411
+ }
412
+
413
+ checkNode(rootNode);
414
+ return interactive;
415
+ }
416
+
417
+ // Pass 1: resolve every top-level local use* function/const declaration's own
418
+ // interactivity (resolvingLocalHooks=true — a local hook calling ANOTHER local
419
+ // hook is conservatively treated as interactive rather than recursed into
420
+ // further, to keep this a bounded, one-level resolution).
421
+ function collectLocalHookDecls(node) {
422
+ let name = null;
423
+ let body = null;
424
+ if (
425
+ node.kind === ts.SyntaxKind.FunctionDeclaration &&
426
+ node.name &&
427
+ /^use[A-Z]/.test(node.name.text) &&
428
+ node.body
429
+ ) {
430
+ name = node.name.text;
431
+ body = node.body;
432
+ } else if (
433
+ node.kind === ts.SyntaxKind.VariableDeclaration &&
434
+ node.name.kind === ts.SyntaxKind.Identifier &&
435
+ /^use[A-Z]/.test(node.name.text) &&
436
+ node.initializer &&
437
+ (node.initializer.kind === ts.SyntaxKind.ArrowFunction ||
438
+ node.initializer.kind === ts.SyntaxKind.FunctionExpression) &&
439
+ node.initializer.body
440
+ ) {
441
+ name = node.name.text;
442
+ body = node.initializer.body;
443
+ }
444
+ if (name && body && !localHookInteractivity.has(name)) {
445
+ localHookInteractivity.set(name, checkInteractivity(body, true));
446
+ }
447
+ ts.forEachChild(node, collectLocalHookDecls);
448
+ }
449
+ collectLocalHookDecls(sourceFile);
450
+
451
+ return {
452
+ isNodeInteractive: (node) => checkInteractivity(node, false),
453
+ // Generic escape hatch for callers that need to treat certain descendants
454
+ // as opaque (e.g. island-split.js's "does THIS JSX element have its own
455
+ // direct interactivity, separate from a nested child element's" check —
456
+ // stopPredicate lets it skip descending into nested JsxElement/
457
+ // JsxSelfClosingElement/JsxFragment nodes while still applying the exact
458
+ // same hook/handler/global rules to everything else).
459
+ isNodeInteractiveWithBoundary: (node, stopPredicate) =>
460
+ checkInteractivity(node, false, stopPredicate),
461
+ localHookInteractivity,
462
+ };
463
+ }
464
+
465
+ /**
466
+ * True for exported bindings that look like React components (PascalCase).
467
+ * Re-exported hooks (`useReducedMotion`) and data constants (`fadeUp`) are
468
+ * not island candidates.
469
+ */
470
+ function isComponentExportName(name) {
471
+ return typeof name === 'string' && name !== 'default' && /^[A-Z]/.test(name);
472
+ }
473
+
474
+ /**
475
+ * React context providers are conventionally named `*Provider`. They use
476
+ * hooks, so a file-level interactivity scan would treat them as islands.
477
+ * Wrapping a provider hydrates its entire subtree as one client root and
478
+ * destroys every nested island inside it. Providers are not UI islands.
479
+ */
480
+ export function isContextProviderExportName(name) {
481
+ return typeof name === 'string' && /Provider$/.test(name);
482
+ }
483
+
484
+ /**
485
+ * Detects if a component node is a pure layout/children wrapper (e.g. `<Reveal>`, `<Stagger>`, `<Float>`).
486
+ * A pure children wrapper receives `{ children }` and renders `{ children }` inside a layout/motion tag
487
+ * without any local state, effects, or event handlers.
488
+ * Wrapping them as individual micro-islands inserts extra <div> wrappers inside CSS grids and flexbox,
489
+ * breaking parent-child layouts. They are preserved as SSR layout containers while their parent
490
+ * UI components hydrate as clean islands.
491
+ */
492
+ export function isPureChildrenWrapper(node, tsModule) {
493
+ if (!node || !tsModule) return false;
494
+ const ts = tsModule;
495
+
496
+ let params = null;
497
+ let body = null;
498
+
499
+ if (
500
+ node.kind === ts.SyntaxKind.FunctionDeclaration ||
501
+ node.kind === ts.SyntaxKind.FunctionExpression ||
502
+ node.kind === ts.SyntaxKind.ArrowFunction
503
+ ) {
504
+ params = node.parameters;
505
+ body = node.body;
506
+ } else if (
507
+ node.kind === ts.SyntaxKind.VariableDeclaration &&
508
+ node.initializer
509
+ ) {
510
+ const init = node.initializer;
511
+ if (
512
+ init.kind === ts.SyntaxKind.FunctionExpression ||
513
+ init.kind === ts.SyntaxKind.ArrowFunction
514
+ ) {
515
+ params = init.parameters;
516
+ body = init.body;
517
+ }
518
+ }
519
+
520
+ if (!params || params.length === 0 || !body) return false;
521
+
522
+ // Check if first parameter is destructured with `children`
523
+ const firstParam = params[0];
524
+ let hasChildren = false;
525
+ if (
526
+ firstParam.name &&
527
+ firstParam.name.kind === ts.SyntaxKind.ObjectBindingPattern
528
+ ) {
529
+ hasChildren = firstParam.name.elements.some((el) => {
530
+ const name = el.propertyName
531
+ ? el.propertyName.text
532
+ : el.name && el.name.text;
533
+ return name === 'children';
534
+ });
535
+ } else if (
536
+ firstParam.name &&
537
+ firstParam.name.kind === ts.SyntaxKind.Identifier &&
538
+ firstParam.name.text === 'props'
539
+ ) {
540
+ let usesPropsChildren = false;
541
+ function checkProps(n) {
542
+ if (usesPropsChildren) return;
543
+ if (
544
+ n.kind === ts.SyntaxKind.PropertyAccessExpression &&
545
+ n.expression &&
546
+ n.expression.text === 'props' &&
547
+ n.name &&
548
+ n.name.text === 'children'
549
+ ) {
550
+ usesPropsChildren = true;
551
+ return;
552
+ }
553
+ ts.forEachChild(n, checkProps);
554
+ }
555
+ checkProps(body);
556
+ hasChildren = usesPropsChildren;
557
+ }
558
+
559
+ if (!hasChildren) return false;
560
+
561
+ // If the component has active state, effects, or custom event handlers (like onClick, onMouseMove),
562
+ // it is an active interactive component (e.g. Magnetic, TiltCard), NOT a pure layout/motion wrapper.
563
+ let hasActiveBehavior = false;
564
+ function checkActive(n) {
565
+ if (hasActiveBehavior) return;
566
+
567
+ // Check for interactive hooks (useState, useEffect, useReducer, useRef, etc.)
568
+ if (n.kind === ts.SyntaxKind.CallExpression) {
569
+ const expr = n.expression;
570
+ let hookName = null;
571
+ if (expr.kind === ts.SyntaxKind.Identifier) {
572
+ hookName = expr.text;
573
+ } else if (expr.kind === ts.SyntaxKind.PropertyAccessExpression) {
574
+ hookName = expr.name ? expr.name.text : null;
575
+ }
576
+ if (
577
+ hookName &&
578
+ hookName.startsWith('use') &&
579
+ !SERVER_SAFE_HOOKS.includes(hookName) &&
580
+ hookName !== 'useReducedMotion'
581
+ ) {
582
+ hasActiveBehavior = true;
583
+ return;
584
+ }
585
+ }
586
+
587
+ // Check for interactive event listeners (onClick, onMouseMove, onMouseEnter, etc.)
588
+ if (
589
+ n.kind === ts.SyntaxKind.JsxAttribute &&
590
+ n.name &&
591
+ n.name.kind === ts.SyntaxKind.Identifier
592
+ ) {
593
+ if (/^on[A-Z]/.test(n.name.text) && !isAttributeOfWpEditable(n, ts)) {
594
+ hasActiveBehavior = true;
595
+ return;
596
+ }
597
+ }
598
+
599
+ // Check for browser globals
600
+ if (
601
+ n.kind === ts.SyntaxKind.Identifier &&
602
+ [
603
+ 'window',
604
+ 'document',
605
+ 'localStorage',
606
+ 'sessionStorage',
607
+ 'navigator',
608
+ ].includes(n.text)
609
+ ) {
610
+ let parent = n.parent;
611
+ let isImportOrProp = false;
612
+ while (parent) {
613
+ if (
614
+ parent.kind === ts.SyntaxKind.ImportDeclaration ||
615
+ parent.kind === ts.SyntaxKind.ImportSpecifier ||
616
+ parent.kind === ts.SyntaxKind.PropertyDeclaration ||
617
+ parent.kind === ts.SyntaxKind.PropertySignature ||
618
+ (parent.kind === ts.SyntaxKind.PropertyAccessExpression &&
619
+ parent.name === n)
620
+ ) {
621
+ isImportOrProp = true;
622
+ break;
623
+ }
624
+ parent = parent.parent;
625
+ }
626
+ if (!isImportOrProp) {
627
+ hasActiveBehavior = true;
628
+ return;
629
+ }
630
+ }
631
+
632
+ ts.forEachChild(n, checkActive);
633
+ }
634
+
635
+ checkActive(body);
636
+
637
+ return !hasActiveBehavior;
638
+ }
639
+
640
+ function hasExportModifier(node, tsModule) {
641
+ return !!(
642
+ node.modifiers &&
643
+ node.modifiers.some((m) => m.kind === tsModule.SyntaxKind.ExportKeyword)
644
+ );
645
+ }
646
+
647
+ function hasDefaultModifier(node, tsModule) {
648
+ return !!(
649
+ node.modifiers &&
650
+ node.modifiers.some((m) => m.kind === tsModule.SyntaxKind.DefaultKeyword)
651
+ );
652
+ }
653
+
654
+ /**
655
+ * Collects locally-declared exported bindings and the AST node whose body
656
+ * should be scanned for interactivity. Covers:
657
+ * export function Foo() {}
658
+ * export const Foo = () => {}
659
+ * export const Foo = React.forwardRef(...)
660
+ * const Foo = () => {}; export { Foo }
661
+ * export default function Foo() {}
662
+ * export default Foo
663
+ *
664
+ * Re-exports from another module (`export { Foo } from './bar'`) are skipped —
665
+ * those are not this file's implementation.
666
+ *
667
+ * @returns {Array<{ name: string, node: object }>}
668
+ */
669
+ export function collectExportedComponentNodes(sourceFile, tsModule) {
670
+ const ts = tsModule;
671
+ const locals = new Map();
672
+
673
+ function collectLocals(node) {
674
+ if (ts.isFunctionDeclaration(node) && node.name) {
675
+ locals.set(node.name.text, node);
676
+ } else if (
677
+ ts.isVariableDeclaration(node) &&
678
+ ts.isIdentifier(node.name) &&
679
+ node.initializer
680
+ ) {
681
+ locals.set(node.name.text, node);
682
+ }
683
+ ts.forEachChild(node, collectLocals);
684
+ }
685
+ collectLocals(sourceFile);
686
+
687
+ const results = [];
688
+ function add(name, node) {
689
+ if (!name || !node) return;
690
+ results.push({ name, node });
691
+ }
692
+
693
+ for (const stmt of sourceFile.statements) {
694
+ if (
695
+ ts.isFunctionDeclaration(stmt) &&
696
+ stmt.name &&
697
+ hasExportModifier(stmt, ts)
698
+ ) {
699
+ add(stmt.name.text, stmt);
700
+ if (hasDefaultModifier(stmt, ts)) add('default', stmt);
701
+ } else if (ts.isFunctionDeclaration(stmt) && hasDefaultModifier(stmt, ts)) {
702
+ add(stmt.name ? stmt.name.text : 'default', stmt);
703
+ add('default', stmt);
704
+ } else if (ts.isVariableStatement(stmt) && hasExportModifier(stmt, ts)) {
705
+ for (const decl of stmt.declarationList.declarations) {
706
+ if (ts.isIdentifier(decl.name)) add(decl.name.text, decl);
707
+ }
708
+ } else if (ts.isExportAssignment(stmt) && !stmt.isExportEquals) {
709
+ if (
710
+ ts.isIdentifier(stmt.expression) &&
711
+ locals.has(stmt.expression.text)
712
+ ) {
713
+ add(stmt.expression.text, locals.get(stmt.expression.text));
714
+ add('default', locals.get(stmt.expression.text));
715
+ } else {
716
+ add('default', stmt.expression);
717
+ }
718
+ } else if (
719
+ ts.isExportDeclaration(stmt) &&
720
+ !stmt.moduleSpecifier &&
721
+ stmt.exportClause &&
722
+ ts.isNamedExports(stmt.exportClause)
723
+ ) {
724
+ for (const el of stmt.exportClause.elements) {
725
+ const exportedName = el.name.text;
726
+ const localName = el.propertyName ? el.propertyName.text : exportedName;
727
+ if (locals.has(localName)) add(exportedName, locals.get(localName));
728
+ }
729
+ }
730
+ }
731
+
732
+ return results;
733
+ }
734
+
735
+ function findExportNode(sourceFile, exportName, tsModule) {
736
+ const exports = collectExportedComponentNodes(sourceFile, tsModule);
737
+ const named = exports.find((e) => e.name === exportName);
738
+ if (named) return named.node;
739
+ if (exportName !== 'default') {
740
+ const fallback = exports.find((e) => e.name === 'default');
741
+ if (fallback) return fallback.node;
742
+ }
743
+ return null;
744
+ }
745
+
746
+ /**
747
+ * Per-export interactivity. A module that exports both a static helper
748
+ * (server-safe hooks only) and a genuine island (state / effects / handlers)
749
+ * must not mark every import from that file as a client island — wrapping a
750
+ * static helper that takes JSX children remounts with `children` stripped
751
+ * and wipes the server HTML.
752
+ *
753
+ * @param {string} filePath
754
+ * @param {string} exportName - JSX tag / named export
755
+ * @returns {boolean}
756
+ */
757
+ export function isExportInteractive(filePath, exportName) {
758
+ if (!exportName || !existsSync(filePath)) return false;
759
+ try {
760
+ const content = readComponentSource(filePath);
761
+
762
+ if (!ts) {
763
+ return isComponentInteractive(filePath);
764
+ }
765
+
766
+ const sourceFile = ts.createSourceFile(
767
+ filePath,
768
+ content,
769
+ ts.ScriptTarget.Latest,
770
+ true,
771
+ ts.ScriptKind.TSX,
772
+ );
773
+
774
+ if (isContextProviderExportName(exportName)) return false;
775
+
776
+ const target = findExportNode(sourceFile, exportName, ts);
777
+ if (!target) return false;
778
+
779
+ if (isPureChildrenWrapper(target, ts)) return false;
780
+
781
+ const { isNodeInteractive } = createInteractivityChecker(sourceFile, ts);
782
+ return isNodeInteractive(target);
783
+ } catch (err) {
784
+ console.error(
785
+ `[AST Interactivity Scan] Error parsing export ${exportName} in ${filePath}:`,
786
+ err,
787
+ );
788
+ return false;
789
+ }
790
+ }
791
+
792
+ /**
793
+ * PascalCase exported components in `filePath` whose own implementation is
794
+ * interactive. Used by Smart Discovery so a mixed helper file only
795
+ * contributes the exports that actually need a client bundle.
796
+ *
797
+ * @param {string} filePath
798
+ * @returns {string[]}
799
+ */
800
+ export function getInteractiveExportNames(filePath) {
801
+ if (!existsSync(filePath)) return [];
802
+ try {
803
+ const content = readComponentSource(filePath);
804
+ if (!ts) {
805
+ return isComponentInteractive(filePath)
806
+ ? [path.basename(filePath).replace(/\.(tsx|ts|jsx|js)$/, '')]
807
+ : [];
808
+ }
809
+
810
+ const sourceFile = ts.createSourceFile(
811
+ filePath,
812
+ content,
813
+ ts.ScriptTarget.Latest,
814
+ true,
815
+ ts.ScriptKind.TSX,
816
+ );
817
+
818
+ const { isNodeInteractive } = createInteractivityChecker(sourceFile, ts);
819
+ const names = [];
820
+ const seen = new Set();
821
+ for (const entry of collectExportedComponentNodes(sourceFile, ts)) {
822
+ if (!isComponentExportName(entry.name) || seen.has(entry.name)) continue;
823
+ if (isContextProviderExportName(entry.name)) continue;
824
+ if (isPureChildrenWrapper(entry.node, ts)) continue;
825
+ if (isNodeInteractive(entry.node)) {
826
+ seen.add(entry.name);
827
+ names.push(entry.name);
828
+ }
829
+ }
830
+
831
+ // Default-exported layout components (for example SiteNavigation) are
832
+ // frequently used by name from page/layout files but are not returned by
833
+ // the named-export collector. Include their declared component name so
834
+ // extracted WordPress shells receive a client hydration entry too.
835
+ const defaultExportMatch = content.match(
836
+ /export\s+default\s+(?:async\s+)?(?:function|class)\s+([A-Z][A-Za-z0-9_$]*)/,
837
+ );
838
+ if (defaultExportMatch) {
839
+ const defaultName = defaultExportMatch[1];
840
+ if (
841
+ !seen.has(defaultName) &&
842
+ isComponentExportName(defaultName) &&
843
+ isComponentInteractive(filePath)
844
+ ) {
845
+ names.push(defaultName);
846
+ }
847
+ }
848
+ return names;
849
+ } catch (err) {
850
+ console.error(
851
+ `[AST Interactivity Scan] Error listing interactive exports for ${filePath}:`,
852
+ err,
853
+ );
854
+ return [];
855
+ }
856
+ }
857
+
858
+ /**
859
+ * Statically analyzes a component file using the TypeScript AST parser
860
+ * to check for client-side interactivity triggers (hooks, inline event handlers, browser globals).
861
+ *
862
+ * File-level: true if ANY top-level code in the file is interactive. Prefer
863
+ * `isExportInteractive` / `getInteractiveExportNames` when deciding whether a
864
+ * specific JSX tag should become a hydration island.
865
+ *
866
+ * @param {string} filePath - Absolute path to the component file.
867
+ * @returns {boolean} True if the component is interactive (island).
868
+ */
869
+ export function isComponentInteractive(filePath) {
870
+ if (!existsSync(filePath)) return false;
871
+ try {
872
+ const content = readComponentSource(filePath);
873
+
874
+ if (!ts) {
875
+ // Regex fallback. Strip <WpEditable ...>...</WpEditable> and self-closing
876
+ // <WpEditable ... /> tags before the inline-handler check — same reasoning
877
+ // as the AST path's isAttributeOfWpEditable: WpEditable's onChange is
878
+ // inert on the frontend and shouldn't by itself force a hydration bundle.
879
+ const contentForHandlerCheck = stripWpEditableBlocksNaive(content);
880
+ const hasState =
881
+ content.includes('useState') ||
882
+ content.includes('useEffect') ||
883
+ content.includes('useRef') ||
884
+ content.includes('useContext');
885
+ const hasMotion =
886
+ CLIENT_ANIMATION_PACKAGES.some(
887
+ (pkg) => content.includes(`"${pkg}"`) || content.includes(`'${pkg}'`),
888
+ ) ||
889
+ /whileInView|whileHover|whileTap|whileDrag|whileFocus|layoutId|data-aos|data-scroll|\bmotion\.|\banimated\./.test(
890
+ content,
891
+ );
892
+ const hasInlineHandlers = /on[A-Z][a-zA-Z]*\s*=\s*/.test(
893
+ contentForHandlerCheck,
894
+ );
895
+ const hasBrowserGlobals =
896
+ /\b(window|document|localStorage|sessionStorage|navigator)\b/.test(
897
+ content,
898
+ );
899
+ // See the serverSafeHooks note below — useWpQuery always needs client hydration.
900
+ const hasWpQuery = content.includes('useWpQuery');
901
+ return (
902
+ hasState ||
903
+ hasMotion ||
904
+ hasInlineHandlers ||
905
+ hasBrowserGlobals ||
906
+ hasWpQuery
907
+ );
908
+ }
909
+
910
+ const sourceFile = ts.createSourceFile(
911
+ filePath,
912
+ content,
913
+ ts.ScriptTarget.Latest,
914
+ true,
915
+ ts.ScriptKind.TSX,
916
+ );
917
+
918
+ const { isNodeInteractive } = createInteractivityChecker(sourceFile, ts);
919
+ return isNodeInteractive(sourceFile);
920
+ } catch (err) {
921
+ console.error(
922
+ `[AST Interactivity Scan] Error parsing AST for ${filePath}:`,
923
+ err,
924
+ );
925
+ return false;
926
+ }
927
+ }
928
+
929
+ export function isComponentEditorUnsafe(filePath) {
930
+ if (!existsSync(filePath) || !ts) return true;
931
+ try {
932
+ const content = readComponentSource(filePath);
933
+ const sourceFile = ts.createSourceFile(
934
+ filePath,
935
+ content,
936
+ ts.ScriptTarget.Latest,
937
+ true,
938
+ ts.ScriptKind.TSX,
939
+ );
940
+ const { isNodeInteractive } = createInteractivityChecker(sourceFile, ts, {
941
+ ignoreMotionTags: true,
942
+ });
943
+ return isNodeInteractive(sourceFile);
944
+ } catch (err) {
945
+ console.error(
946
+ `[AST Editor Interactivity Scan] Error parsing ${filePath}:`,
947
+ err,
948
+ );
949
+ return true;
950
+ }
951
+ }