@ecopages/core 0.3.1 → 0.3.2

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 (39) hide show
  1. package/package.json +3 -3
  2. package/src/adapters/node/create-app.d.ts +12 -1
  3. package/src/adapters/node/create-app.js +18 -3
  4. package/src/adapters/node/runtime-host.d.ts +5 -0
  5. package/src/adapters/node/runtime-host.js +8 -1
  6. package/src/adapters/shared/hmr/hmr-manager.d.ts +12 -2
  7. package/src/adapters/shared/hmr/hmr-manager.js +20 -16
  8. package/src/adapters/shared/runtime/bind-runtime-server.js +3 -1
  9. package/src/adapters/shared/runtime/copy-runtime-public-dir.js +10 -9
  10. package/src/adapters/shared/runtime/port-manager.d.ts +6 -0
  11. package/src/adapters/shared/runtime/port-manager.js +16 -2
  12. package/src/assets/app-browser-client-build.js +1 -2
  13. package/src/assets/asset-processing-service/browser-runtime-entry-resolution.js +8 -8
  14. package/src/assets/asset-processing-service/browser-runtime-entry.factory.js +4 -4
  15. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +12 -8
  16. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +36 -16
  17. package/src/assets/asset-processing-service/processors/stylesheet/file-stylesheet.processor.js +11 -6
  18. package/src/assets/browser-asset-output.d.ts +19 -0
  19. package/src/assets/browser-asset-output.js +30 -0
  20. package/src/assets/hashed-browser-asset.d.ts +8 -6
  21. package/src/assets/hashed-browser-asset.js +8 -6
  22. package/src/build/build-graph.js +2 -2
  23. package/src/build/preserve-import-meta-transform.js +2 -2
  24. package/src/build/rolldown/app-package-declarations.js +3 -3
  25. package/src/build/rolldown/rolldown-adapter-helpers.js +3 -3
  26. package/src/build/rolldown/server-side-css-shim-plugin.js +3 -3
  27. package/src/build/server-bundle-publication.js +4 -5
  28. package/src/config/config-module-files.js +2 -3
  29. package/src/diagnostics/startup-trace.js +2 -5
  30. package/src/html-pages/html-page-module-scripts.js +4 -3
  31. package/src/html-pages/html-page-renderer.js +2 -3
  32. package/src/plugins/component-import-discovery.js +4 -4
  33. package/src/plugins/foreign-jsx-override-plugin.js +2 -2
  34. package/src/plugins/tsconfig-import-resolver.js +12 -12
  35. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +0 -17
  36. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +0 -23
  37. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +2 -2
  38. package/src/route-renderer/page-loading/page-dependency-bundling.js +5 -5
  39. package/src/router/server/route-registry.js +1 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/core",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Core package for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@clack/prompts": "^1.7.0",
24
- "@ecopages/file-system": "0.3.1",
24
+ "@ecopages/file-system": "0.3.2",
25
25
  "@ecopages/logger": "^0.2.3",
26
26
  "@ecopages/scripts-injector": "^0.1.5",
27
27
  "@jridgewell/remapping": "^2.3.5",
@@ -35,7 +35,7 @@
35
35
  "ws": "^8.20.1"
36
36
  },
37
37
  "peerDependencies": {
38
- "@ecopages/dev-toolbar": "0.3.1"
38
+ "@ecopages/dev-toolbar": "0.3.2"
39
39
  },
