@ecopages/react 0.2.0-beta.31 → 0.2.0-beta.33

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 (57) hide show
  1. package/README.md +5 -1
  2. package/package.json +4 -4
  3. package/src/app/client-only.js +13 -17
  4. package/src/app/dynamic.js +7 -10
  5. package/src/app/dynamic.test.browser.js +27 -29
  6. package/src/bundling/bootstrap-package-paths.js +5 -6
  7. package/src/bundling/bundle.js +115 -114
  8. package/src/bundling/discover-layout-runtime-modules.js +166 -155
  9. package/src/bundling/runtime-alias-map.d.ts +4 -1
  10. package/src/bundling/runtime-alias-map.js +107 -95
  11. package/src/bundling/runtime-bundle.js +250 -274
  12. package/src/bundling/runtime-interop-plugin.js +31 -35
  13. package/src/bundling/runtime-mode.js +10 -5
  14. package/src/bundling/runtime-modules.js +46 -35
  15. package/src/client-graph/ast-transform.js +415 -305
  16. package/src/client-graph/boundary-cache.js +146 -104
  17. package/src/client-graph/boundary-plugin.js +122 -104
  18. package/src/client-graph/component-config-traversal.js +70 -49
  19. package/src/client-graph/declared-modules.js +63 -41
  20. package/src/client-graph/reachability-analyzer.js +506 -313
  21. package/src/client-graph/specifier-classification.js +209 -141
  22. package/src/contracts/router-adapter.js +6 -0
  23. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  24. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  25. package/src/hmr/hmr-scripts.js +22 -9
  26. package/src/hmr/hmr-strategy.d.ts +12 -181
  27. package/src/hmr/hmr-strategy.js +321 -650
  28. package/src/hmr/page-metadata-cache.js +43 -40
  29. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +23 -0
  30. package/src/hmr/react-hmr-dev-transform-plugins.js +20 -0
  31. package/src/hydration/assert-no-bare-ecopages-imports.js +6 -6
  32. package/src/hydration/bootstrap-imports.js +30 -20
  33. package/src/hydration/hydration-asset.js +216 -213
  34. package/src/hydration/hydration-scripts.d.ts +4 -0
  35. package/src/hydration/hydration-scripts.js +199 -66
  36. package/src/hydration/hydration-scripts.test.browser.js +163 -168
  37. package/src/hydration/page-data-manifest.js +89 -45
  38. package/src/hydration/page-data-reader.js +45 -32
  39. package/src/hydration/page-payload.js +101 -99
  40. package/src/hydration/serialize-page-data-script.js +27 -28
  41. package/src/mdx/mdx-config-dependency.js +108 -112
  42. package/src/mdx/mdx-loader-plugin.js +7 -10
  43. package/src/page/page-module.js +72 -66
  44. package/src/plugin/react.constants.js +1 -4
  45. package/src/plugin/react.plugin.d.ts +1 -0
  46. package/src/plugin/react.plugin.js +227 -216
  47. package/src/plugin/react.types.js +1 -0
  48. package/src/render/component-ownership.js +42 -18
  49. package/src/render/component-ssr.js +168 -190
  50. package/src/render/eco-embed.js +8 -10
  51. package/src/render/errors.js +21 -16
  52. package/src/render/html-boundary.js +55 -51
  53. package/src/render/layout-compose.js +122 -94
  54. package/src/render/react-renderer.js +433 -468
  55. package/src/render/react-runtime.js +25 -20
  56. package/src/render/unified-layout-composition.js +74 -85
  57. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
