@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,52 @@
1
+ /**
2
+ * Pick the React component export that matches a hydration island name.
3
+ *
4
+ * Never fall back to `Object.values(module)[0]` — Vite's export object
5
+ * order is not the component the island was named for. A multi-export
6
+ * module would otherwise mount a sibling export with the wrong props.
7
+ *
8
+ * @param {Record<string, unknown>} module
9
+ * @param {string} islandName kebab-case island id (e.g. "product-hotspot")
10
+ * @returns {Function|undefined}
11
+ */
12
+ export function resolveIslandComponent(module, islandName) {
13
+ if (!module || !islandName) return undefined;
14
+
15
+ const pascalName = islandName
16
+ .split("-")
17
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
18
+ .join("");
19
+
20
+ if (typeof module[pascalName] === "function") return module[pascalName];
21
+ if (typeof module.default === "function") return module.default;
22
+
23
+ const fnKeys = Object.keys(module).filter(
24
+ (k) => k !== "default" && typeof module[k] === "function",
25
+ );
26
+ if (fnKeys.length === 1) return module[fnKeys[0]];
27
+
28
+ return undefined;
29
+ }
30
+
31
+ /**
32
+ * Browser-hydrator copy of resolveIslandComponent (no ESM import in the
33
+ * generated IIFE). Keep in sync with the function above.
34
+ */
35
+ export const RESOLVE_ISLAND_COMPONENT_JS = `
36
+ const pascalName = islandName
37
+ .split("-")
38
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
39
+ .join("");
40
+ let Component = typeof module[pascalName] === "function" ? module[pascalName] : undefined;
41
+ if (!Component && typeof module.default === "function") {
42
+ Component = module.default;
43
+ }
44
+ if (!Component) {
45
+ const fnKeys = Object.keys(module).filter(function (k) {
46
+ return k !== "default" && typeof module[k] === "function";
47
+ });
48
+ if (fnKeys.length === 1) {
49
+ Component = module[fnKeys[0]];
50
+ }
51
+ }
52
+ `;
@@ -0,0 +1,81 @@
1
+ import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { scanForHydrationIslands, findComponentPath } from "./islands-scanner.js";
4
+ import { splitInteractiveIslands } from "./island-split.js";
5
+ import { scanAppProviders } from "./scan-app-providers.js";
6
+
7
+ /**
8
+ * Resolves Rollup's multi-entry input mapping for Vite based on discovered hydration islands.
9
+ *
10
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
11
+ * @returns {Record<string, string>} Rollup input object.
12
+ */
13
+ export function getHydrationRollupInputs(themeRoot) {
14
+ const inputs = {
15
+ index: path.resolve(themeRoot, "index.html"),
16
+ };
17
+
18
+ // vite.config.ts calls this at config-load time — BEFORE any plugin's
19
+ // buildStart() hook fires (config resolution always precedes the build's
20
+ // plugin lifecycle) — so a component that a dev's own code mixes static
21
+ // and interactive content in must be auto-split HERE, not only in
22
+ // forgewpPageConfigPlugin's buildStart(); otherwise scanForHydrationIslands
23
+ // below sees the original, still-fully-interactive file and registers it
24
+ // as its own direct Rollup entry, containing raw (pre-esbuild) JSX that
25
+ // Rollup's lightweight import-analysis parser cannot handle.
26
+ try {
27
+ splitInteractiveIslands(themeRoot);
28
+ } catch (err) {
29
+ console.warn("[ForgeWP Auto-Island-Split] Error running splitInteractiveIslands:", err.message);
30
+ }
31
+
32
+ const islands = scanForHydrationIslands(themeRoot);
33
+ for (const island of islands) {
34
+ const compPath = findComponentPath(themeRoot, island);
35
+ if (compPath) {
36
+ inputs[island] = compPath;
37
+ }
38
+ }
39
+
40
+ // Provider modules are not UI islands, but every island remounts in its
41
+ // own React root and must be wrapped with the same provider tree the
42
+ // layout declared (flying hearts, cart drawer open, auth, …).
43
+ for (const provider of scanAppProviders(themeRoot)) {
44
+ if (!inputs[provider.kebab] && existsSync(provider.file)) {
45
+ inputs[provider.kebab] = provider.file;
46
+ }
47
+ }
48
+
49
+ // Scan and inject custom blocks from src/blocks/
50
+ const blocksDir = path.join(themeRoot, "src", "blocks");
51
+ if (existsSync(blocksDir)) {
52
+ try {
53
+ const items = readdirSync(blocksDir);
54
+ for (const item of items) {
55
+ const fullPath = path.join(blocksDir, item);
56
+ const isDir = statSync(fullPath).isDirectory();
57
+ if (isDir) {
58
+ const indexPath = path.join(fullPath, "index.tsx");
59
+ if (existsSync(indexPath)) {
60
+ const blockName = item
61
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
62
+ .toLowerCase()
63
+ .replace(/[^a-z0-9]+/g, "-");
64
+ inputs[`block-${blockName}`] = indexPath;
65
+ }
66
+ } else if (item.endsWith(".tsx") || item.endsWith(".jsx")) {
67
+ const blockName = item
68
+ .replace(/\.(tsx|jsx)$/, "")
69
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
70
+ .toLowerCase()
71
+ .replace(/[^a-z0-9]+/g, "-");
72
+ inputs[`block-${blockName}`] = fullPath;
73
+ }
74
+ }
75
+ } catch (err) {
76
+ console.warn("[Hydration Scanner] Failed to scan src/blocks/:", err.message);
77
+ }
78
+ }
79
+
80
+ return inputs;
81
+ }
@@ -0,0 +1,220 @@
1
+ import { readFileSync, existsSync } from "node:fs";
2
+ import { ts } from "./is-interactive.js";
3
+
4
+ /**
5
+ * Matches only the Tailwind utility families that affect box geometry/
6
+ * positioning within a parent (the auto-island wrapper's actual job, per
7
+ * this file's own module doc). Deliberately excludes anything decorative
8
+ * (bg-*, border*, rounded-*, shadow-*, padding, text-*, font-*, etc.) —
9
+ * the wrapper sits OUTSIDE the component's own root element, so copying a
10
+ * decorative class means both wrapper and root render it, doubling up
11
+ * backgrounds/borders/shadows/padding into a visible "box inside a box".
12
+ * Only a class needed to keep the wrapper from collapsing to an unstyled
13
+ * shrink-to-fit box belongs here.
14
+ */
15
+ const LAYOUT_CLASS_PATTERN = new RegExp(
16
+ '^(?:' +
17
+ '[whm]in-w-|[whm]ax-w-|[whm]in-h-|[whm]ax-h-|w-|h-|size-|' +
18
+ 'block$|inline(?:-|$)|flex(?:-|$)|grid(?:-|$)|hidden$|table(?:-|$)|contents$|flow-root$|' +
19
+ 'static$|relative$|absolute$|fixed$|sticky$|inset-|top-|right-|bottom-|left-|z-|' +
20
+ 'col-|row-|gap-|items-|justify-|self-|place-|order-|basis-|shrink|grow|' +
21
+ 'overflow-|aspect-' +
22
+ ')',
23
+ );
24
+
25
+ function filterToLayoutClasses(classString) {
26
+ const kept = classString
27
+ .split(/\s+/)
28
+ .filter(Boolean)
29
+ .filter((cls) => {
30
+ // Responsive/state variants (sm:flex, hover:flex) — check the utility
31
+ // after the last ':' so a variant prefix doesn't block a real match.
32
+ const bare = cls.includes(':') ? cls.slice(cls.lastIndexOf(':') + 1) : cls;
33
+ return LAYOUT_CLASS_PATTERN.test(bare);
34
+ });
35
+ return kept.length > 0 ? kept.join(' ') : null;
36
+ }
37
+
38
+ /**
39
+ * Statically extracts the literal `className` of a component's outermost returned
40
+ * JSX element, so auto-generated <Hydrate> wrapper divs (Smart Discovery) can inherit
41
+ * layout-critical classes (w-full, flex, grid, sticky, ...) instead of defaulting to a
42
+ * bare `display:block` box with no width/layout awareness of its own.
43
+ *
44
+ * Without this, wrapping an interactive component whose root element carries sizing
45
+ * classes silently breaks percentage-width layouts: the wrapper becomes an unstyled
46
+ * shrink-to-fit box sitting between the real parent and the component, and `w-full`
47
+ * on the component's root can no longer resolve against the intended container.
48
+ *
49
+ * Resolution is intentionally conservative — only proven-static values (string literals,
50
+ * no-substitution template literals) are hoisted. Anything dynamic (template
51
+ * expressions, cn()/clsx() calls, identifiers, conditionals) is reported as unresolved
52
+ * so callers can fall back to a lint warning instead of guessing at runtime behavior.
53
+ *
54
+ * @param {string} filePath - Absolute path to the component file.
55
+ * @returns {{ resolvable: boolean, className: string | null, reason?: string }}
56
+ */
57
+ export function getComponentRootClassName(filePath) {
58
+ if (!ts || !filePath || !existsSync(filePath)) {
59
+ return { resolvable: false, className: null, reason: "no-parser" };
60
+ }
61
+
62
+ try {
63
+ const content = readFileSync(filePath, "utf8");
64
+ const sourceFile = ts.createSourceFile(
65
+ filePath,
66
+ content,
67
+ ts.ScriptTarget.Latest,
68
+ true,
69
+ ts.ScriptKind.TSX
70
+ );
71
+
72
+ const candidates = [];
73
+
74
+ function registerCandidate(node, name) {
75
+ if (name && /^[A-Z]/.test(name)) {
76
+ candidates.push({ name, node });
77
+ }
78
+ }
79
+
80
+ function visit(node) {
81
+ if (ts.isFunctionDeclaration(node) && node.name) {
82
+ registerCandidate(node, node.name.text);
83
+ } else if (ts.isVariableStatement(node)) {
84
+ for (const decl of node.declarationList.declarations) {
85
+ if (
86
+ decl.name &&
87
+ ts.isIdentifier(decl.name) &&
88
+ decl.initializer &&
89
+ (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer))
90
+ ) {
91
+ registerCandidate(decl.initializer, decl.name.text);
92
+ }
93
+ }
94
+ }
95
+ ts.forEachChild(node, visit);
96
+ }
97
+ visit(sourceFile);
98
+
99
+ if (candidates.length === 0) {
100
+ return { resolvable: true, className: null };
101
+ }
102
+
103
+ // ForgeWP's convention is one component per file — prefer the last top-level
104
+ // candidate (typically the default-exported component; helper/inner functions
105
+ // declared earlier in the file are unlikely to be the mount point).
106
+ const target = candidates[candidates.length - 1];
107
+ const rootExpr = findReturnedJsxExpression(target.node);
108
+ if (!rootExpr) {
109
+ return { resolvable: true, className: null };
110
+ }
111
+
112
+ return extractClassNameFromJsxRoot(rootExpr);
113
+ } catch {
114
+ return { resolvable: false, className: null, reason: "parse-error" };
115
+ }
116
+ }
117
+
118
+ function unwrapParens(node) {
119
+ while (node && ts.isParenthesizedExpression(node)) {
120
+ node = node.expression;
121
+ }
122
+ return node;
123
+ }
124
+
125
+ function findReturnedJsxExpression(fnNode) {
126
+ const body = fnNode.body;
127
+ if (!body) return null;
128
+
129
+ // Arrow function with an implicit expression body: const Foo = () => (<div />)
130
+ if (!ts.isBlock(body)) {
131
+ return unwrapParens(body);
132
+ }
133
+
134
+ // Block body: use the first top-level `return` statement. Early-return guards
135
+ // (loading states, null checks, etc.) mean this isn't always the "real" root,
136
+ // which is fine — it's a best-effort hint, not a correctness guarantee.
137
+ for (const stmt of body.statements) {
138
+ if (ts.isReturnStatement(stmt) && stmt.expression) {
139
+ return unwrapParens(stmt.expression);
140
+ }
141
+ }
142
+ return null;
143
+ }
144
+
145
+ function extractStaticStringsFromExpression(node) {
146
+ if (!node) return [];
147
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
148
+ return [node.text];
149
+ }
150
+ if (ts.isTemplateExpression(node)) {
151
+ const parts = [node.head.text];
152
+ for (const span of node.templateSpans) {
153
+ parts.push(span.literal.text);
154
+ }
155
+ return parts;
156
+ }
157
+ if (ts.isCallExpression(node)) {
158
+ const parts = [];
159
+ for (const arg of node.arguments) {
160
+ parts.push(...extractStaticStringsFromExpression(arg));
161
+ }
162
+ return parts;
163
+ }
164
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {
165
+ return [
166
+ ...extractStaticStringsFromExpression(node.left),
167
+ ...extractStaticStringsFromExpression(node.right),
168
+ ];
169
+ }
170
+ return [];
171
+ }
172
+
173
+ function extractClassNameFromJsxRoot(expr) {
174
+ if (!expr) return { resolvable: true, className: null };
175
+
176
+ let targetElement = expr;
177
+
178
+ // Handle Fragments (<> ... </>) by inspecting the first child element
179
+ if (ts.isJsxFragment(expr)) {
180
+ const firstChild = expr.children.find(
181
+ (c) => ts.isJsxElement(c) || ts.isJsxSelfClosingElement(c)
182
+ );
183
+ if (firstChild) {
184
+ targetElement = firstChild;
185
+ }
186
+ }
187
+
188
+ if (!ts.isJsxElement(targetElement) && !ts.isJsxSelfClosingElement(targetElement)) {
189
+ return { resolvable: true, className: null };
190
+ }
191
+
192
+ const opening = ts.isJsxElement(targetElement) ? targetElement.openingElement : targetElement;
193
+ const classAttr = opening.attributes.properties.find(
194
+ (p) => ts.isJsxAttribute(p) && p.name && p.name.text === "className"
195
+ );
196
+
197
+ if (!classAttr) {
198
+ return { resolvable: true, className: null };
199
+ }
200
+ if (!classAttr.initializer) {
201
+ return { resolvable: false, className: null, reason: "dynamic-classname" };
202
+ }
203
+
204
+ const init = classAttr.initializer;
205
+ if (ts.isStringLiteral(init)) {
206
+ return { resolvable: true, className: filterToLayoutClasses(init.text) };
207
+ }
208
+ if (ts.isJsxExpression(init) && init.expression) {
209
+ const staticStrings = extractStaticStringsFromExpression(init.expression);
210
+ if (staticStrings.length > 0) {
211
+ const combined = staticStrings.join(" ");
212
+ const layoutClasses = filterToLayoutClasses(combined);
213
+ if (layoutClasses) {
214
+ return { resolvable: true, className: layoutClasses };
215
+ }
216
+ }
217
+ }
218
+
219
+ return { resolvable: false, className: null, reason: "dynamic-classname" };
220
+ }
@@ -0,0 +1,154 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { ts, isContextProviderExportName } from "./is-interactive.js";
4
+ import { resolveImportPath } from "./utils.js";
5
+
6
+ function toKebabName(exportName) {
7
+ return exportName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
8
+ }
9
+
10
+ /**
11
+ * Walks `src/app/layout.tsx` (and `src/app/layout.ts`) for theme-local
12
+ * `*Provider` components that wrap `{children}`. Returned in nest order
13
+ * (outermost first) so the hydrator can rebuild the same provider tree
14
+ * around every island. Not an island list — providers must not become
15
+ * `data-forgewp-hydrate` wrappers.
16
+ *
17
+ * @param {string} themeRoot
18
+ * @returns {Array<{ exportName: string, kebab: string, file: string }>}
19
+ */
20
+ export function scanAppProviders(themeRoot) {
21
+ if (!ts || !themeRoot) return [];
22
+
23
+ const candidates = [
24
+ path.join(themeRoot, "src", "app", "layout.tsx"),
25
+ path.join(themeRoot, "src", "app", "layout.ts"),
26
+ path.join(themeRoot, "src", "app", "layout.jsx"),
27
+ path.join(themeRoot, "src", "app", "layout.js"),
28
+ ];
29
+ const layoutPath = candidates.find((p) => existsSync(p));
30
+ if (!layoutPath) return [];
31
+
32
+ let sourceText;
33
+ try {
34
+ sourceText = readFileSync(layoutPath, "utf8");
35
+ } catch {
36
+ return [];
37
+ }
38
+
39
+ const sourceFile = ts.createSourceFile(
40
+ layoutPath,
41
+ sourceText,
42
+ ts.ScriptTarget.Latest,
43
+ true,
44
+ ts.ScriptKind.TSX,
45
+ );
46
+
47
+ const imports = {};
48
+ function collectImports(node) {
49
+ if (ts.isImportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
50
+ const spec = node.moduleSpecifier.text;
51
+ const clause = node.importClause;
52
+ if (clause) {
53
+ if (clause.name) imports[clause.name.text] = spec;
54
+ if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
55
+ clause.namedBindings.elements.forEach((el) => {
56
+ imports[el.name.text] = spec;
57
+ });
58
+ }
59
+ }
60
+ }
61
+ ts.forEachChild(node, collectImports);
62
+ }
63
+ collectImports(sourceFile);
64
+
65
+ const found = [];
66
+ const seen = new Set();
67
+
68
+ function visit(node) {
69
+ if (ts.isJsxElement(node)) {
70
+ const tag = node.openingElement.tagName;
71
+ if (ts.isIdentifier(tag) && isContextProviderExportName(tag.text)) {
72
+ const spec = imports[tag.text];
73
+ if (spec && (spec.startsWith(".") || spec.startsWith("@/"))) {
74
+ const resolved = resolveImportPath(path.dirname(layoutPath), spec, themeRoot);
75
+ if (resolved && !seen.has(tag.text)) {
76
+ seen.add(tag.text);
77
+ found.push({
78
+ exportName: tag.text,
79
+ kebab: toKebabName(tag.text),
80
+ file: resolved,
81
+ });
82
+ }
83
+ }
84
+ }
85
+ }
86
+ ts.forEachChild(node, visit);
87
+ }
88
+ visit(sourceFile);
89
+
90
+ return found;
91
+ }
92
+
93
+ /**
94
+ * True when `filePath` imports a module that is one of the layout providers
95
+ * (or a hook/component from the same file). Used so only islands that
96
+ * actually consume cart/wishlist/auth context get wrapped — wrapping a
97
+ * quote carousel with a motion-heavy wishlist provider remounts it from
98
+ * `initial={{ opacity: 0 }}` and hides text that SSR already painted.
99
+ */
100
+ export function fileImportsProvider(filePath, providers, visited = new Set()) {
101
+ if (!filePath || !providers || providers.length === 0 || !existsSync(filePath) || visited.has(filePath)) {
102
+ return false;
103
+ }
104
+ visited.add(filePath);
105
+ const providerFiles = new Set(providers.map((p) => p.file.replace(/\\/g, "/")));
106
+ let sourceText;
107
+ try {
108
+ sourceText = readFileSync(filePath, "utf8");
109
+ } catch {
110
+ return false;
111
+ }
112
+ if (!ts) {
113
+ return providers.some((p) => sourceText.includes(p.exportName) || sourceText.includes(p.kebab));
114
+ }
115
+ const sourceFile = ts.createSourceFile(
116
+ filePath,
117
+ sourceText,
118
+ ts.ScriptTarget.Latest,
119
+ true,
120
+ ts.ScriptKind.TSX,
121
+ );
122
+ const themeRootGuess = filePath.includes(`${path.sep}src${path.sep}`)
123
+ ? filePath.slice(0, filePath.indexOf(`${path.sep}src${path.sep}`))
124
+ : path.dirname(filePath);
125
+
126
+ let found = false;
127
+ const importedPaths = [];
128
+ function visit(node) {
129
+ if (found) return;
130
+ if (ts.isImportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
131
+ const spec = node.moduleSpecifier.text;
132
+ if (spec.startsWith(".") || spec.startsWith("@/")) {
133
+ const resolved = resolveImportPath(path.dirname(filePath), spec, themeRootGuess);
134
+ if (resolved) {
135
+ if (providerFiles.has(resolved.replace(/\\/g, "/"))) {
136
+ found = true;
137
+ return;
138
+ }
139
+ importedPaths.push(resolved);
140
+ }
141
+ }
142
+ }
143
+ ts.forEachChild(node, visit);
144
+ }
145
+ visit(sourceFile);
146
+ if (found) return true;
147
+
148
+ for (const imp of importedPaths) {
149
+ if (fileImportsProvider(imp, providers, visited)) {
150
+ return true;
151
+ }
152
+ }
153
+ return false;
154
+ }