40
40
  "peerDependenciesMeta": {
41
41
  "@ecopages/dev-toolbar": {
@@ -58,6 +58,15 @@ export declare class EcopagesApp implements AsyncDisposable {
58
58
  /** @remarks Initialized by the first `fetch()` or `start()` call and exposed for host-level request middleware. */
59
59
  serverAdapter: NodeServerAdapter | undefined;
60
60
  private lifecycle;
61
+ /**
62
+ * Counts `stop()` calls.
63
+ *
64
+ * @remarks
65
+ * A `start()` or `fetch()` that waits for a running stop compares it after the
66
+ * wait, so a later `stop()` cancels it instead of sharing the first stop's promise
67
+ * and letting it start a new session afterwards.
68
+ */
69
+ private stopCount;
61
70
  constructor(options: EcopagesAppRuntimeOptions, dependencies: EcopagesAppDependencies);
62
71
  private register;
63
72
  get<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
@@ -173,7 +182,9 @@ export declare class EcopagesApp implements AsyncDisposable {
173
182
  *
174
183
  * @remarks
175
184
  * Resolves without a server when `stop()` is called before startup finishes;
176
- * that startup does not continue.
185
+ * that startup does not continue. It still rejects when the step in flight
186
+ * fails, such as a bind failure. A call made while `stop()` runs waits for it,
187
+ * and resolves without a server when another `stop()` arrives in that wait.
177
188
  */
178
189
  start(onAppStart?: OnAppStartCallback): Promise<NodeServerInstance | void>;
179
190
  private bootServer;
@@ -51,6 +51,15 @@ export class EcopagesApp {
51
51
  /** @remarks Initialized by the first `fetch()` or `start()` call and exposed for host-level request middleware. */
52
52
  serverAdapter;
53
53
  lifecycle = { phase: 'idle' };
54
+ /**
55
+ * Counts `stop()` calls.
56
+ *
57
+ * @remarks
58
+ * A `start()` or `fetch()` that waits for a running stop compares it after the
59
+ * wait, so a later `stop()` cancels it instead of sharing the first stop's promise
60
+ * and letting it start a new session afterwards.
61
+ */
62
+ stopCount = 0;
54
63
  constructor(options, dependencies) {
55
64
  this.runtimeLabel = resolveProcessRuntimeLabel();
56
65
  this.appConfig = options.appConfig;
@@ -333,7 +342,9 @@ export class EcopagesApp {
333
342
  *
334
343
  * @remarks
335
344
  * Resolves without a server when `stop()` is called before startup finishes;
336
- * that startup does not continue.
345
+ * that startup does not continue. It still rejects when the step in flight
346
+ * fails, such as a bind failure. A call made while `stop()` runs waits for it,
347
+ * and resolves without a server when another `stop()` arrives in that wait.
337
348
  */
338
349
  async start(onAppStart) {
339
350
  if (onAppStart) {
@@ -388,7 +399,10 @@ export class EcopagesApp {
388
399
  return this.isActive(session) ? session : undefined;
389
400
  }
390
401
  if (current.phase === 'stopping') {
402
+ const stopCount = this.stopCount;
391
403
  await current.stopped;
404
+ if (this.stopCount !== stopCount)
405
+ return undefined;
392
406
  return await this.getReadySession();
393
407
  }
394
408
  const ready = this.initializeSession();
@@ -412,7 +426,7 @@ export class EcopagesApp {
412
426
  const { build, preview, serveOnly, keepGoing } = this.cliArgs;
413
427
  if (preview && serveOnly) {
414
428
  const previewOrigin = await session.adapter.servePreviewOnly();
415
- if (previewOrigin)
429
+ if (previewOrigin && this.isActive(session))
416
430
  await this.notifyListening(previewOrigin);
417
431
  return;
418
432
  }
@@ -420,7 +434,7 @@ export class EcopagesApp {
420
434
  appLogger.debugTime('Building static pages');
421
435
  const previewOrigin = await session.adapter.buildStatic({ preview, keepGoing });
422
436
  appLogger.debugTimeEnd('Building static pages');
423
- if (preview && previewOrigin)
437
+ if (preview && previewOrigin && this.isActive(session))
424
438
  await this.notifyListening(previewOrigin);
425
439
  return;
426
440
  }
@@ -523,6 +537,7 @@ export class EcopagesApp {
523
537
  * releases whatever that step created.
524
538
  */
525
539
  stop(force = true) {
540
+ this.stopCount += 1;
526
541
  const current = this.lifecycle;
527
542
  if (current.phase === 'idle' || current.phase === 'stopped')
528
543
  return Promise.resolve();
@@ -45,6 +45,11 @@ export declare class NodeRuntimeHost {
45
45
  * Client disconnects are treated as normal aborts and are not logged. Other
46
46
  * failures here (the response write, or an uninitialised adapter) are logged
47
47
  * with their stack and answered with 500.
48
+ *
49
+ * The hostname is resolved to its first address before `listen()`, which is
50
+ * what Node does internally. Bun instead tries every address the name resolves
51
+ * to, so when `localhost:<port>` is taken on `::1` it binds `127.0.0.1` and
52
+ * never reports `EADDRINUSE`, leaving two servers behind one origin.
48
53
  */
49
54
  start(serveOptions: NodeRuntimeServeOptions): Promise<NodeServerInstance>;
50
55
  /**
@@ -1,3 +1,4 @@
1
+ import { lookup } from 'node:dns/promises';
1
2
  import { createServer } from 'node:http';
2
3
  import { DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT } from '../../constants.js';
3
4
  import { appLogger } from '../../global/app-logger.js';
@@ -38,10 +39,16 @@ export class NodeRuntimeHost {
38
39
  * Client disconnects are treated as normal aborts and are not logged. Other
39
40
  * failures here (the response write, or an uninitialised adapter) are logged
40
41
  * with their stack and answered with 500.
42
+ *
43
+ * The hostname is resolved to its first address before `listen()`, which is
44
+ * what Node does internally. Bun instead tries every address the name resolves
45
+ * to, so when `localhost:<port>` is taken on `::1` it binds `127.0.0.1` and
46
+ * never reports `EADDRINUSE`, leaving two servers behind one origin.
41
47
  */
42
48
  async start(serveOptions) {
43
49
  const hostname = String(serveOptions.hostname ?? DEFAULT_ECOPAGES_HOSTNAME);
44
50
  const port = Number(serveOptions.port ?? DEFAULT_ECOPAGES_PORT);
51
+ const { address } = await lookup(hostname);
45
52
  let server;
46
53
  server = this.serverFactory(async (req, res) => {
47
54
  try {
@@ -67,7 +74,7 @@ export class NodeRuntimeHost {
67
74
  });
68
75
  await new Promise((resolve, reject) => {
69
76
  server.once('error', reject);
70
- server.listen(port, hostname, () => {
77
+ server.listen(port, address, () => {
71
78
  server.off('error', reject);
72
79
  resolve();
73
80
  });
@@ -24,6 +24,14 @@ export declare class HmrManager implements IHmrManager {
24
24
  private readonly fallbackStrategy;
25
25
  private readonly scriptEntrypointChangeHandlers;
26
26
  private readonly registeredScriptReloadRequired;
27
+ /**
28
+ * Error messages of changed files whose strategy or script-change handler threw, by file path.
29
+ *
30
+ * @remarks
31
+ * An entry stays until that file processes without error, because nothing records it again on a later
32
+ * request the way a dev-transform failure is.
33
+ */
34
+ private readonly fileChangeErrors;
27
35
  protected readonly entrypointRegistry: DevTransformEntrypointRegistry;
28
36
  protected readonly browserBundleService: BrowserBundleService;
29
37
  protected readonly invalidationService: DevelopmentInvalidationService;
@@ -98,11 +106,13 @@ export declare class HmrManager implements IHmrManager {
98
106
  getWatchedFiles(): Map<string, string>;
99
107
  getRegisteredEntrypoints(): ReadonlyMap<string, ResolvedHmrEntrypoint>;
100
108
  /**
101
- * Sends a browser that just connected the build errors of modules that still fail to transpile.
109
+ * Sends a browser that just connected the build errors of modules that still fail to transpile, and of
110
+ * changed files whose last processing failed.
102
111
  *
103
112
  * @remarks
104
113
  * A build error is broadcast while the failing module is served, which can happen before the page's HMR
105
- * socket connects. Without this replay that browser would never show the error.
114
+ * socket connects. A change error can share its batch with a `reload`, which drops the error shown before
115
+ * it. Without this replay that browser would never show the error.
106
116
  */
107
117
  sendPendingBuildErrors(client: {
108
118
  send(payload: string): void;
@@ -31,6 +31,14 @@ export class HmrManager {
31
31
  fallbackStrategy = new DefaultHmrStrategy();
32
32
  scriptEntrypointChangeHandlers = [];
33
33
  registeredScriptReloadRequired = new Set();
34
+ /**
35
+ * Error messages of changed files whose strategy or script-change handler threw, by file path.
36
+ *
37
+ * @remarks
38
+ * An entry stays until that file processes without error, because nothing records it again on a later
39
+ * request the way a dev-transform failure is.
40
+ */
41
+ fileChangeErrors = new Map();
34
42
  entrypointRegistry;
35
43
  browserBundleService;
36
44
  invalidationService;
@@ -196,10 +204,13 @@ export class HmrManager {
196
204
  for (const filePath of uniqueFilePaths) {
197
205
  try {
198
206
  events.push(...(await this.processFileChange(filePath)));
207
+ this.fileChangeErrors.delete(filePath);
199
208
  }
200
209
  catch (error) {
201
210
  appLogger.error(error instanceof Error ? error : new Error(String(error)));
202
- events.push({ type: 'error', message: error instanceof Error ? error.message : String(error) });
211
+ const message = error instanceof Error ? error.message : String(error);
212
+ this.fileChangeErrors.set(filePath, message);
213
+ events.push({ type: 'error', message });
203
214
  }
204
215
  }
205
216
  this.broadcastBatchEvents(events, options, uniqueFilePaths);
@@ -279,18 +290,8 @@ export class HmrManager {
279
290
  */
280
291
  async runRegisteredEntrypointChangeHandlers(filePath) {
281
292
  for (const handler of this.scriptEntrypointChangeHandlers) {
282
- try {
283
- const result = await handler(filePath);
284
- if (result === true) {
285
- this.registeredScriptReloadRequired.add(path.resolve(filePath));
286
- }
287
- }
288
- catch (error) {
289
- const message = error instanceof Error
290
- ? error.message
291
- : `Failed to handle registered script entrypoint change for ${filePath}: ${String(error)}`;
292
- this.broadcast({ type: 'error', message });
293
- throw error;
293
+ if ((await handler(filePath)) === true) {
294
+ this.registeredScriptReloadRequired.add(path.resolve(filePath));
294
295
  }
295
296
  }
296
297
  }
@@ -316,14 +317,16 @@ export class HmrManager {
316
317
  return this.entrypointRegistry.getRegisteredEntrypoints();
317
318
  }
318
319
  /**
319
- * Sends a browser that just connected the build errors of modules that still fail to transpile.
320
+ * Sends a browser that just connected the build errors of modules that still fail to transpile, and of
321
+ * changed files whose last processing failed.
320
322
  *
321
323
  * @remarks
322
324
  * A build error is broadcast while the failing module is served, which can happen before the page's HMR
323
- * socket connects. Without this replay that browser would never show the error.
325
+ * socket connects. A change error can share its batch with a `reload`, which drops the error shown before
326
+ * it. Without this replay that browser would never show the error.
324
327
  */
325
328
  sendPendingBuildErrors(client) {
326
- for (const message of this.devTransformServer.getFailureMessages()) {
329
+ for (const message of [...this.devTransformServer.getFailureMessages(), ...this.fileChangeErrors.values()]) {
327
330
  client.send(JSON.stringify({ type: 'error', message }));
328
331
  }
329
332
  }
@@ -355,6 +358,7 @@ export class HmrManager {
355
358
  this.readyRuntimes.clear();
356
359
  this.scriptEntrypointChangeHandlers.length = 0;
357
360
  this.registeredScriptReloadRequired.clear();
361
+ this.fileChangeErrors.clear();
358
362
  this.entrypointRegistry.clearAll();
359
363
  this.devTransformServer.reset();
360
364
  this.buildInputIndex.clearConsumer('entrypoint');
@@ -1,4 +1,5 @@
1
- import { PortManager } from './port-manager.js';
1
+ import { DEFAULT_ECOPAGES_HOSTNAME } from '../../../constants.js';
2
+ import { isPortAvailable, PortManager } from './port-manager.js';
2
3
  import { appLogger } from '../../../global/app-logger.js';
3
4
  /**
4
5
  * Starts a runtime server, optionally negotiating a fallback port via
@@ -27,6 +28,7 @@ export async function bindRuntimeServer(runtimeHost, options) {
27
28
  activeRuntimeOrigin = runtimeOrigin;
28
29
  return boundPort;
29
30
  },
31
+ probePort: (port) => isPortAvailable(port, options.serveOptions.hostname ?? DEFAULT_ECOPAGES_HOSTNAME),
30
32
  warn: (message) => appLogger.warn(message),
31
33
  });
32
34
  const boundPort = await portManager.bind({
@@ -1,9 +1,8 @@
1
- import { lstatSync, readdirSync, readlinkSync } from 'node:fs';
2
1
  import path from 'node:path';
3
2
  import { fileSystem } from '@ecopages/file-system';
4
3
  function tryLstat(filePath) {
5
4
  try {
6
- return lstatSync(filePath);
5
+ return fileSystem.lstat(filePath);
7
6
  }
8
7
  catch (error) {
9
8
  if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
@@ -17,7 +16,7 @@ export function copyRuntimePublicFileIfChanged(sourcePath, destinationPath) {
17
16
  return;
18
17
  }
19
18
  fileSystem.ensureDir(path.dirname(destinationPath));
20
- const destinationIsSymbolicLink = tryLstat(destinationPath)?.isSymbolicLink() ?? false;
19
+ const destinationIsSymbolicLink = tryLstat(destinationPath)?.isSymbolicLink ?? false;
21
20
  if (destinationIsSymbolicLink) {
22
21
  fileSystem.remove(destinationPath);
23
22
  }
@@ -42,18 +41,20 @@ export async function copyRuntimePublicFile(sourcePath, destinationPath) {
42
41
  */
43
42
  export function copyRuntimePublicDirIfChanged(sourceDir, destinationDir) {
44
43
  fileSystem.ensureDir(destinationDir);
45
- for (const entry of readdirSync(sourceDir, { withFileTypes: true })) {
44
+ for (const entry of fileSystem.readdir(sourceDir)) {
46
45
  const sourcePath = path.join(sourceDir, entry.name);
47
46
  const destinationPath = path.join(destinationDir, entry.name);
48
- if (entry.isDirectory()) {
47
+ if (entry.isDirectory) {
49
48
  copyRuntimePublicDirIfChanged(sourcePath, destinationPath);
50
49
  continue;
51
50
  }
52
- if (entry.isSymbolicLink()) {
53
- const sourceTarget = readlinkSync(sourcePath);
51
+ if (entry.isSymbolicLink) {
52
+ const sourceTarget = fileSystem.readlink(sourcePath);
54
53
  const destinationStats = tryLstat(destinationPath);
55
54
  const destinationExists = destinationStats !== undefined;
56
- const destinationTarget = destinationStats?.isSymbolicLink() ? readlinkSync(destinationPath) : undefined;
55
+ const destinationTarget = destinationStats?.isSymbolicLink
56
+ ? fileSystem.readlink(destinationPath)
57
+ : undefined;
57
58
  if (sourceTarget === destinationTarget) {
58
59
  continue;
59
60
  }
@@ -63,7 +64,7 @@ export function copyRuntimePublicDirIfChanged(sourceDir, destinationDir) {
63
64
  fileSystem.copyFile(sourcePath, destinationPath);
64
65
  continue;
65
66
  }
66
- if (!entry.isFile()) {
67
+ if (!entry.isFile) {
67
68
  continue;
68
69
  }
69
70
  copyRuntimePublicFileIfChanged(sourcePath, destinationPath);
@@ -7,6 +7,12 @@ export declare function isPortInUseError(error: unknown): boolean;
7
7
  * short-lived Node `net.Server`.
8
8
  *
9
9
  * @remarks
10
+ * `hostname` is resolved to a single address first and the probe binds that
11
+ * address, mirroring what the server bind does. Passing the hostname straight
12
+ * to `listen()` makes some runtimes (Bun) try every resolved address, so a
13
+ * taken port can be reported as free. A hostname that does not resolve reports
14
+ * the port as unavailable.
15
+ *
10
16
  * A successful probe only guarantees the port was free at probe time; callers
11
17
  * must still handle EADDRINUSE when they actually bind, since release races
12
18
  * can flip the answer between probe and bind.
@@ -1,3 +1,4 @@
1
+ import { lookup } from 'node:dns/promises';
1
2
  import { createServer as createNetServer } from 'node:net';
2
3
  import { createClackDefaultPrompt } from './port-manager-default-prompt.js';
3
4
  /**
@@ -14,18 +15,31 @@ function sleep(ms) {
14
15
  * short-lived Node `net.Server`.
15
16
  *
16
17
  * @remarks
18
+ * `hostname` is resolved to a single address first and the probe binds that
19
+ * address, mirroring what the server bind does. Passing the hostname straight
20
+ * to `listen()` makes some runtimes (Bun) try every resolved address, so a
21
+ * taken port can be reported as free. A hostname that does not resolve reports
22
+ * the port as unavailable.
23
+ *
17
24
  * A successful probe only guarantees the port was free at probe time; callers
18
25
  * must still handle EADDRINUSE when they actually bind, since release races
19
26
  * can flip the answer between probe and bind.
20
27
  */
21
- export function isPortAvailable(port, hostname = '127.0.0.1') {
28
+ export async function isPortAvailable(port, hostname = '127.0.0.1') {
29
+ let address;
30
+ try {
31
+ ({ address } = await lookup(hostname));
32
+ }
33
+ catch {
34
+ return false;
35
+ }
22
36
  return new Promise((resolve) => {
23
37
  const tester = createNetServer();
24
38
  tester.once('error', () => resolve(false));
25
39
  tester.once('listening', () => {
26
40
  tester.close(() => resolve(true));
27
41
  });
28
- tester.listen(port, hostname);
42
+ tester.listen(port, address);
29
43
  });
30
44
  }
31
45
  const PORT_RELEASE_RACE_RETRIES = 2;
@@ -1,6 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { contentHash } from '../utils/content-hash.js';
3
- import { realpathSync } from 'node:fs';
4
3
  import path from 'node:path';
5
4
  import { fileSystem } from '@ecopages/file-system';
6
5
  import { getBuildEntryOutput, collectBuildEntryInputPaths } from '../build/build-graph.js';
@@ -380,7 +379,7 @@ function collectHtmlScriptUrls(appConfig, result, htmlEntryNames) {
380
379
  for (const [script, entryName] of htmlEntryNames) {
381
380
  const output = getBuildEntryOutput(result, entryName, appConfig.rootDir);
382
381
  if (output) {
383
- urls.set(realpathSync(script), `/${path.relative(appConfig.absolutePaths.distDir, output).split(path.sep).join('/')}`);
382
+ urls.set(fileSystem.realpath(script), `/${path.relative(appConfig.absolutePaths.distDir, output).split(path.sep).join('/')}`);
384
383
  }
385
384
  }
386
385
  return urls;
@@ -1,5 +1,5 @@
1
- import fs from 'node:fs';
2
1
  import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { ResolverFactory } from 'oxc-resolver';
5
5
  import { isBarePackageImportSpecifier } from '../../plugins/tsconfig-import-resolver.js';
@@ -43,12 +43,12 @@ function resolveLegacyPackageModuleEntry(options) {
43
43
  }
44
44
  try {
45
45
  const packageJsonPath = options.requireFromRoot.resolve(`${packageRoot}/package.json`);
46
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
46
+ const packageJson = JSON.parse(fileSystem.readFileSync(packageJsonPath));
47
47
  if (packageJson.exports !== undefined || typeof packageJson.module !== 'string') {
48
48
  return undefined;
49
49
  }
50
50
  const modulePath = path.resolve(path.dirname(packageJsonPath), packageJson.module);
51
- return fs.existsSync(modulePath) ? modulePath : undefined;
51
+ return fileSystem.exists(modulePath) ? modulePath : undefined;
52
52
  }
53
53
  catch {
54
54
  return undefined;
@@ -92,7 +92,7 @@ export function resolveBrowserRuntimeEntryPath(options) {
92
92
  : resolvedPath.endsWith('.cts')
93
93
  ? `${resolvedPath.slice(0, -4)}.ts`
94
94
  : undefined;
95
- return esmSibling && fs.existsSync(esmSibling) ? esmSibling : resolvedPath;
95
+ return esmSibling && fileSystem.exists(esmSibling) ? esmSibling : resolvedPath;
96
96
  }
97
97
  catch {
98
98
  return undefined;
@@ -142,8 +142,8 @@ export function resolveBrowserRuntimeEntryImport(options) {
142
142
  export function inferBrowserRuntimeDefaultExportPolicy(options) {
143
143
  const { specifier, requireFromRoot, rootDir } = options;
144
144
  const entryPath = resolveBrowserRuntimeEntryPath({ specifier, requireFromRoot, rootDir });
145
- if (entryPath && fs.existsSync(entryPath)) {
146
- const source = fs.readFileSync(entryPath, 'utf8');
145
+ if (entryPath && fileSystem.exists(entryPath)) {
146
+ const source = fileSystem.readFileSync(entryPath);
147
147
  if (ESM_DEFAULT_EXPORT.test(source)) {
148
148
  return 'emit-default';
149
149
  }
@@ -171,10 +171,10 @@ export function inferBrowserRuntimeDefaultExportPolicy(options) {
171
171
  * files does not emit named ESM bindings such as `jsx`.
172
172
  */
173
173
  export function browserRuntimeEntryHasEsmExports(entryPath) {
174
- if (!entryPath || !fs.existsSync(entryPath)) {
174
+ if (!entryPath || !fileSystem.exists(entryPath)) {
175
175
  return true;
176
176
  }
177
- const source = fs.readFileSync(entryPath, 'utf8');
177
+ const source = fileSystem.readFileSync(entryPath);
178
178
  return ESM_DEFAULT_EXPORT.test(source) || ESM_NAMED_EXPORT.test(source);
179
179
  }
180
180
  /**
@@ -1,5 +1,5 @@
1
- import fs from 'node:fs';
2
1
  import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
3
  import { createRequire } from 'node:module';
4
4
  import { DEFAULT_ECOPAGES_WORK_DIR } from '../../constants.js';
5
5
  import { browserRuntimeEntryHasEsmExports, inferBrowserRuntimeDefaultExportPolicy, listBrowserRuntimeCjsExportNames, resolveBrowserRuntimeEntryImport, resolveBrowserRuntimeEntryPath, } from './browser-runtime-entry-resolution.js';
@@ -23,7 +23,7 @@ export function createBrowserRuntimeEntryModule(options) {
23
23
  const rootDir = options.rootDir ?? process.cwd();
24
24
  const workDir = options.workDir ?? path.join(rootDir, DEFAULT_ECOPAGES_WORK_DIR);
25
25
  const artifactsDir = path.join(workDir, '.browser-runtime-entries', options.cacheDirName ?? 'ecopages-browser-runtime');
26
- fs.mkdirSync(artifactsDir, { recursive: true });
26
+ fileSystem.ensureDir(artifactsDir);
27
27
  const requireFromRoot = createRequire(path.join(rootDir, 'package.json'));
28
28
  const seenExports = new Set();
29
29
  const statements = [];
@@ -60,8 +60,8 @@ export function createBrowserRuntimeEntryModule(options) {
60
60
  }
61
61
  }
62
62
  const content = statements.join('\n');
63
- if (!fs.existsSync(filePath) || fs.readFileSync(filePath, 'utf-8') !== content) {
64
- fs.writeFileSync(filePath, content, 'utf-8');
63
+ if (!fileSystem.exists(filePath) || fileSystem.readFileSync(filePath) !== content) {
64
+ fileSystem.write(filePath, content);
65
65
  }
66
66
  return filePath;
67
67
  }
@@ -21,11 +21,14 @@ export declare class FileScriptProcessor extends BaseScriptProcessor<FileScriptA
21
21
  processGrouped(deps: FileScriptAsset[]): Promise<ProcessedAsset[]>;
22
22
  /**
23
23
  * @remarks
24
- * With HMR active, bundled scripts are built and watched by the HMR manager, which emits ES
25
- * modules. In production, `bundle: false` scripts are written under a hash of their bytes.
26
- * In development they are copied to their source-relative path so HMR can refresh them.
27
- * `classic` scripts are compiled on their own as classic scripts. Vendor runtimes keep their
28
- * stable names.
24
+ * With HMR active, a bundled script is built and watched by the HMR manager, which emits an ES
25
+ * module and serves the dev-transform URL. In production, a `bundle: false` script is written
26
+ * under a hash of its bytes. In development, a non-classic `bundle: false` file inside `srcDir`
27
+ * is copied to its source-relative path. A classic script inside `srcDir` is compiled and written
28
+ * under that path with a `.js` name. A file outside `srcDir` has no such path that stays inside
29
+ * `dist`: an unbundled or classic script is written under a content hash, and a bundled script
30
+ * is emitted in `dist/assets` under the bundler's `[name]-[hash]` name. Vendor runtimes inside
31
+ * `src` keep their stable names.
29
32
  */
30
33
  process(dep: FileScriptAsset): Promise<ProcessedAsset>;
31
34
  private processWithHmr;
@@ -33,9 +36,10 @@ export declare class FileScriptProcessor extends BaseScriptProcessor<FileScriptA
33
36
  private processBundledScript;
34
37
  /**
35
38
  * @remarks
36
- * The output keeps the source path and name, with a TypeScript extension turned into `.js`, as a
37
- * copied classic `.js` does. A second source file for the same output is rejected while the first
38
- * still exists, so a last write cannot silently win.
39
+ * The output keeps the source path and name when the file is inside `srcDir`, with a TypeScript
40
+ * extension turned into `.js`, as a copied classic `.js` does. A file outside `srcDir` is written
41
+ * under a content hash in `dist/assets`. A second source file for the same output is rejected while
42
+ * the first still exists, so a last write cannot silently win.
39
43
  *
40
44
  * @throws When the file cannot be a classic script, or another existing file is emitted to its output.
41
45
  */
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path';
2
- import { RESOLVED_ASSETS_DIR } from '../../../../constants.js';
3
2
  import { fileSystem } from '@ecopages/file-system';
3
+ import { assertBrowserOutputInsideDist, sourceRelativeBrowserAssetPath } from '../../../browser-asset-output.js';
4
4
  import { writeHashedBrowserAsset } from '../../../hashed-browser-asset.js';
5
5
  import { BaseScriptProcessor } from '../base/base-script-processor.js';
6
6
  import { classicScriptOutputName, compileClassicScript } from './classic-script-compiler.js';
@@ -50,11 +50,14 @@ export class FileScriptProcessor extends BaseScriptProcessor {
50
50
  }
51
51
  /**
52
52
  * @remarks
53
- * With HMR active, bundled scripts are built and watched by the HMR manager, which emits ES
54
- * modules. In production, `bundle: false` scripts are written under a hash of their bytes.
55
- * In development they are copied to their source-relative path so HMR can refresh them.
56
- * `classic` scripts are compiled on their own as classic scripts. Vendor runtimes keep their
57
- * stable names.
53
+ * With HMR active, a bundled script is built and watched by the HMR manager, which emits an ES
54
+ * module and serves the dev-transform URL. In production, a `bundle: false` script is written
55
+ * under a hash of its bytes. In development, a non-classic `bundle: false` file inside `srcDir`
56
+ * is copied to its source-relative path. A classic script inside `srcDir` is compiled and written
57
+ * under that path with a `.js` name. A file outside `srcDir` has no such path that stays inside
58
+ * `dist`: an unbundled or classic script is written under a content hash, and a bundled script
59
+ * is emitted in `dist/assets` under the bundler's `[name]-[hash]` name. Vendor runtimes inside
60
+ * `src` keep their stable names.
58
61
  */
59
62
  async process(dep) {
60
63
  const hmrManager = this.getActiveHmrManager();
@@ -84,13 +87,15 @@ export class FileScriptProcessor extends BaseScriptProcessor {
84
87
  };
85
88
  }
86
89
  processUnbundledScript(dep, content) {
87
- const outFilepath = path.relative(this.appConfig.absolutePaths.srcDir, dep.filepath);
90
+ const outFilepath = sourceRelativeBrowserAssetPath(this.appConfig.absolutePaths.srcDir, dep.filepath);
88
91
  const output = dep.classic ? this.emitClassicScript(dep, outFilepath, content.toString()) : undefined;
89
92
  let filepath = output?.filepath;
90
93
  if (!dep.classic && !dep.inline) {
91
- if (dep.packageRole === 'runtime' || !this.isProduction) {
92
- filepath = path.join(this.getAssetsDir(), outFilepath);
93
- fileSystem.copyFile(dep.filepath, filepath);
94
+ if (outFilepath && (dep.packageRole === 'runtime' || !this.isProduction)) {
95
+ const destination = path.join(this.getAssetsDir(), outFilepath);
96
+ assertBrowserOutputInsideDist(this.appConfig.absolutePaths.distDir, destination);
97
+ fileSystem.copyFile(dep.filepath, destination);
98
+ filepath = destination;
94
99
  }
95
100
  else {
96
101
  filepath = writeHashedBrowserAsset({
@@ -114,12 +119,17 @@ export class FileScriptProcessor extends BaseScriptProcessor {
114
119
  };
115
120
  }
116
121
  async processBundledScript(dep) {
117
- const relativeFilepath = path.relative(this.appConfig.absolutePaths.srcDir, dep.filepath);
118
- const outdirPath = path.join(this.appConfig.absolutePaths.distDir, RESOLVED_ASSETS_DIR, relativeFilepath);
122
+ const relativeFilepath = sourceRelativeBrowserAssetPath(this.appConfig.absolutePaths.srcDir, dep.filepath);
123
+ const outdir = relativeFilepath
124
+ ? path.dirname(path.join(this.getAssetsDir(), relativeFilepath))
125
+ : this.getAssetsDir();
126
+ if (relativeFilepath) {
127
+ assertBrowserOutputInsideDist(this.appConfig.absolutePaths.distDir, outdir);
128
+ }
119
129
  const bundlerOptions = this.getBundlerOptions(dep);
120
130
  const bundledOutput = await this.bundleScript({
121
131
  entrypoint: dep.filepath,
122
- outdir: path.dirname(outdirPath),
132
+ outdir,
123
133
  minify: this.isProduction,
124
134
  ...bundlerOptions,
125
135
  plugins: bundlerOptions.plugins,
@@ -139,9 +149,10 @@ export class FileScriptProcessor extends BaseScriptProcessor {
139
149
  }
140
150
  /**
141
151
  * @remarks
142
- * The output keeps the source path and name, with a TypeScript extension turned into `.js`, as a
143
- * copied classic `.js` does. A second source file for the same output is rejected while the first
144
- * still exists, so a last write cannot silently win.
152
+ * The output keeps the source path and name when the file is inside `srcDir`, with a TypeScript
153
+ * extension turned into `.js`, as a copied classic `.js` does. A file outside `srcDir` is written
154
+ * under a content hash in `dist/assets`. A second source file for the same output is rejected while
155
+ * the first still exists, so a last write cannot silently win.
145
156
  *
146
157
  * @throws When the file cannot be a classic script, or another existing file is emitted to its output.
147
158
  */
@@ -153,7 +164,16 @@ export class FileScriptProcessor extends BaseScriptProcessor {
153
164
  if (dep.inline) {
154
165
  return { code: compiled.code };
155
166
  }
167
+ if (!outFilepath) {
168
+ const filepath = writeHashedBrowserAsset({
169
+ bytes: compiled.code,
170
+ directory: this.getAssetsDir(),
171
+ extension: '.js',
172
+ });
173
+ return { code: compiled.code, filepath };
174
+ }
156
175
  const filepath = path.join(this.getAssetsDir(), classicScriptOutputName(outFilepath));
176
+ assertBrowserOutputInsideDist(this.appConfig.absolutePaths.distDir, filepath);
157
177
  const other = this.classicScriptSources.get(filepath);
158
178
  if (other !== undefined && other !== dep.filepath && fileSystem.exists(other)) {
159
179
  throw new Error(`${dep.filepath} and ${other} are both emitted as ${filepath}. Rename one of them.`);