@ecopages/react 0.2.0-alpha.5 → 0.2.0-alpha.51
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.
- package/README.md +152 -29
- package/package.json +24 -12
- package/src/eco-embed.d.ts +11 -0
- package/src/eco-embed.js +11 -0
- package/src/react-hmr-strategy.d.ts +65 -43
- package/src/react-hmr-strategy.js +298 -145
- package/src/react-renderer.d.ts +169 -42
- package/src/react-renderer.js +484 -164
- package/src/react.constants.d.ts +1 -0
- package/src/react.constants.js +4 -0
- package/src/react.plugin.d.ts +40 -111
- package/src/react.plugin.js +136 -61
- package/src/react.types.d.ts +88 -0
- package/src/react.types.js +0 -0
- package/src/router-adapter.d.ts +7 -14
- package/src/runtime/use-sync-external-store-with-selector.d.ts +3 -0
- package/src/runtime/use-sync-external-store-with-selector.js +56 -0
- package/src/services/react-bundle.service.d.ts +22 -35
- package/src/services/react-bundle.service.js +41 -105
- package/src/services/react-hmr-page-metadata-cache.d.ts +9 -0
- package/src/services/react-hmr-page-metadata-cache.js +18 -2
- package/src/services/react-hydration-asset.service.d.ts +28 -19
- package/src/services/react-hydration-asset.service.js +85 -66
- package/src/services/react-mdx-config-dependency.service.d.ts +36 -0
- package/src/services/react-mdx-config-dependency.service.js +122 -0
- package/src/services/react-page-module.service.d.ts +10 -2
- package/src/services/react-page-module.service.js +47 -39
- package/src/services/react-page-payload.service.d.ts +46 -0
- package/src/services/react-page-payload.service.js +67 -0
- package/src/services/react-runtime-bundle.service.d.ts +20 -13
- package/src/services/react-runtime-bundle.service.js +146 -179
- package/src/utils/client-graph-boundary-plugin.d.ts +1 -1
- package/src/utils/client-graph-boundary-plugin.js +80 -3
- package/src/utils/component-config-traversal.d.ts +36 -0
- package/src/utils/component-config-traversal.js +54 -0
- package/src/utils/declared-modules.d.ts +1 -1
- package/src/utils/declared-modules.js +7 -16
- package/src/utils/dynamic.test.browser.d.ts +1 -0
- package/src/utils/dynamic.test.browser.js +33 -0
- package/src/utils/hydration-scripts.d.ts +27 -6
- package/src/utils/hydration-scripts.js +177 -44
- package/src/utils/hydration-scripts.test.browser.d.ts +1 -0
- package/src/utils/hydration-scripts.test.browser.js +198 -0
- package/src/utils/react-dom-runtime-interop-plugin.d.ts +5 -0
- package/src/utils/react-dom-runtime-interop-plugin.js +38 -0
- package/src/utils/react-mdx-loader-plugin.d.ts +1 -1
- package/src/utils/react-mdx-loader-plugin.js +13 -5
- package/src/utils/react-runtime-alias-map.d.ts +8 -0
- package/src/utils/react-runtime-alias-map.js +90 -0
- package/CHANGELOG.md +0 -67
- package/src/react-hmr-strategy.ts +0 -455
- package/src/react-renderer.ts +0 -403
- package/src/react.plugin.ts +0 -241
- package/src/router-adapter.ts +0 -95
- package/src/services/react-bundle.service.ts +0 -217
- package/src/services/react-hmr-page-metadata-cache.ts +0 -24
- package/src/services/react-hydration-asset.service.ts +0 -260
- package/src/services/react-page-module.service.ts +0 -214
- package/src/services/react-runtime-bundle.service.ts +0 -271
- package/src/utils/client-graph-boundary-plugin.ts +0 -710
- package/src/utils/client-only.ts +0 -27
- package/src/utils/declared-modules.ts +0 -99
- package/src/utils/dynamic.ts +0 -27
- package/src/utils/hmr-scripts.ts +0 -47
- package/src/utils/html-boundary.ts +0 -66
- package/src/utils/hydration-scripts.ts +0 -338
- package/src/utils/reachability-analyzer.ts +0 -593
- package/src/utils/react-mdx-loader-plugin.ts +0 -40
|
@@ -1,455 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* React HMR Strategy
|
|
3
|
-
*
|
|
4
|
-
* Handles hot module replacement for React components.
|
|
5
|
-
* Triggers module invalidation on changes to ensure fresh component re-renders.
|
|
6
|
-
*
|
|
7
|
-
* @module
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import path from 'node:path';
|
|
11
|
-
import { pathToFileURL } from 'node:url';
|
|
12
|
-
|
|
13
|
-
import { HmrStrategy, HmrStrategyType, type HmrAction } from '@ecopages/core/hmr/hmr-strategy';
|
|
14
|
-
import { defaultBuildAdapter } from '@ecopages/core/build/build-adapter';
|
|
15
|
-
import type { EcoBuildPlugin } from '@ecopages/core/build/build-types';
|
|
16
|
-
import { FileNotFoundError, fileSystem } from '@ecopages/file-system';
|
|
17
|
-
import { Logger } from '@ecopages/logger';
|
|
18
|
-
import type { DefaultHmrContext, EcoComponentConfig } from '@ecopages/core';
|
|
19
|
-
import type { CompileOptions } from '@mdx-js/mdx';
|
|
20
|
-
import { injectHmrHandler } from './utils/hmr-scripts.ts';
|
|
21
|
-
import { createClientGraphBoundaryPlugin } from './utils/client-graph-boundary-plugin.ts';
|
|
22
|
-
import { collectPageDeclaredModules, collectPageDeclaredModulesFromModule } from './utils/declared-modules.ts';
|
|
23
|
-
import type { ReactHmrPageMetadataCache } from './services/react-hmr-page-metadata-cache.ts';
|
|
24
|
-
|
|
25
|
-
const appLogger = new Logger('[ReactHmrStrategy]');
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Strategy for handling React component HMR updates.
|
|
29
|
-
*
|
|
30
|
-
* This strategy provides React-specific HMR handling by rebuilding entrypoints
|
|
31
|
-
* and injecting HMR acceptance handlers that trigger module invalidation.
|
|
32
|
-
*
|
|
33
|
-
* The processing steps are:
|
|
34
|
-
* 1. Check if any React entrypoints are registered
|
|
35
|
-
* 2. Rebuild all React entrypoints (the changed file could be a dependency)
|
|
36
|
-
* 3. Replace bare specifiers with runtime URLs
|
|
37
|
-
* 4. Inject HMR acceptance handler
|
|
38
|
-
* 5. Broadcast update events for each rebuilt entrypoint
|
|
39
|
-
*
|
|
40
|
-
* @remarks
|
|
41
|
-
* This strategy has higher priority than generic JsHmrStrategy, allowing it
|
|
42
|
-
* to handle React files specially while falling back to generic handling for
|
|
43
|
-
* non-React files.
|
|
44
|
-
*
|
|
45
|
-
* Future enhancement: Track dependencies using Bun's transpiler API to only
|
|
46
|
-
* rebuild affected entrypoints instead of all of them.
|
|
47
|
-
*
|
|
48
|
-
* @see https://bun.sh/docs/runtime/transpiler
|
|
49
|
-
*
|
|
50
|
-
* @example
|
|
51
|
-
* ```typescript
|
|
52
|
-
* const context = {
|
|
53
|
-
* getWatchedFiles: () => watchedFilesMap,
|
|
54
|
-
* getSpecifierMap: () => specifierMap,
|
|
55
|
-
* getDistDir: () => '/path/to/dist/_hmr',
|
|
56
|
-
* getPlugins: () => [],
|
|
57
|
-
* getSrcDir: () => '/path/to/src',
|
|
58
|
-
* getLayoutsDir: () => '/path/to/src/layouts'
|
|
59
|
-
* };
|
|
60
|
-
* const strategy = new ReactHmrStrategy(context);
|
|
61
|
-
* ```
|
|
62
|
-
*/
|
|
63
|
-
export class ReactHmrStrategy extends HmrStrategy {
|
|
64
|
-
readonly type = HmrStrategyType.INTEGRATION;
|
|
65
|
-
private mdxCompilerOptions?: CompileOptions;
|
|
66
|
-
private readonly knownEntrypoints = new Set<string>();
|
|
67
|
-
|
|
68
|
-
private async importNodePageModule(entrypointPath: string): Promise<{
|
|
69
|
-
default?: { config?: EcoComponentConfig };
|
|
70
|
-
config?: EcoComponentConfig;
|
|
71
|
-
}> {
|
|
72
|
-
const srcDir = this.context.getSrcDir();
|
|
73
|
-
const rootDir = path.dirname(srcDir);
|
|
74
|
-
const outdir = path.join(path.resolve(this.context.getDistDir(), '..', '..'), '.server-modules');
|
|
75
|
-
const fileBaseName = path.basename(entrypointPath, path.extname(entrypointPath));
|
|
76
|
-
const fileHash = fileSystem.hash(entrypointPath);
|
|
77
|
-
const outputFileName = `${fileBaseName}-${fileHash}.js`;
|
|
78
|
-
|
|
79
|
-
const buildResult = await defaultBuildAdapter.build({
|
|
80
|
-
entrypoints: [entrypointPath],
|
|
81
|
-
root: rootDir,
|
|
82
|
-
outdir,
|
|
83
|
-
target: 'node',
|
|
84
|
-
format: 'esm',
|
|
85
|
-
sourcemap: 'none',
|
|
86
|
-
splitting: false,
|
|
87
|
-
minify: false,
|
|
88
|
-
naming: outputFileName,
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
if (!buildResult.success) {
|
|
92
|
-
const details = buildResult.logs.map((log) => log.message).join(' | ');
|
|
93
|
-
throw new Error(`Error transpiling React HMR page module: ${details}`);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
const preferredOutputPath = path.join(outdir, outputFileName);
|
|
97
|
-
const compiledOutput =
|
|
98
|
-
buildResult.outputs.find((output) => output.path === preferredOutputPath)?.path ??
|
|
99
|
-
buildResult.outputs.find((output) => output.path.endsWith('.js'))?.path;
|
|
100
|
-
|
|
101
|
-
if (!compiledOutput) {
|
|
102
|
-
throw new Error(`No transpiled output generated for React HMR page module: ${entrypointPath}`);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
return (await import(pathToFileURL(compiledOutput).href)) as {
|
|
106
|
-
default?: { config?: EcoComponentConfig };
|
|
107
|
-
config?: EcoComponentConfig;
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Redirects `use-sync-external-store/shim` imports to React's built-in
|
|
113
|
-
* `useSyncExternalStore`.
|
|
114
|
-
*
|
|
115
|
-
* Libraries like React Aria still list `use-sync-external-store` as a
|
|
116
|
-
* dependency to support React 16/17. On React 18+ the `/shim` export is
|
|
117
|
-
* already a pass-through, but without this plugin esbuild would bundle
|
|
118
|
-
* the full CJS shim (including `process.env` branching) into the browser
|
|
119
|
-
* bundle. The plugin short-circuits the resolution so only a single clean
|
|
120
|
-
* ESM re-export is emitted.
|
|
121
|
-
*/
|
|
122
|
-
private createUseSyncExternalStoreShimPlugin(): EcoBuildPlugin {
|
|
123
|
-
return {
|
|
124
|
-
name: 'react-hmr-use-sync-external-store-shim',
|
|
125
|
-
setup(build) {
|
|
126
|
-
build.onResolve({ filter: /^use-sync-external-store\/shim(?:\/index\.js)?$/ }, () => ({
|
|
127
|
-
path: 'use-sync-external-store/shim',
|
|
128
|
-
namespace: 'ecopages-react-hmr-shim',
|
|
129
|
-
}));
|
|
130
|
-
|
|
131
|
-
build.onLoad(
|
|
132
|
-
{ filter: /^use-sync-external-store\/shim$/, namespace: 'ecopages-react-hmr-shim' },
|
|
133
|
-
() => ({
|
|
134
|
-
contents: "export { useSyncExternalStore } from 'react';",
|
|
135
|
-
loader: 'js',
|
|
136
|
-
}),
|
|
137
|
-
);
|
|
138
|
-
|
|
139
|
-
build.onLoad({ filter: /[\\/]use-sync-external-store[\\/]shim[\\/]index\.js$/ }, () => ({
|
|
140
|
-
contents: "export { useSyncExternalStore } from 'react';",
|
|
141
|
-
loader: 'js',
|
|
142
|
-
}));
|
|
143
|
-
|
|
144
|
-
build.onLoad(
|
|
145
|
-
{
|
|
146
|
-
filter: /[\\/]use-sync-external-store[\\/]cjs[\\/]use-sync-external-store-shim\.development\.js$/,
|
|
147
|
-
},
|
|
148
|
-
() => ({
|
|
149
|
-
contents: "export { useSyncExternalStore } from 'react';",
|
|
150
|
-
loader: 'js',
|
|
151
|
-
}),
|
|
152
|
-
);
|
|
153
|
-
},
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* Creates a new React HMR strategy instance.
|
|
159
|
-
*
|
|
160
|
-
* @param context - The HMR context providing access to watched files, plugins, build directories,
|
|
161
|
-
* and the layouts directory for detecting layout file changes that require full
|
|
162
|
-
* page reloads instead of module-level HMR updates.
|
|
163
|
-
* @param pageMetadataCache - React-only cache of declared browser modules discovered during
|
|
164
|
-
* server rendering. This avoids re-importing unchanged page modules
|
|
165
|
-
* during save-time Fast Refresh rebuilds.
|
|
166
|
-
* @param mdxCompilerOptions - Optional MDX compiler options for processing .mdx files
|
|
167
|
-
* @param explicitGraphEnabled - Enables explicit graph mode for React HMR bundling.
|
|
168
|
-
* In explicit mode, HMR builds omit AST server-only stripping plugins in React paths.
|
|
169
|
-
*/
|
|
170
|
-
constructor(
|
|
171
|
-
private context: DefaultHmrContext,
|
|
172
|
-
private pageMetadataCache: ReactHmrPageMetadataCache,
|
|
173
|
-
mdxCompilerOptions?: CompileOptions,
|
|
174
|
-
private explicitGraphEnabled = false,
|
|
175
|
-
) {
|
|
176
|
-
super();
|
|
177
|
-
this.mdxCompilerOptions = mdxCompilerOptions;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Returns build plugins for React HMR bundling.
|
|
182
|
-
*
|
|
183
|
-
* Includes the client graph boundary plugin to prevent undeclared imports
|
|
184
|
-
* (including `node:*`) from breaking the browser bundle.
|
|
185
|
-
*/
|
|
186
|
-
private getBuildPlugins(declaredModules?: string[]): EcoBuildPlugin[] {
|
|
187
|
-
const allowSpecifiers = [
|
|
188
|
-
'@ecopages/core',
|
|
189
|
-
'react',
|
|
190
|
-
'react-dom',
|
|
191
|
-
'react/jsx-runtime',
|
|
192
|
-
'react/jsx-dev-runtime',
|
|
193
|
-
'react-dom/client',
|
|
194
|
-
...Array.from(this.context.getSpecifierMap().keys()),
|
|
195
|
-
];
|
|
196
|
-
|
|
197
|
-
return [
|
|
198
|
-
createClientGraphBoundaryPlugin({
|
|
199
|
-
absWorkingDir: path.dirname(this.context.getSrcDir()),
|
|
200
|
-
alwaysAllowSpecifiers: allowSpecifiers,
|
|
201
|
-
declaredModules,
|
|
202
|
-
}),
|
|
203
|
-
...this.context.getPlugins(),
|
|
204
|
-
this.createUseSyncExternalStoreShimPlugin(),
|
|
205
|
-
];
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
private isReactEntrypoint(filePath: string): boolean {
|
|
209
|
-
if (filePath.endsWith('.tsx')) {
|
|
210
|
-
return true;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
return filePath.endsWith('.mdx') && this.mdxCompilerOptions !== undefined;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/**
|
|
217
|
-
* Determines if the file is a React/MDX entrypoint that's registered for HMR.
|
|
218
|
-
*
|
|
219
|
-
* @param filePath - Absolute path to the changed file
|
|
220
|
-
* @returns True if this is a registered React or MDX entrypoint
|
|
221
|
-
*/
|
|
222
|
-
matches(filePath: string): boolean {
|
|
223
|
-
const watchedFiles = this.context.getWatchedFiles();
|
|
224
|
-
appLogger.debug(`Checking ${filePath}. Watched: ${watchedFiles.size}`);
|
|
225
|
-
if (watchedFiles.size === 0) {
|
|
226
|
-
return false;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
return this.isReactEntrypoint(filePath);
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
/**
|
|
233
|
-
* Checks if a file is a layout file.
|
|
234
|
-
*
|
|
235
|
-
* Layout files require special HMR handling because they wrap multiple pages and affect
|
|
236
|
-
* the entire page structure. When a layout changes, we trigger a 'layout-update' event
|
|
237
|
-
* instead of a regular 'update' event, which instructs the browser to perform a full
|
|
238
|
-
* page reload (or clear cache and re-render) rather than attempting module-level HMR.
|
|
239
|
-
*
|
|
240
|
-
* @param filePath - Absolute path to the file
|
|
241
|
-
* @returns True if the file is in the layouts directory
|
|
242
|
-
*/
|
|
243
|
-
private isLayoutFile(filePath: string): boolean {
|
|
244
|
-
return filePath.startsWith(this.context.getLayoutsDir());
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* Processes a React file change by rebuilding all React entrypoints.
|
|
249
|
-
*
|
|
250
|
-
* For layout files, broadcasts a 'layout-update' event to trigger full page reload.
|
|
251
|
-
* For regular components/pages, broadcasts 'update' events for module-level HMR.
|
|
252
|
-
* When a page entrypoint is first registered, only that entrypoint is built.
|
|
253
|
-
* Subsequent file updates rebuild all watched React entrypoints as usual.
|
|
254
|
-
*
|
|
255
|
-
* @param _filePath - Absolute path to the changed file
|
|
256
|
-
* @returns Action to broadcast update events (layout-update for layouts, update for components)
|
|
257
|
-
*/
|
|
258
|
-
async process(_filePath: string): Promise<HmrAction> {
|
|
259
|
-
appLogger.debug(`Processing ${_filePath}`);
|
|
260
|
-
const watchedFiles = this.context.getWatchedFiles();
|
|
261
|
-
|
|
262
|
-
if (watchedFiles.size === 0) {
|
|
263
|
-
appLogger.debug(`No watched files`);
|
|
264
|
-
return { type: 'none' };
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
const isLayout = this.isLayoutFile(_filePath);
|
|
268
|
-
if (isLayout) {
|
|
269
|
-
appLogger.debug(`Detected layout file change: ${_filePath}`);
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
const entrypointsToBuild =
|
|
273
|
-
!this.knownEntrypoints.has(_filePath) && watchedFiles.has(_filePath)
|
|
274
|
-
? [[_filePath, watchedFiles.get(_filePath)!]]
|
|
275
|
-
: watchedFiles.entries();
|
|
276
|
-
this.knownEntrypoints.add(_filePath);
|
|
277
|
-
|
|
278
|
-
const updates: string[] = [];
|
|
279
|
-
for (const [entrypoint, outputUrl] of entrypointsToBuild) {
|
|
280
|
-
if (!this.isReactEntrypoint(entrypoint)) {
|
|
281
|
-
continue;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
appLogger.debug(`Bundling ${entrypoint}`);
|
|
285
|
-
const success = await this.bundleReactEntrypoint(entrypoint, outputUrl);
|
|
286
|
-
if (success) {
|
|
287
|
-
updates.push(outputUrl);
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
if (updates.length > 0) {
|
|
292
|
-
if (isLayout) {
|
|
293
|
-
appLogger.debug(`Layout update detected, sending layout-update event`);
|
|
294
|
-
return {
|
|
295
|
-
type: 'broadcast',
|
|
296
|
-
events: [
|
|
297
|
-
{
|
|
298
|
-
type: 'layout-update',
|
|
299
|
-
},
|
|
300
|
-
],
|
|
301
|
-
};
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
appLogger.debug(`Broadcasting ${updates.length} updates`);
|
|
305
|
-
return {
|
|
306
|
-
type: 'broadcast',
|
|
307
|
-
events: updates.map((path) => ({
|
|
308
|
-
type: 'update',
|
|
309
|
-
path,
|
|
310
|
-
timestamp: Date.now(),
|
|
311
|
-
})),
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
appLogger.debug(`No updates generated`);
|
|
316
|
-
return { type: 'none' };
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/**
|
|
320
|
-
* Bundles a single React/MDX entrypoint with HMR support.
|
|
321
|
-
*
|
|
322
|
-
* @param entrypointPath - Absolute path to the source file
|
|
323
|
-
* @param outputUrl - URL path for the bundled file
|
|
324
|
-
* @returns True if bundling was successful
|
|
325
|
-
*/
|
|
326
|
-
private async bundleReactEntrypoint(entrypointPath: string, outputUrl: string): Promise<boolean> {
|
|
327
|
-
try {
|
|
328
|
-
const isMdx = entrypointPath.endsWith('.mdx');
|
|
329
|
-
const srcDir = this.context.getSrcDir();
|
|
330
|
-
const relativePath = path.relative(srcDir, entrypointPath);
|
|
331
|
-
const relativePathJs = relativePath.replace(/\.(tsx?|jsx?|mdx)$/, '.js');
|
|
332
|
-
const encodedPathJs = this.encodeDynamicSegments(relativePathJs);
|
|
333
|
-
const outputPath = path.join(this.context.getDistDir(), encodedPathJs);
|
|
334
|
-
const tempDir = path.dirname(outputPath);
|
|
335
|
-
|
|
336
|
-
const declaredModules = this.pageMetadataCache.getDeclaredModules(entrypointPath)
|
|
337
|
-
? this.pageMetadataCache.getDeclaredModules(entrypointPath)!
|
|
338
|
-
: isMdx
|
|
339
|
-
? await collectPageDeclaredModules(entrypointPath)
|
|
340
|
-
: collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
|
|
341
|
-
const plugins = this.getBuildPlugins(declaredModules);
|
|
342
|
-
|
|
343
|
-
if (isMdx && this.mdxCompilerOptions) {
|
|
344
|
-
const { createReactMdxLoaderPlugin } = await import('./utils/react-mdx-loader-plugin.ts');
|
|
345
|
-
const mdxPlugin = createReactMdxLoaderPlugin(this.mdxCompilerOptions);
|
|
346
|
-
plugins.unshift(mdxPlugin);
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
const result = await defaultBuildAdapter.build({
|
|
350
|
-
entrypoints: [entrypointPath],
|
|
351
|
-
outdir: tempDir,
|
|
352
|
-
naming: `[name].[hash].tmp`,
|
|
353
|
-
target: 'browser',
|
|
354
|
-
format: 'esm',
|
|
355
|
-
sourcemap: 'none',
|
|
356
|
-
plugins,
|
|
357
|
-
minify: false,
|
|
358
|
-
external: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime', 'react-dom/client'],
|
|
359
|
-
});
|
|
360
|
-
|
|
361
|
-
if (!result.success) {
|
|
362
|
-
appLogger.error(`Failed to build ${entrypointPath}:`, result.logs);
|
|
363
|
-
return false;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
const tempFile = result.outputs[0]?.path;
|
|
367
|
-
if (!tempFile) {
|
|
368
|
-
appLogger.error(`No output file generated for ${entrypointPath}`);
|
|
369
|
-
return false;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
const processed = await this.processOutput(tempFile, outputPath, outputUrl);
|
|
373
|
-
return processed;
|
|
374
|
-
} catch (error) {
|
|
375
|
-
appLogger.error(`Error bundling ${entrypointPath}:`, error as Error);
|
|
376
|
-
return false;
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
/**
|
|
381
|
-
* Encodes dynamic route segments (brackets) in file paths.
|
|
382
|
-
* Converts `[slug]` to `_slug_` to avoid filesystem issues.
|
|
383
|
-
*/
|
|
384
|
-
private encodeDynamicSegments(filepath: string): string {
|
|
385
|
-
return filepath.replace(/\[([^\]]+)\]/g, '_$1_');
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
/**
|
|
389
|
-
* Processes bundled output by replacing specifiers and injecting HMR handler.
|
|
390
|
-
* Writes to temp file first, then renames atomically to avoid conflicts.
|
|
391
|
-
*
|
|
392
|
-
* @param tempPath - Path to the temporary bundled file
|
|
393
|
-
* @param finalPath - Final destination path
|
|
394
|
-
* @param url - URL path for logging
|
|
395
|
-
* @returns True if processing was successful
|
|
396
|
-
*/
|
|
397
|
-
private async processOutput(tempPath: string, finalPath: string, url: string): Promise<boolean> {
|
|
398
|
-
if (!fileSystem.exists(tempPath)) {
|
|
399
|
-
appLogger.debug(`Skipping stale temp output for ${url}: ${tempPath}`);
|
|
400
|
-
return false;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
try {
|
|
404
|
-
let code = await fileSystem.readFile(tempPath);
|
|
405
|
-
|
|
406
|
-
code = this.replaceBareSpecifiers(code);
|
|
407
|
-
code = injectHmrHandler(code);
|
|
408
|
-
|
|
409
|
-
await fileSystem.writeAsync(finalPath, code);
|
|
410
|
-
await fileSystem.removeAsync(tempPath).catch(() => {});
|
|
411
|
-
|
|
412
|
-
appLogger.debug(`Processed ${url} with HMR handler`);
|
|
413
|
-
return true;
|
|
414
|
-
} catch (error) {
|
|
415
|
-
if (
|
|
416
|
-
error instanceof FileNotFoundError ||
|
|
417
|
-
(error instanceof Error && error.message.includes('not found')) ||
|
|
418
|
-
(error instanceof Error && 'code' in error && error.code === 'ENOENT')
|
|
419
|
-
) {
|
|
420
|
-
appLogger.debug(`Skipping stale temp output for ${url}: ${tempPath}`);
|
|
421
|
-
await fileSystem.removeAsync(tempPath).catch(() => {});
|
|
422
|
-
return false;
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
appLogger.error(`Error processing output for ${url}:`, error as Error);
|
|
426
|
-
await fileSystem.removeAsync(tempPath).catch(() => {});
|
|
427
|
-
return false;
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
/**
|
|
432
|
-
* Replaces bare specifiers with runtime URLs.
|
|
433
|
-
*
|
|
434
|
-
* Handles both static imports and dynamic imports.
|
|
435
|
-
*
|
|
436
|
-
* @param code - The bundled code to transform
|
|
437
|
-
* @returns The transformed code with runtime URLs
|
|
438
|
-
*/
|
|
439
|
-
private replaceBareSpecifiers(code: string): string {
|
|
440
|
-
const specifierMap = this.context.getSpecifierMap();
|
|
441
|
-
|
|
442
|
-
if (specifierMap.size === 0) {
|
|
443
|
-
return code;
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
let result = code;
|
|
447
|
-
for (const [bareSpec, runtimeUrl] of specifierMap.entries()) {
|
|
448
|
-
const escaped = bareSpec.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
449
|
-
result = result.replace(new RegExp(`from\\s*["']${escaped}["']`, 'g'), `from "${runtimeUrl}"`);
|
|
450
|
-
result = result.replace(new RegExp(`import\\(["']${escaped}["']\\)`, 'g'), `import("${runtimeUrl}")`);
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
return result;
|
|
454
|
-
}
|
|
455
|
-
}
|