@@ -1,335 +1,445 @@
1
- import { extname } from "node:path";
2
- import { cachedParseSync } from "@ecopages/core/cache";
3
- import { analyzeReachability } from "./reachability-analyzer.js";
4
- import {
5
- isBareSpecifier,
6
- isProjectAliasSpecifier,
7
- isServerOnlySpecifier,
8
- toModuleBaseSpecifier,
9
- parseDeclaredModules,
10
- mergeDeclaredModulesMap,
11
- normalizeRequestedExportsKey,
12
- resolveRequestedExportsKey,
13
- mergeRequestedExportRules
14
- } from "./specifier-classification.js";
15
- const SERVER_ONLY_ECO_PAGE_OPTION_KEYS = /* @__PURE__ */ new Set([
16
- "cache",
17
- "middleware",
18
- "requires",
19
- "metadata",
20
- "staticProps",
21
- "staticPaths"
1
+ /**
2
+ * AST transforms for the client graph boundary plugin.
3
+ */
4
+ import { extname } from 'node:path';
5
+ import { cachedParseSync } from '@ecopages/core/cache';
6
+ import { analyzeReachability } from './reachability-analyzer.js';
7
+ import { isBareSpecifier, isProjectAliasSpecifier, isServerOnlySpecifier, toModuleBaseSpecifier, parseDeclaredModules, mergeDeclaredModulesMap, normalizeRequestedExportsKey, resolveRequestedExportsKey, mergeRequestedExportRules, } from './specifier-classification.js';
8
+ const SERVER_ONLY_ECO_PAGE_OPTION_KEYS = new Set([
9
+ 'cache',
10
+ 'middleware',
11
+ 'requires',
12
+ 'metadata',
13
+ 'staticProps',
14
+ 'staticPaths',
22
15
  ]);
16
+ /**
17
+ * Returns the proper OxC parser dialect to use for string source parsing.
18
+ *
19
+ * @param filename - File path.
20
+ * @returns Language string.
21
+ */
23
22
  function parserLanguageForFile(filename) {
24
- const extension = extname(filename).toLowerCase();
25
- if (extension === ".tsx") return "tsx";
26
- if (extension === ".ts") return "ts";
27
- if (extension === ".jsx") return "jsx";
28
- return "js";
23
+ const extension = extname(filename).toLowerCase();
24
+ if (extension === '.tsx')
25
+ return 'tsx';
26
+ if (extension === '.ts')
27
+ return 'ts';
28
+ if (extension === '.jsx')
29
+ return 'jsx';
30
+ return 'js';
29
31
  }
32
+ /**
33
+ * Extracts a static property key name from an object literal property node.
34
+ *
35
+ * The client graph boundary rewrite only strips known `eco.page(...)` keys when
36
+ * it can prove the property name statically. Computed or otherwise dynamic keys
37
+ * are ignored so the transform remains conservative.
38
+ *
39
+ * @param node - OXC AST node representing an object property key.
40
+ * @returns Static property key name when it can be resolved, otherwise `undefined`.
41
+ */
30
42
  function getObjectPropertyKeyName(node) {
31
- if (!node) return void 0;
32
- if (node.type === "Identifier") return node.name;
33
- if (node.type === "StringLiteral" || node.type === "Literal") {
34
- return typeof node.value === "string" ? node.value : void 0;
35
- }
36
- return void 0;
43
+ if (!node)
44
+ return undefined;
45
+ if (node.type === 'Identifier')
46
+ return node.name;
47
+ if (node.type === 'StringLiteral' || node.type === 'Literal') {
48
+ return typeof node.value === 'string' ? node.value : undefined;
49
+ }
50
+ return undefined;
37
51
  }
52
+ /**
53
+ * Removes server-only `eco.page(...)` options from browser-bound modules.
54
+ *
55
+ * Import pruning alone is not sufficient because a page module can still retain
56
+ * references to stripped server imports through config fields like `middleware`
57
+ * or `metadata`. This pass rewrites the `eco.page(...)` object literal so only
58
+ * browser-relevant properties remain.
59
+ *
60
+ * @param source - Original or already-transformed module source.
61
+ * @param program - Parsed OXC program for the same source text.
62
+ * @returns Updated source plus a flag indicating whether any rewrite occurred.
63
+ */
38
64
  function stripServerOnlyEcoPageOptions(source, program) {
39
- const edits = [];
40
- function walk(node) {
41
- if (!node || typeof node !== "object") return;
42
- if (Array.isArray(node)) {
43
- for (const child of node) walk(child);
44
- return;
45
- }
46
- if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && node.callee.object?.type === "Identifier" && node.callee.object.name === "eco" && node.callee.property?.type === "Identifier" && node.callee.property.name === "page" && node.arguments?.[0]?.type === "ObjectExpression") {
47
- const objectExpression = node.arguments[0];
48
- const keptProperties = [];
49
- let removedProperty = false;
50
- for (const property of objectExpression.properties ?? []) {
51
- if (property?.type === "Property") {
52
- const keyName = getObjectPropertyKeyName(property.key);
53
- if (keyName && SERVER_ONLY_ECO_PAGE_OPTION_KEYS.has(keyName)) {
54
- removedProperty = true;
55
- continue;
56
- }
65
+ const edits = [];
66
+ function walk(node) {
67
+ if (!node || typeof node !== 'object')
68
+ return;
69
+ if (Array.isArray(node)) {
70
+ for (const child of node)
71
+ walk(child);
72
+ return;
57
73
  }
58
- keptProperties.push(source.slice(property.start, property.end));
59
- }
60
- if (removedProperty) {
61
- const replacement = keptProperties.length > 0 ? `{ ${keptProperties.join(", ")} }` : "{}";
62
- edits.push({
63
- start: objectExpression.start,
64
- end: objectExpression.end,
65
- replacement
66
- });
67
- }
68
- }
69
- for (const key in node) {
70
- if (key !== "type" && key !== "start" && key !== "end") {
71
- walk(node[key]);
72
- }
73
- }
74
- }
75
- walk(program);
76
- if (edits.length === 0) {
77
- return { transformed: source, modified: false };
78
- }
79
- edits.sort((a, b) => b.start - a.start);
80
- let transformed = source;
81
- for (const edit of edits) {
82
- transformed = transformed.slice(0, edit.start) + edit.replacement + transformed.slice(edit.end);
83
- }
84
- return { transformed, modified: true };
85
- }
86
- function transformModuleImports(source, filename, globallyAllowed, requestedExports, projectRoot) {
87
- let result;
88
- try {
89
- result = cachedParseSync(filename, source, {
90
- sourceType: "module",
91
- lang: parserLanguageForFile(filename)
92
- });
93
- } catch {
94
- return { transformed: source, modified: false };
95
- }
96
- const { program } = result;
97
- const localDeclared = [];
98
- function walk(node) {
99
- if (!node || typeof node !== "object") return;
100
- if (Array.isArray(node)) {
101
- for (const child of node) walk(child);
102
- return;
103
- }
104
- if (node.type === "Property" && node.key?.name === "modules" && node.value?.type === "ArrayExpression") {
105
- for (const el of node.value.elements) {
106
- if ((el.type === "StringLiteral" || el.type === "Literal") && typeof el.value === "string") {
107
- localDeclared.push(el.value);
74
+ if (node.type === 'CallExpression' &&
75
+ node.callee?.type === 'MemberExpression' &&
76
+ node.callee.object?.type === 'Identifier' &&
77
+ node.callee.object.name === 'eco' &&
78
+ node.callee.property?.type === 'Identifier' &&
79
+ node.callee.property.name === 'page' &&
80
+ node.arguments?.[0]?.type === 'ObjectExpression') {
81
+ const objectExpression = node.arguments[0];
82
+ const keptProperties = [];
83
+ let removedProperty = false;
84
+ for (const property of objectExpression.properties ?? []) {
85
+ if (property?.type === 'Property') {
86
+ const keyName = getObjectPropertyKeyName(property.key);
87
+ if (keyName && SERVER_ONLY_ECO_PAGE_OPTION_KEYS.has(keyName)) {
88
+ removedProperty = true;
89
+ continue;
90
+ }
91
+ }
92
+ keptProperties.push(source.slice(property.start, property.end));
93
+ }
94
+ if (removedProperty) {
95
+ const replacement = keptProperties.length > 0 ? `{ ${keptProperties.join(', ')} }` : '{}';
96
+ edits.push({
97
+ start: objectExpression.start,
98
+ end: objectExpression.end,
99
+ replacement,
100
+ });
101
+ }
108
102
  }
109
- }
103
+ for (const key in node) {
104
+ if (key !== 'type' && key !== 'start' && key !== 'end') {
105
+ walk(node[key]);
106
+ }
107
+ }
108
+ }
109
+ walk(program);
110
+ if (edits.length === 0) {
111
+ return { transformed: source, modified: false };
110
112
  }
111
- for (const key in node) {
112
- if (key !== "type" && key !== "start" && key !== "end") {
113
- walk(node[key]);
114
- }
113
+ edits.sort((a, b) => b.start - a.start);
114
+ let transformed = source;
115
+ for (const edit of edits) {
116
+ transformed = transformed.slice(0, edit.start) + edit.replacement + transformed.slice(edit.end);
115
117
  }
116
- }
117
- walk(program);
118
- const locallyAllowed = parseDeclaredModules(localDeclared);
119
- const allowedMap = mergeDeclaredModulesMap(globallyAllowed, locallyAllowed);
120
- const explicitRequestedExports = requestedExports.get(normalizeRequestedExportsKey(filename));
121
- const reachability = analyzeReachability(source, filename, program, explicitRequestedExports);
122
- for (const statement of program.body) {
123
- if (statement.type === "ImportDeclaration") {
124
- const reachableRules = reachability.reachableImports.get(statement.source.value);
125
- const requestedModuleKey = resolveRequestedExportsKey(filename, statement.source.value);
126
- if (!requestedModuleKey || !reachableRules) continue;
127
- mergeRequestedExportRules(requestedExports, requestedModuleKey, reachableRules);
128
- continue;
118
+ return { transformed, modified: true };
119
+ }
120
+ /**
121
+ * Parses a module using Oxc AST and surgically removes forbidden imports.
122
+ * Filters down to the exact specifiers requested via `{namedImport}` syntax.
123
+ *
124
+ * @param source - The raw string source content of the module.
125
+ * @param filename - The absolute path of the module.
126
+ * @param globallyAllowed - A map of modules declared globally allowable by the build configuration.
127
+ * @param requestedExports - Local requested-export registry used to propagate named reachability across files.
128
+ * @returns An object containing the transformed string and a boolean indicating if changes occurred.
129
+ */
130
+ export function transformModuleImports(source, filename, globallyAllowed, requestedExports, projectRoot) {
131
+ /**
132
+ * Parse the source
133
+ *
134
+ * We parse once here and then reuse the resulting `program` AST for both
135
+ * the local `modules` declaration walk (step 2) and the reachability analysis
136
+ * (step 3). Passing it through avoids a redundant second `parseSync` call inside
137
+ * `analyzeReachability`, cutting the per-file OxC work roughly in half.
138
+ */
139
+ let result;
140
+ try {
141
+ result = cachedParseSync(filename, source, {
142
+ sourceType: 'module',
143
+ lang: parserLanguageForFile(filename),
144
+ });
129
145
  }
130
- if (statement.type === "ExportNamedDeclaration" && statement.source) {
131
- const reachableRules = reachability.reachableImports.get(statement.source.value);
132
- const requestedModuleKey = resolveRequestedExportsKey(filename, statement.source.value);
133
- if (!requestedModuleKey || !reachableRules) continue;
134
- mergeRequestedExportRules(requestedExports, requestedModuleKey, reachableRules);
135
- continue;
146
+ catch {
147
+ return { transformed: source, modified: false };
136
148
  }
137
- if (statement.type === "ExportAllDeclaration" && statement.source) {
138
- const reachableRules = reachability.reachableImports.get(statement.source.value);
139
- const requestedModuleKey = resolveRequestedExportsKey(filename, statement.source.value);
140
- if (!requestedModuleKey || !reachableRules) continue;
141
- mergeRequestedExportRules(requestedExports, requestedModuleKey, reachableRules);
149
+ const { program } = result;
150
+ const localDeclared = [];
151
+ /**
152
+ * Collect locally declared modules
153
+ *
154
+ * Walk the AST looking for `modules: [...]` array properties. These are the
155
+ * component-level allowlist declarations that a developer writes inside
156
+ * `eco.page({ modules: ['react', '@myorg/ui{Button}'] })` to explicitly opt
157
+ * specific packages into the client bundle.
158
+ *
159
+ * The collected specifiers are merged with the globally configured allowlist
160
+ * before any import filtering takes place.
161
+ */
162
+ function walk(node) {
163
+ if (!node || typeof node !== 'object')
164
+ return;
165
+ if (Array.isArray(node)) {
166
+ for (const child of node)
167
+ walk(child);
168
+ return;
169
+ }
170
+ if (node.type === 'Property' && node.key?.name === 'modules' && node.value?.type === 'ArrayExpression') {
171
+ for (const el of node.value.elements) {
172
+ if ((el.type === 'StringLiteral' || el.type === 'Literal') && typeof el.value === 'string') {
173
+ localDeclared.push(el.value);
174
+ }
175
+ }
176
+ }
177
+ for (const key in node) {
178
+ if (key !== 'type' && key !== 'start' && key !== 'end') {
179
+ walk(node[key]);
180
+ }
181
+ }
142
182
  }
143
- }
144
- const edits = [];
145
- function processSpecifier(specifier) {
146
- const moduleBase = toModuleBaseSpecifier(specifier);
147
- const explicitRules = allowedMap.get(moduleBase);
148
- if (isServerOnlySpecifier(specifier)) {
149
- if (explicitRules) {
150
- return { allowed: true, rules: explicitRules };
151
- }
152
- return { allowed: false };
183
+ walk(program);
184
+ /**
185
+ * Merge allowlists and compute reachability
186
+ *
187
+ * Combine the globally declared modules (from plugin config) with the locally
188
+ * declared ones (from the component's `modules` array) into a single authoritative map.
189
+ *
190
+ * Then run the reachability analysis, passing the already-parsed `program` so the
191
+ * analyser skips its own internal `parseSync` call (see step 1 above).
192
+ */
193
+ const locallyAllowed = parseDeclaredModules(localDeclared);
194
+ const allowedMap = mergeDeclaredModulesMap(globallyAllowed, locallyAllowed);
195
+ const explicitRequestedExports = requestedExports.get(normalizeRequestedExportsKey(filename));
196
+ const reachability = analyzeReachability(source, filename, program, explicitRequestedExports);
197
+ for (const statement of program.body) {
198
+ if (statement.type === 'ImportDeclaration') {
199
+ const reachableRules = reachability.reachableImports.get(statement.source.value);
200
+ const requestedModuleKey = resolveRequestedExportsKey(filename, statement.source.value);
201
+ if (!requestedModuleKey || !reachableRules)
202
+ continue;
203
+ mergeRequestedExportRules(requestedExports, requestedModuleKey, reachableRules);
204
+ continue;
205
+ }
206
+ if (statement.type === 'ExportNamedDeclaration' && statement.source) {
207
+ const reachableRules = reachability.reachableImports.get(statement.source.value);
208
+ const requestedModuleKey = resolveRequestedExportsKey(filename, statement.source.value);
209
+ if (!requestedModuleKey || !reachableRules)
210
+ continue;
211
+ mergeRequestedExportRules(requestedExports, requestedModuleKey, reachableRules);
212
+ continue;
213
+ }
214
+ if (statement.type === 'ExportAllDeclaration' && statement.source) {
215
+ const reachableRules = reachability.reachableImports.get(statement.source.value);
216
+ const requestedModuleKey = resolveRequestedExportsKey(filename, statement.source.value);
217
+ if (!requestedModuleKey || !reachableRules)
218
+ continue;
219
+ mergeRequestedExportRules(requestedExports, requestedModuleKey, reachableRules);
220
+ }
153
221
  }
154
- if (isProjectAliasSpecifier(specifier, projectRoot)) return { allowed: true, rules: explicitRules ?? "*" };
155
- if (!isBareSpecifier(specifier)) return { allowed: true, rules: explicitRules ?? "*" };
156
- return { allowed: true, rules: explicitRules ?? "*" };
157
- }
158
- function walkImports(node) {
159
- if (!node || typeof node !== "object") return;
160
- if (Array.isArray(node)) {
161
- for (const child of node) walkImports(child);
162
- return;
222
+ /**
223
+ * Build the edit list
224
+ *
225
+ * Walk the AST a second time, this time inspecting every import/export/dynamic-import
226
+ * node against the combined allowlist and the reachability graph:
227
+ *
228
+ * - **Forbidden + unreachable** → replace with empty string (pruned).
229
+ * - **Forbidden + reachable from a known client root** → throw a build error so the
230
+ * developer is forced to resolve the server-client boundary violation explicitly.
231
+ * - **Allowed with specific named rules** → surgically rewrite the import to keep only
232
+ * the permitted named bindings; the bundler tree-shakes the rest.
233
+ * - **Allowed with no restrictions** → left untouched; the bundler handles tree-shaking.
234
+ */
235
+ const edits = [];
236
+ function processSpecifier(specifier) {
237
+ const moduleBase = toModuleBaseSpecifier(specifier);
238
+ const explicitRules = allowedMap.get(moduleBase);
239
+ if (isServerOnlySpecifier(specifier)) {
240
+ if (explicitRules) {
241
+ return { allowed: true, rules: explicitRules };
242
+ }
243
+ return { allowed: false };
244
+ }
245
+ if (isProjectAliasSpecifier(specifier, projectRoot))
246
+ return { allowed: true, rules: explicitRules ?? '*' };
247
+ if (!isBareSpecifier(specifier))
248
+ return { allowed: true, rules: explicitRules ?? '*' };
249
+ /** By default, bare specifiers (NPM modules) are allowed entirely. */
250
+ return { allowed: true, rules: explicitRules ?? '*' };
163
251
  }
164
- if (node.type === "ImportDeclaration") {
165
- const specifier = node.source.value;
166
- const reachableRules = reachability.reachableImports.get(specifier);
167
- const { allowed, rules } = processSpecifier(specifier);
168
- if (!allowed) {
169
- if (reachableRules && !reachability.isFallbackRoots) {
170
- throw new Error(
171
- `[Ecopages Client Reachability] Forbidden client import '${specifier}' at ${filename}:${node.start}. This import is explicitly reachable from the React render function.`
172
- );
173
- } else {
174
- edits.push({ start: node.start, end: node.end, replacement: "" });
252
+ function walkImports(node) {
253
+ if (!node || typeof node !== 'object')
254
+ return;
255
+ if (Array.isArray(node)) {
256
+ for (const child of node)
257
+ walkImports(child);
258
+ return;
175
259
  }
176
- return;
177
- }
178
- if (rules instanceof Set && node.specifiers && node.specifiers.length > 0) {
179
- let keptSpecifierCount = 0;
180
- let defaultImportLocal;
181
- let namespaceImportLocal;
182
- const namedImportNodes = [];
183
- for (const spec of node.specifiers) {
184
- if (spec.type === "ImportSpecifier") {
185
- const importedName = spec.imported.type === "Identifier" ? spec.imported.name : spec.imported.value;
186
- if (rules.has(importedName)) {
187
- keptSpecifierCount += 1;
188
- const localName = spec.local?.name;
189
- if (localName && localName !== importedName) {
190
- namedImportNodes.push(`${importedName} as ${localName}`);
191
- } else {
192
- namedImportNodes.push(importedName);
193
- }
260
+ if (node.type === 'ImportDeclaration') {
261
+ const specifier = node.source.value;
262
+ const reachableRules = reachability.reachableImports.get(specifier);
263
+ const { allowed, rules } = processSpecifier(specifier);
264
+ if (!allowed) {
265
+ if (reachableRules && !reachability.isFallbackRoots) {
266
+ throw new Error(`[Ecopages Client Reachability] Forbidden client import '${specifier}' at ${filename}:${node.start}. This import is explicitly reachable from the React render function.`);
267
+ }
268
+ else {
269
+ edits.push({ start: node.start, end: node.end, replacement: '' });
270
+ }
271
+ return;
194
272
  }
195
- } else if (spec.type === "ImportDefaultSpecifier") {
196
- if (rules.has("default")) {
197
- keptSpecifierCount += 1;
198
- defaultImportLocal = spec.local.name;
273
+ /**
274
+ * If it IS allowed by the base specifier, we must check if there are specific named rules.
275
+ * If there are specific rules (a Set), we must surgically remove any specifiers that aren't in the rule.
276
+ */
277
+ if (rules instanceof Set && node.specifiers && node.specifiers.length > 0) {
278
+ let keptSpecifierCount = 0;
279
+ let defaultImportLocal;
280
+ let namespaceImportLocal;
281
+ const namedImportNodes = [];
282
+ for (const spec of node.specifiers) {
283
+ if (spec.type === 'ImportSpecifier') {
284
+ const importedName = spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value;
285
+ if (rules.has(importedName)) {
286
+ keptSpecifierCount += 1;
287
+ const localName = spec.local?.name;
288
+ if (localName && localName !== importedName) {
289
+ namedImportNodes.push(`${importedName} as ${localName}`);
290
+ }
291
+ else {
292
+ namedImportNodes.push(importedName);
293
+ }
294
+ }
295
+ }
296
+ else if (spec.type === 'ImportDefaultSpecifier') {
297
+ if (rules.has('default')) {
298
+ keptSpecifierCount += 1;
299
+ defaultImportLocal = spec.local.name;
300
+ }
301
+ }
302
+ else if (spec.type === 'ImportNamespaceSpecifier') {
303
+ if (rules.has('*')) {
304
+ keptSpecifierCount += 1;
305
+ namespaceImportLocal = spec.local.name;
306
+ }
307
+ }
308
+ }
309
+ if (keptSpecifierCount === 0) {
310
+ edits.push({ start: node.start, end: node.end, replacement: '' });
311
+ }
312
+ else if (keptSpecifierCount < node.specifiers.length) {
313
+ let newDeclaration = '';
314
+ if (defaultImportLocal && namespaceImportLocal) {
315
+ newDeclaration = `import ${defaultImportLocal}, * as ${namespaceImportLocal} from '${specifier}';`;
316
+ }
317
+ else if (namespaceImportLocal) {
318
+ newDeclaration = `import * as ${namespaceImportLocal} from '${specifier}';`;
319
+ }
320
+ else if (defaultImportLocal && namedImportNodes.length > 0) {
321
+ newDeclaration = `import ${defaultImportLocal}, { ${namedImportNodes.join(', ')} } from '${specifier}';`;
322
+ }
323
+ else if (defaultImportLocal) {
324
+ newDeclaration = `import ${defaultImportLocal} from '${specifier}';`;
325
+ }
326
+ else {
327
+ newDeclaration = `import { ${namedImportNodes.join(', ')} } from '${specifier}';`;
328
+ }
329
+ edits.push({ start: node.start, end: node.end, replacement: newDeclaration });
330
+ }
331
+ return;
199
332
  }
200
- } else if (spec.type === "ImportNamespaceSpecifier") {
201
- if (rules.has("*")) {
202
- keptSpecifierCount += 1;
203
- namespaceImportLocal = spec.local.name;
333
+ /**
334
+ * If it IS allowed (globally or all specifiers match) and IS reachable,
335
+ * we can safely just leave the import alone.
336
+ * ESBuild will natively treeshake any bindings that are actually unused.
337
+ *
338
+ * However, if it is completely unreachable, and it's a side-effect import
339
+ * (no specifiers), we want to proactively prune it.
340
+ */
341
+ if (!reachableRules && (!node.specifiers || node.specifiers.length === 0)) {
342
+ edits.push({ start: node.start, end: node.end, replacement: '' });
204
343
  }
205
- }
344
+ return;
206
345
  }
207
- if (keptSpecifierCount === 0) {
208
- edits.push({ start: node.start, end: node.end, replacement: "" });
209
- } else if (keptSpecifierCount < node.specifiers.length) {
210
- let newDeclaration = "";
211
- if (defaultImportLocal && namespaceImportLocal) {
212
- newDeclaration = `import ${defaultImportLocal}, * as ${namespaceImportLocal} from '${specifier}';`;
213
- } else if (namespaceImportLocal) {
214
- newDeclaration = `import * as ${namespaceImportLocal} from '${specifier}';`;
215
- } else if (defaultImportLocal && namedImportNodes.length > 0) {
216
- newDeclaration = `import ${defaultImportLocal}, { ${namedImportNodes.join(", ")} } from '${specifier}';`;
217
- } else if (defaultImportLocal) {
218
- newDeclaration = `import ${defaultImportLocal} from '${specifier}';`;
219
- } else {
220
- newDeclaration = `import { ${namedImportNodes.join(", ")} } from '${specifier}';`;
221
- }
222
- edits.push({ start: node.start, end: node.end, replacement: newDeclaration });
346
+ if (node.type === 'ExportNamedDeclaration' && node.source) {
347
+ const specifier = node.source.value;
348
+ const { allowed } = processSpecifier(specifier);
349
+ if (!allowed) {
350
+ const reachableRules = reachability.reachableImports.get(specifier);
351
+ if (reachableRules && !reachability.isFallbackRoots) {
352
+ throw new Error(`[Ecopages Client Reachability] Forbidden client export from '${specifier}' at ${filename}:${node.start}. This export is explicitly reachable from the React render function.`);
353
+ }
354
+ else {
355
+ edits.push({ start: node.start, end: node.end, replacement: '' });
356
+ }
357
+ }
358
+ return;
223
359
  }
224
- return;
225
- }
226
- if (!reachableRules && (!node.specifiers || node.specifiers.length === 0)) {
227
- edits.push({ start: node.start, end: node.end, replacement: "" });
228
- }
229
- return;
230
- }
231
- if (node.type === "ExportNamedDeclaration" && node.source) {
232
- const specifier = node.source.value;
233
- const { allowed } = processSpecifier(specifier);
234
- if (!allowed) {
235
- const reachableRules = reachability.reachableImports.get(specifier);
236
- if (reachableRules && !reachability.isFallbackRoots) {
237
- throw new Error(
238
- `[Ecopages Client Reachability] Forbidden client export from '${specifier}' at ${filename}:${node.start}. This export is explicitly reachable from the React render function.`
239
- );
240
- } else {
241
- edits.push({ start: node.start, end: node.end, replacement: "" });
360
+ if (node.type === 'ExportAllDeclaration' && node.source) {
361
+ const specifier = node.source.value;
362
+ const { allowed } = processSpecifier(specifier);
363
+ if (!allowed) {
364
+ const reachableRules = reachability.reachableImports.get(specifier);
365
+ if (reachableRules && !reachability.isFallbackRoots) {
366
+ throw new Error(`[Ecopages Client Reachability] Forbidden client export * from '${specifier}' at ${filename}:${node.start}. This export is explicitly reachable from the React render function.`);
367
+ }
368
+ else {
369
+ edits.push({ start: node.start, end: node.end, replacement: '' });
370
+ }
371
+ }
372
+ return;
242
373
  }
243
- }
244
- return;
245
- }
246
- if (node.type === "ExportAllDeclaration" && node.source) {
247
- const specifier = node.source.value;
248
- const { allowed } = processSpecifier(specifier);
249
- if (!allowed) {
250
- const reachableRules = reachability.reachableImports.get(specifier);
251
- if (reachableRules && !reachability.isFallbackRoots) {
252
- throw new Error(
253
- `[Ecopages Client Reachability] Forbidden client export * from '${specifier}' at ${filename}:${node.start}. This export is explicitly reachable from the React render function.`
254
- );
255
- } else {
256
- edits.push({ start: node.start, end: node.end, replacement: "" });
374
+ if (node.type === 'ImportExpression' && node.source?.value) {
375
+ const specifier = node.source.value;
376
+ const { allowed } = processSpecifier(specifier);
377
+ const reachableRules = reachability.reachableImports.get(specifier);
378
+ if (!reachableRules) {
379
+ if (!allowed) {
380
+ edits.push({ start: node.start, end: node.end, replacement: 'Promise.resolve({})' });
381
+ }
382
+ return;
383
+ }
384
+ if (!allowed) {
385
+ if (!reachability.isFallbackRoots) {
386
+ throw new Error(`[Ecopages Client Reachability] Forbidden dynamic import('${specifier}') at ${filename}:${node.start}. This import is explicitly reachable from the React render function.`);
387
+ }
388
+ else {
389
+ edits.push({ start: node.start, end: node.end, replacement: 'Promise.resolve({})' });
390
+ }
391
+ }
392
+ return;
257
393
  }
258
- }
259
- return;
260
- }
261
- if (node.type === "ImportExpression" && node.source?.value) {
262
- const specifier = node.source.value;
263
- const { allowed } = processSpecifier(specifier);
264
- const reachableRules = reachability.reachableImports.get(specifier);
265
- if (!reachableRules) {
266
- if (!allowed) {
267
- edits.push({ start: node.start, end: node.end, replacement: "Promise.resolve({})" });
394
+ if (node.type === 'CallExpression' && node.callee?.type === 'Identifier' && node.callee.name === 'require') {
395
+ const arg = node.arguments?.[0];
396
+ if (arg && (arg.type === 'StringLiteral' || arg.type === 'Literal') && typeof arg.value === 'string') {
397
+ const specifier = arg.value;
398
+ const { allowed } = processSpecifier(specifier);
399
+ const reachableRules = reachability.reachableImports.get(specifier);
400
+ if (!reachableRules) {
401
+ if (!allowed) {
402
+ edits.push({ start: node.start, end: node.end, replacement: '({})' });
403
+ }
404
+ }
405
+ else if (!allowed) {
406
+ if (!reachability.isFallbackRoots) {
407
+ throw new Error(`[Ecopages Client Reachability] Forbidden require('${specifier}') at ${filename}:${node.start}. This import is explicitly reachable from the React render function.`);
408
+ }
409
+ else {
410
+ edits.push({ start: node.start, end: node.end, replacement: '({})' });
411
+ }
412
+ }
413
+ }
268
414
  }
269
- return;
270
- }
271
- if (!allowed) {
272
- if (!reachability.isFallbackRoots) {
273
- throw new Error(
274
- `[Ecopages Client Reachability] Forbidden dynamic import('${specifier}') at ${filename}:${node.start}. This import is explicitly reachable from the React render function.`
275
- );
276
- } else {
277
- edits.push({ start: node.start, end: node.end, replacement: "Promise.resolve({})" });
415
+ for (const key in node) {
416
+ if (key !== 'type' && key !== 'start' && key !== 'end') {
417
+ walkImports(node[key]);
418
+ }
278
419
  }
279
- }
280
- return;
281
420
  }
282
- if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require") {
283
- const arg = node.arguments?.[0];
284
- if (arg && (arg.type === "StringLiteral" || arg.type === "Literal") && typeof arg.value === "string") {
285
- const specifier = arg.value;
286
- const { allowed } = processSpecifier(specifier);
287
- const reachableRules = reachability.reachableImports.get(specifier);
288
- if (!reachableRules) {
289
- if (!allowed) {
290
- edits.push({ start: node.start, end: node.end, replacement: "({})" });
291
- }
292
- } else if (!allowed) {
293
- if (!reachability.isFallbackRoots) {
294
- throw new Error(
295
- `[Ecopages Client Reachability] Forbidden require('${specifier}') at ${filename}:${node.start}. This import is explicitly reachable from the React render function.`
296
- );
297
- } else {
298
- edits.push({ start: node.start, end: node.end, replacement: "({})" });
299
- }
300
- }
301
- }
421
+ walkImports(program);
422
+ if (edits.length === 0) {
423
+ return stripServerOnlyEcoPageOptions(source, program);
424
+ }
425
+ edits.sort((a, b) => b.start - a.start);
426
+ let transformed = source;
427
+ for (const edit of edits) {
428
+ transformed = transformed.slice(0, edit.start) + edit.replacement + transformed.slice(edit.end);
429
+ }
430
+ let reparsedResult;
431
+ try {
432
+ reparsedResult = cachedParseSync(filename, transformed, {
433
+ sourceType: 'module',
434
+ lang: parserLanguageForFile(filename),
435
+ });
436
+ }
437
+ catch {
438
+ return { transformed, modified: true };
302
439
  }
303
- for (const key in node) {
304
- if (key !== "type" && key !== "start" && key !== "end") {
305
- walkImports(node[key]);
306
- }
440
+ const strippedPageOptions = stripServerOnlyEcoPageOptions(transformed, reparsedResult.program);
441
+ if (strippedPageOptions.modified) {
442
+ return strippedPageOptions;
307
443
  }
308
- }
309
- walkImports(program);
310
- if (edits.length === 0) {
311
- return stripServerOnlyEcoPageOptions(source, program);
312
- }
313
- edits.sort((a, b) => b.start - a.start);
314
- let transformed = source;
315
- for (const edit of edits) {
316
- transformed = transformed.slice(0, edit.start) + edit.replacement + transformed.slice(edit.end);
317
- }
318
- let reparsedResult;
319
- try {
320
- reparsedResult = cachedParseSync(filename, transformed, {
321
- sourceType: "module",
322
- lang: parserLanguageForFile(filename)
323
- });
324
- } catch {
325
444
  return { transformed, modified: true };
326
- }
327
- const strippedPageOptions = stripServerOnlyEcoPageOptions(transformed, reparsedResult.program);
328
- if (strippedPageOptions.modified) {
329
- return strippedPageOptions;
330
- }
331
- return { transformed, modified: true };
332
445
  }
333
- export {
334
- transformModuleImports
335
- };