@ecopages/core 0.7.1 → 0.9.0

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 (146) hide show
  1. package/README.md +2 -2
  2. package/package.json +14 -4
  3. package/src/adapters/node/create-app.d.ts +1 -1
  4. package/src/adapters/node/create-app.js +1 -1
  5. package/src/adapters/node/server-adapter.d.ts +1 -0
  6. package/src/adapters/node/server-adapter.js +4 -1
  7. package/src/adapters/shared/hmr/hmr-manager.d.ts +2 -0
  8. package/src/adapters/shared/hmr/hmr-manager.js +8 -4
  9. package/src/adapters/shared/http/api-request-pipeline.d.ts +16 -3
  10. package/src/adapters/shared/http/api-request-pipeline.js +16 -11
  11. package/src/adapters/shared/http/explicit-static-route-matcher.js +8 -4
  12. package/src/adapters/shared/runtime/render-context.d.ts +2 -0
  13. package/src/adapters/shared/runtime/render-context.js +4 -0
  14. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +2 -2
  15. package/src/adapters/shared/runtime/server-request-pipeline.js +4 -3
  16. package/src/adapters/shared/runtime/server-static-builder.js +4 -1
  17. package/src/adapters/shared/runtime/unattached-scripts.d.ts +17 -0
  18. package/src/adapters/shared/runtime/unattached-scripts.js +57 -0
  19. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +3 -2
  20. package/src/adapters/shared/ws/ws-pattern-matcher.d.ts +14 -1
  21. package/src/adapters/shared/ws/ws-pattern-matcher.js +14 -13
  22. package/src/assets/app-browser-client-build.js +3 -0
  23. package/src/assets/asset-processing-service/asset-processing.service.d.ts +9 -0
  24. package/src/assets/asset-processing-service/asset-processing.service.js +19 -0
  25. package/src/assets/asset-processing-service/processed-asset-ledger.d.ts +16 -2
  26. package/src/assets/asset-processing-service/processed-asset-ledger.js +31 -3
  27. package/src/assets/asset-processing-service/processors/stylesheet/import-order.js +5 -3
  28. package/src/build/build-graph.d.ts +19 -2
  29. package/src/build/build-graph.js +19 -18
  30. package/src/build/cache/pages-unified-graph-build.d.ts +4 -6
  31. package/src/build/cache/pages-unified-graph-build.js +14 -51
  32. package/src/build/cache/server-module-entries.d.ts +5 -9
  33. package/src/build/cache/server-module-entries.js +5 -58
  34. package/src/build/contracts/build-contracts.d.ts +15 -0
  35. package/src/build/contracts.d.ts +1 -1
  36. package/src/build/contracts.js +1 -1
  37. package/src/build/production-asset-ledger.d.ts +1 -1
  38. package/src/build/production-asset-ledger.js +4 -2
  39. package/src/build/rolldown/file-role-grammar-plugin.d.ts +11 -0
  40. package/src/build/rolldown/file-role-grammar-plugin.js +32 -0
  41. package/src/build/rolldown/rolldown-adapter-helpers.d.ts +11 -0
  42. package/src/build/rolldown/rolldown-adapter-helpers.js +79 -10
  43. package/src/build/rolldown/ssr-script-entries-plugin.d.ts +31 -0
  44. package/src/build/rolldown/ssr-script-entries-plugin.js +104 -0
  45. package/src/build/server/server-modules-manifest.d.ts +6 -1
  46. package/src/build/server/server-modules-manifest.js +10 -1
  47. package/src/build/server/view-reference.d.ts +9 -0
  48. package/src/build/server/view-reference.js +11 -0
  49. package/src/build.d.ts +2 -1
  50. package/src/build.js +2 -1
  51. package/src/cli.d.ts +14 -0
  52. package/src/cli.js +14 -0
  53. package/src/config/assembly/app-runtime.d.ts +13 -0
  54. package/src/config/assembly/app-runtime.js +2 -0
  55. package/src/config/assembly/finalize-config.js +13 -8
  56. package/src/config/internal-types.d.ts +0 -12
  57. package/src/config/resolve-eco-config-path.d.ts +2 -0
  58. package/src/config/resolve-eco-config-path.js +2 -1
  59. package/src/config/server-config-bundle.d.ts +0 -1
  60. package/src/config/server-config-bundle.js +1 -1
  61. package/src/config/user-config-types.d.ts +0 -12
  62. package/src/dev/invalidation/development-invalidation.service.d.ts +0 -2
  63. package/src/dev/invalidation/development-invalidation.service.js +1 -11
  64. package/src/dev/transform-server/dev-transform-vendor-registry.js +33 -19
  65. package/src/eco/discovered-dependencies.d.ts +5 -0
  66. package/src/eco/discovered-dependencies.js +9 -0
  67. package/src/eco/eco.browser.js +5 -5
  68. package/src/eco/eco.js +24 -5
  69. package/src/eco/migration-docs.d.ts +7 -0
  70. package/src/eco/migration-docs.js +7 -0
  71. package/src/hmr/client/hmr-runtime.js +1 -1
  72. package/src/hmr/strategies/js-hmr-strategy.d.ts +0 -2
  73. package/src/hmr/strategies/server-rendered-template-hmr-strategy.d.ts +2 -1
  74. package/src/hmr/strategies/server-rendered-template-hmr-strategy.js +4 -3
  75. package/src/html/html-rewriter.d.ts +9 -7
  76. package/src/html/html-rewriter.js +26 -41
  77. package/src/html/html-transformer.service.d.ts +2 -2
  78. package/src/html/html-transformer.service.js +21 -15
  79. package/src/html-pages/html-page-module-scripts.js +2 -1
  80. package/src/html-pages/html-pages.plugin.d.ts +1 -1
  81. package/src/html-pages/html-pages.plugin.js +1 -1
  82. package/src/integration.d.ts +1 -1
  83. package/src/integration.js +1 -1
  84. package/src/islands/island-host.d.ts +16 -5
  85. package/src/islands/island-host.js +8 -1
  86. package/src/plugins/component-import-discovery.d.ts +14 -1
  87. package/src/plugins/component-import-discovery.js +36 -16
  88. package/src/plugins/eco-component-meta-plugin.d.ts +5 -0
  89. package/src/plugins/eco-component-meta-plugin.js +39 -22
  90. package/src/plugins/ecopages-virtual-imports.d.ts +15 -0
  91. package/src/plugins/ecopages-virtual-imports.js +25 -0
  92. package/src/plugins/integration-plugin.d.ts +1 -1
  93. package/src/plugins/integration-plugin.js +1 -1
  94. package/src/plugins/tsconfig-import-resolver.d.ts +2 -0
  95. package/src/plugins/tsconfig-import-resolver.js +7 -5
  96. package/src/route-renderer/error-pages/error-page-renderer.js +3 -2
  97. package/src/route-renderer/explicit-view-render-preparation.d.ts +10 -3
  98. package/src/route-renderer/explicit-view-render-preparation.js +14 -8
  99. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +24 -9
  100. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +73 -50
  101. package/src/route-renderer/orchestration/integration-renderer.d.ts +39 -10
  102. package/src/route-renderer/orchestration/integration-renderer.js +74 -38
  103. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.d.ts +32 -11
  104. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +68 -61
  105. package/src/route-renderer/page-declaration.d.ts +25 -0
  106. package/src/route-renderer/page-declaration.js +39 -0
  107. package/src/route-renderer/page-loading/component-declarations.d.ts +65 -0
  108. package/src/route-renderer/page-loading/component-declarations.js +77 -0
  109. package/src/route-renderer/page-loading/component-dependency-collection.d.ts +4 -16
  110. package/src/route-renderer/page-loading/component-dependency-collection.js +36 -105
  111. package/src/route-renderer/page-loading/declared-asset-collection.d.ts +19 -14
  112. package/src/route-renderer/page-loading/declared-asset-collection.js +66 -67
  113. package/src/route-renderer/page-loading/dependency-resolver.d.ts +18 -10
  114. package/src/route-renderer/page-loading/dependency-resolver.js +58 -99
  115. package/src/route-renderer/page-loading/lazy-entry-collection.d.ts +19 -26
  116. package/src/route-renderer/page-loading/lazy-entry-collection.js +53 -64
  117. package/src/route-renderer/page-loading/module-declaration-aggregation.d.ts +17 -3
  118. package/src/route-renderer/page-loading/module-declaration-aggregation.js +14 -13
  119. package/src/route-renderer/page-loading/page-module-loader.d.ts +10 -11
  120. package/src/route-renderer/page-loading/page-module-loader.js +30 -30
  121. package/src/router/server/pages-dir.d.ts +7 -0
  122. package/src/router/server/pages-dir.js +7 -0
  123. package/src/router/server/route-registry.d.ts +22 -10
  124. package/src/router/server/route-registry.js +54 -23
  125. package/src/router/server/segment-path-matcher.d.ts +29 -5
  126. package/src/router/server/segment-path-matcher.js +22 -19
  127. package/src/static-site-generator/production-page-browser-graph-prebuild.d.ts +2 -2
  128. package/src/static-site-generator/production-page-browser-graph-prebuild.js +5 -5
  129. package/src/static-site-generator/static-site-generator.d.ts +17 -1
  130. package/src/static-site-generator/static-site-generator.js +46 -12
  131. package/src/types/contracts.d.ts +28 -28
  132. package/src/types/eco-api-types.d.ts +17 -12
  133. package/src/types/public-types.d.ts +1 -1
  134. package/src/utils/file-roles.d.ts +48 -0
  135. package/src/utils/file-roles.js +85 -0
  136. package/src/utils/node-builtin.d.ts +10 -0
  137. package/src/utils/node-builtin.js +13 -0
  138. package/src/watchers/project-watcher.js +2 -2
  139. package/src/build/contracts/server-only-specifier.d.ts +0 -8
  140. package/src/build/contracts/server-only-specifier.js +0 -11
  141. package/src/route-renderer/orchestration/route-pipeline/marker-artifact.utils.d.ts +0 -5
  142. package/src/route-renderer/orchestration/route-pipeline/marker-artifact.utils.js +0 -11
  143. package/src/route-renderer/page-loading/ecopages-virtual-imports.d.ts +0 -12
  144. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +0 -100
  145. package/src/utils/endpoint-file-extensions.d.ts +0 -11
  146. package/src/utils/endpoint-file-extensions.js +0 -13
@@ -10,18 +10,21 @@
10
10
  * @module
11
11
  */
12
12
  import { createHash } from 'node:crypto';
13
- import { builtinModules, createRequire } from 'node:module';
13
+ import { createRequire } from 'node:module';
14
14
  import { path } from '@ecopages/file-system/path';
15
15
  import { fileSystem } from '@ecopages/file-system';
16
16
  import { stripVTControlCharacters } from 'node:util';
17
- import { recordBuildEntryOutput, resolveBuildEntryPath } from '../build-graph.js';
17
+ import { recordBuildEntryOutput, resolveBuildEntryPath, resolveRequestedBuildEntries } from '../build-graph.js';
18
18
  import { id as idFilter, include } from 'rolldown/filter';
19
19
  import { escapeRegExp } from '../../utils/regex-escaping.js';
20
20
  import { isPathInside } from '../../utils/path-containment.js';
21
21
  import { isEcopagesEnvEnabled } from '../../env.js';
22
22
  import { isBarePackageImportSpecifier } from '../../plugins/tsconfig-import-resolver.js';
23
23
  import { toPackageRootSpecifier } from '../../plugins/package-specifier.js';
24
- import { isServerOnlyModuleSpecifier } from '../contracts/server-only-specifier.js';
24
+ import { isServerOnlyModuleSpecifier } from '../../utils/file-roles.js';
25
+ import { isNodeBuiltinSpecifier, nodeBuiltinSpecifiers } from '../../utils/node-builtin.js';
26
+ import { createFileRoleGrammarPlugin } from './file-role-grammar-plugin.js';
27
+ import { createSsrScriptEntriesPlugin } from './ssr-script-entries-plugin.js';
25
28
  import { createWorkerEntriesPlugin } from './worker-entries-plugin.js';
26
29
  import { createStylesheetModulePlugin } from './stylesheet-module-plugin.js';
27
30
  import { appLogger } from '../../global/app-logger.js';
@@ -30,7 +33,6 @@ import { fromRolldownModuleId } from './rolldown-module-id.js';
30
33
  import { createRolldownPluginBridge } from './rolldown-plugin-bridge.js';
31
34
  import { isDeclaredAppPackageImport, isWorkspacePackageImport } from './app-package-declarations.js';
32
35
  const coreSourceFile = path.fromFileUrl(import.meta.url);
33
- const nodeBuiltinSpecifiers = new Set(builtinModules);
34
36
  const MAX_FLATTENED_PRESERVED_MODULE_NAME_BYTES = 120;
35
37
  const PRESERVED_MODULE_NAME_HASH_LENGTH = 16;
36
38
  let corePackageNames;
@@ -269,8 +271,28 @@ export function createInstalledPackageExternalPlugin(contextRoot, outdir, report
269
271
  },
270
272
  };
271
273
  }
272
- function isNodeBuiltinSpecifier(id) {
273
- return id.startsWith('node:') || nodeBuiltinSpecifiers.has(id);
274
+ /**
275
+ * Names the import chain from the nearest app module to `specifier`, as ` (imported from <app module> > <package module> > ...)`.
276
+ *
277
+ * @remarks
278
+ * A package's own modules are not what the author wrote: when a bare `import 'pg'` reaches a built-in, the useful
279
+ * answer is the app module that imported the package. The walk follows each module's first importer until it
280
+ * leaves `node_modules` or reaches an entry, so the chain is the first path the bundler found. Rolldown ids are
281
+ * native paths, so each is converted to forward slashes before the `node_modules` test and kept native for
282
+ * `getModuleInfo`.
283
+ */
284
+ function describeImportChain(context, importer, specifier) {
285
+ const chain = [];
286
+ const seen = new Set();
287
+ for (let current = importer; current && !seen.has(current);) {
288
+ seen.add(current);
289
+ const id = fromRolldownModuleId(current);
290
+ chain.unshift(id);
291
+ if (!id.split('/').includes('node_modules'))
292
+ break;
293
+ current = context.getModuleInfo(current)?.importers[0];
294
+ }
295
+ return ` (imported from ${[...chain, specifier].join(' > ')})`;
274
296
  }
275
297
  const nodeBuiltinFilter = new RegExp(`^(?:node:.*|${[...nodeBuiltinSpecifiers].map((specifier) => escapeRegExp(specifier)).join('|')})$`);
276
298
  /**
@@ -281,6 +303,9 @@ const nodeBuiltinFilter = new RegExp(`^(?:node:.*|${[...nodeBuiltinSpecifiers].m
281
303
  * bare specifiers. This plugin fails the build instead so server-only graphs
282
304
  * cannot reach the browser as silent CORS errors.
283
305
  *
306
+ * A built-in is recorded where it resolves and reported at `buildEnd`, because the importer chain through
307
+ * `node_modules` to the app module is only known once every module is parsed.
308
+ *
284
309
  * The `.server` check reads the resolved ids a module imports once it is parsed,
285
310
  * not the specifiers as written, so an alias such as a `package.json` `imports`
286
311
  * entry or a tsconfig path is rejected like a relative import. Rolldown has no
@@ -291,6 +316,7 @@ export function createBrowserServerOnlyGuardPlugin() {
291
316
  const from = importer ? ` (imported from ${fromRolldownModuleId(importer)})` : '';
292
317
  throw new Error(`[browser-build] server-only module "${fromRolldownModuleId(id)}" cannot be bundled for the browser${from}. Check the browser graph boundary for the importer.`);
293
318
  };
319
+ const builtinImports = [];
294
320
  return {
295
321
  name: 'ecopages-browser-server-only-guard',
296
322
  resolveId: {
@@ -299,10 +325,20 @@ export function createBrowserServerOnlyGuardPlugin() {
299
325
  if (!isNodeBuiltinSpecifier(id)) {
300
326
  return null;
301
327
  }
302
- const from = importer ? ` (imported from ${fromRolldownModuleId(importer)})` : '';
303
- throw new Error(`[browser-build] Node builtin "${id}" cannot be bundled for the browser${from}. Check package "browser" exports and the client-graph boundary for the importer.`);
328
+ builtinImports.push({ id, importer });
329
+ return { id, external: true };
304
330
  },
305
331
  },
332
+ buildStart() {
333
+ builtinImports.length = 0;
334
+ },
335
+ buildEnd() {
336
+ const first = builtinImports[0];
337
+ if (!first)
338
+ return;
339
+ const chain = first.importer ? describeImportChain(this, first.importer, first.id) : '';
340
+ throw new Error(`[browser-build] Node builtin "${first.id}" cannot be bundled for the browser${chain}. Keep server-only code in a ".server" module that only server-side hooks such as props import, or check package "browser" exports and the client-graph boundary.`);
341
+ },
306
342
  moduleParsed(info) {
307
343
  if (info.isEntry && isServerOnlyModuleSpecifier(info.id)) {
308
344
  rejectServerOnly(info.id, undefined);
@@ -446,10 +482,12 @@ async function buildRolldownInputPlugins(options, contextRoot, outdir, rolldownP
446
482
  createInstalledPackageExternalPlugin(contextRoot, outdir, options.reportPackagesOutsideRoot === true ? (options.runtimeOutdir ?? outdir) : undefined),
447
483
  ]
448
484
  : []),
485
+ createFileRoleGrammarPlugin(),
449
486
  ...(rolldownPlatform === 'browser' ? [createBrowserServerOnlyGuardPlugin()] : []),
450
487
  createStylesheetModulePlugin({ environment: options.environment, root: contextRoot }, options.stylesheets, watchFiles),
451
488
  ...appPlugins,
452
489
  ...(options.environment === 'browser' && options.workerEntries !== false ? [createWorkerEntriesPlugin()] : []),
490
+ ...(options.ssrScriptEntries === true ? [createSsrScriptEntriesPlugin()] : []),
453
491
  ];
454
492
  }
455
493
  async function buildRolldownInputOptions(options, contextRoot, outdir, external, rolldownPlatform, watchFiles) {
@@ -539,6 +577,25 @@ function flattenPreservedModuleFileNames(pattern) {
539
577
  function sanitizePreservedModuleName(name) {
540
578
  return name.replace(/^(?:\.\.?\/)+/u, '').replaceAll(/[\0?*:]/gu, '_');
541
579
  }
580
+ /**
581
+ * Names the chunk of the installed package a module belongs to, or nothing for app code.
582
+ *
583
+ * @remarks
584
+ * The package is the one at the last `node_modules` segment, so a pnpm store path and a nested install both resolve to
585
+ * the package that owns the module.
586
+ */
587
+ export function getInstalledPackageChunkName(moduleId) {
588
+ const marker = 'node_modules/';
589
+ const normalized = moduleId.replaceAll('\\', '/');
590
+ const index = normalized.lastIndexOf(marker);
591
+ if (index === -1)
592
+ return null;
593
+ const [first, second] = normalized.slice(index + marker.length).split('/');
594
+ if (!first)
595
+ return null;
596
+ const packageName = first.startsWith('@') && second ? `${first.slice(1)}-${second}` : first;
597
+ return `vendor-${packageName}`;
598
+ }
542
599
  function buildRolldownOutputOptions(options, outdir) {
543
600
  const entryFileNames = resolveRolldownEntryFileNames(options);
544
601
  return {
@@ -559,6 +616,18 @@ function buildRolldownOutputOptions(options, outdir) {
559
616
  : {}),
560
617
  sourcemap: mapRolldownSourcemap(options.sourcemap),
561
618
  ...(shouldDisableRolldownCodeSplitting(options) ? { codeSplitting: false } : {}),
619
+ ...(options.packageChunks && options.splitting !== false
620
+ ? {
621
+ codeSplitting: {
622
+ groups: [
623
+ {
624
+ name: getInstalledPackageChunkName,
625
+ minSize: options.packageChunks.minSize,
626
+ },
627
+ ],
628
+ },
629
+ }
630
+ : {}),
562
631
  };
563
632
  }
564
633
  /**
@@ -638,6 +707,7 @@ export function buildResultFromRolldownOutput(output, outdir, contextRoot, depen
638
707
  },
639
708
  ]));
640
709
  const entryOutputs = {};
710
+ const requestedEntries = resolveRequestedBuildEntries(entrypoints, contextRoot);
641
711
  for (const chunk of chunks) {
642
712
  if (!chunk.isEntry || !chunk.facadeModuleId) {
643
713
  continue;
@@ -645,8 +715,7 @@ export function buildResultFromRolldownOutput(output, outdir, contextRoot, depen
645
715
  recordBuildEntryOutput(entryOutputs, normalizeOutputPath(chunk.fileName, outdir), {
646
716
  facadeModuleId: resolveBuildEntryPath(chunk.facadeModuleId, contextRoot),
647
717
  chunkName: chunk.name,
648
- entrypoints,
649
- root: contextRoot,
718
+ requestedEntries,
650
719
  });
651
720
  }
652
721
  return {
@@ -0,0 +1,31 @@
1
+ import type { RolldownPlugin } from 'rolldown';
2
+ declare const PARSER_LANGUAGES: readonly ["js", "jsx", "ts", "tsx"];
3
+ /** A script a declaration lists with a literal `src`. */
4
+ export type DeclaredScript = {
5
+ src: string;
6
+ ssr: boolean;
7
+ };
8
+ /**
9
+ * Lists the scripts a module's declarations name with a literal `src`, relative to that module.
10
+ *
11
+ * @remarks
12
+ * Finds each string or `{ src }` entry of a literal `scripts: [...]` array, and any `{ src, ssr: true }` object.
13
+ * A `src` that is computed at runtime is not found.
14
+ */
15
+ export declare function findDeclaredScripts(file: string, code: string, lang: (typeof PARSER_LANGUAGES)[number]): DeclaredScript[];
16
+ /**
17
+ * The parser language for a file name, or `undefined` when it is not a script module.
18
+ */
19
+ export declare function scriptModuleLanguage(file: string): (typeof PARSER_LANGUAGES)[number] | undefined;
20
+ /**
21
+ * Emits each `ssr: true` script a declaration lists as an entry of the server build that bundles the declaration.
22
+ *
23
+ * @remarks
24
+ * A custom element script that the server also evaluates is not imported by the component that lists it, so only
25
+ * the declaration names it: `dependencies.scripts: [{ src: './x.script.js', ssr: true }]`, with `src` relative to the
26
+ * declaring module. The script then shares chunks with the rest of the build and keeps its exports like any
27
+ * entry, so no second build is needed to add it. Only a literal `src` beside a literal `ssr: true` is found; a
28
+ * script path computed at runtime is not.
29
+ */
30
+ export declare function createSsrScriptEntriesPlugin(): RolldownPlugin;
31
+ export {};
@@ -0,0 +1,104 @@
1
+ import { fileSystem } from '@ecopages/file-system';
2
+ import { path } from '@ecopages/file-system/path';
3
+ import { parseModuleSource } from '../../cache/module-parse-cache.js';
4
+ import { fromRolldownModuleId } from './rolldown-module-id.js';
5
+ const SSR_SCRIPT_PATTERN = /\bssr\s*:\s*(?:true|!0)/u;
6
+ const PARSER_LANGUAGES = ['js', 'jsx', 'ts', 'tsx'];
7
+ function isNode(value) {
8
+ return typeof value === 'object' && value !== null;
9
+ }
10
+ function propertyValue(object, name) {
11
+ for (const property of Array.isArray(object.properties) ? object.properties : []) {
12
+ if (!isNode(property) || (property.type !== 'ObjectProperty' && property.type !== 'Property'))
13
+ continue;
14
+ const key = property.key;
15
+ if (isNode(key) && (key.name === name || key.value === name))
16
+ return property.value;
17
+ }
18
+ return undefined;
19
+ }
20
+ function declaredScriptOf(value) {
21
+ if (isNode(value) && typeof value.value === 'string')
22
+ return { src: value.value, ssr: false };
23
+ if (!isNode(value) || value.type !== 'ObjectExpression')
24
+ return undefined;
25
+ const src = propertyValue(value, 'src');
26
+ const ssr = propertyValue(value, 'ssr');
27
+ if (!isNode(src) || typeof src.value !== 'string')
28
+ return undefined;
29
+ return { src: src.value, ssr: isNode(ssr) && ssr.value === true };
30
+ }
31
+ function collectDeclaredScripts(value, scripts) {
32
+ if (Array.isArray(value)) {
33
+ for (const child of value)
34
+ collectDeclaredScripts(child, scripts);
35
+ return;
36
+ }
37
+ if (!isNode(value))
38
+ return;
39
+ if (value.type === 'ObjectExpression') {
40
+ const listed = propertyValue(value, 'scripts');
41
+ if (isNode(listed) && listed.type === 'ArrayExpression' && Array.isArray(listed.elements)) {
42
+ for (const element of listed.elements) {
43
+ const script = declaredScriptOf(element);
44
+ if (script)
45
+ scripts.push(script);
46
+ }
47
+ }
48
+ const own = declaredScriptOf(value);
49
+ if (own?.ssr)
50
+ scripts.push(own);
51
+ }
52
+ for (const [key, child] of Object.entries(value)) {
53
+ if (key !== 'type' && typeof child === 'object')
54
+ collectDeclaredScripts(child, scripts);
55
+ }
56
+ }
57
+ /**
58
+ * Lists the scripts a module's declarations name with a literal `src`, relative to that module.
59
+ *
60
+ * @remarks
61
+ * Finds each string or `{ src }` entry of a literal `scripts: [...]` array, and any `{ src, ssr: true }` object.
62
+ * A `src` that is computed at runtime is not found.
63
+ */
64
+ export function findDeclaredScripts(file, code, lang) {
65
+ const scripts = [];
66
+ collectDeclaredScripts(parseModuleSource(file, code, { sourceType: 'module', lang }).program, scripts);
67
+ return scripts;
68
+ }
69
+ /**
70
+ * The parser language for a file name, or `undefined` when it is not a script module.
71
+ */
72
+ export function scriptModuleLanguage(file) {
73
+ return PARSER_LANGUAGES.find((language) => file.endsWith(`.${language}`));
74
+ }
75
+ /**
76
+ * Emits each `ssr: true` script a declaration lists as an entry of the server build that bundles the declaration.
77
+ *
78
+ * @remarks
79
+ * A custom element script that the server also evaluates is not imported by the component that lists it, so only
80
+ * the declaration names it: `dependencies.scripts: [{ src: './x.script.js', ssr: true }]`, with `src` relative to the
81
+ * declaring module. The script then shares chunks with the rest of the build and keeps its exports like any
82
+ * entry, so no second build is needed to add it. Only a literal `src` beside a literal `ssr: true` is found; a
83
+ * script path computed at runtime is not.
84
+ */
85
+ export function createSsrScriptEntriesPlugin() {
86
+ return {
87
+ name: 'ecopages:ssr-script-entries',
88
+ transform: {
89
+ filter: { code: SSR_SCRIPT_PATTERN },
90
+ handler(code, id, meta) {
91
+ const file = fromRolldownModuleId(id);
92
+ const lang = PARSER_LANGUAGES.find((language) => language === meta.moduleType) ?? 'js';
93
+ for (const { src, ssr } of findDeclaredScripts(file, code, lang)) {
94
+ if (!ssr)
95
+ continue;
96
+ const script = path.resolve(path.dirname(file), src);
97
+ if (fileSystem.exists(script))
98
+ this.emitFile({ type: 'chunk', id: script });
99
+ }
100
+ return null;
101
+ },
102
+ },
103
+ };
104
+ }
@@ -34,7 +34,12 @@ export declare function requireProductionServerModules(appConfig: EcoPagesAppCon
34
34
  * Names the source file and tells the operator to run `ecopages build`. It is
35
35
  * never a compile fallback.
36
36
  */
37
- export declare function missingProductionServerModuleError(sourceKey: string): Error;
37
+ /** The production server build holds no module for a source the app imports. */
38
+ export declare class MissingProductionServerModuleError extends Error {
39
+ readonly sourceKey: string;
40
+ constructor(sourceKey: string);
41
+ }
42
+ export declare function missingProductionServerModuleError(sourceKey: string): MissingProductionServerModuleError;
38
43
  /**
39
44
  * Finds the production map key for `filePath`: its path relative to `rootDir`, when the map records it.
40
45
  *
@@ -81,8 +81,17 @@ export function requireProductionServerModules(appConfig) {
81
81
  * Names the source file and tells the operator to run `ecopages build`. It is
82
82
  * never a compile fallback.
83
83
  */
84
+ /** The production server build holds no module for a source the app imports. */
85
+ export class MissingProductionServerModuleError extends Error {
86
+ sourceKey;
87
+ constructor(sourceKey) {
88
+ super(`No compiled server module for ${sourceKey}. Run \`ecopages build\`.`);
89
+ this.name = 'MissingProductionServerModuleError';
90
+ this.sourceKey = sourceKey;
91
+ }
92
+ }
84
93
  export function missingProductionServerModuleError(sourceKey) {
85
- return new Error(`No compiled server module for ${sourceKey}. Run \`ecopages build\`.`);
94
+ return new MissingProductionServerModuleError(sourceKey);
86
95
  }
87
96
  function modulePathWithoutQuery(filePath) {
88
97
  const query = filePath.indexOf('?');
@@ -37,6 +37,15 @@ export declare function viewExtensionFilter(extensions: readonly string[]): RegE
37
37
  * when it renders the view.
38
38
  */
39
39
  export declare function createViewReference<P = Record<string, unknown>>(filePath: string, integration?: string | null): ViewReference<P>;
40
+ /**
41
+ * True when `filePath` is a view the server entry imported, so a View Reference exists for it.
42
+ *
43
+ * @remarks
44
+ * The registry is the module-level set `createViewReference` fills, in development by the preload and in
45
+ * production by the imported-view plugin. The preload names a view by its absolute path, which is what this
46
+ * checks, so it answers for the development server; a production bundle names views relative to the app root.
47
+ */
48
+ export declare function isViewReferencePath(filePath: string): boolean;
40
49
  /**
41
50
  * Synthetic ESM source the CLI hook and server-entry plugin evaluate instead of the view.
42
51
  *
@@ -101,6 +101,17 @@ export function createViewReference(filePath, integration) {
101
101
  viewReferences.set(filePath, reference);
102
102
  return reference;
103
103
  }
104
+ /**
105
+ * True when `filePath` is a view the server entry imported, so a View Reference exists for it.
106
+ *
107
+ * @remarks
108
+ * The registry is the module-level set `createViewReference` fills, in development by the preload and in
109
+ * production by the imported-view plugin. The preload names a view by its absolute path, which is what this
110
+ * checks, so it answers for the development server; a production bundle names views relative to the app root.
111
+ */
112
+ export function isViewReferencePath(filePath) {
113
+ return viewReferences.has(path.resolve(filePath));
114
+ }
104
115
  /**
105
116
  * Synthetic ESM source the CLI hook and server-entry plugin evaluate instead of the view.
106
117
  *
package/src/build.d.ts CHANGED
@@ -3,7 +3,8 @@ export { isLitStaticRenderWorkerThread } from './build/browser/lit-static-render
3
3
  export { restoreProductionBrowserBuild } from './static-site-generator/production-page-browser-graph-prebuild.js';
4
4
  export { type BuildAdapter, type BuildExecutor, type BuildOptions, type BuildResult, resolveIntegrationDependencies, setupAppRuntimeIntegrations, setupAppRuntimePlugins, teardownAppRuntimeIntegrations, } from './build/build-adapter.js';
5
5
  export { CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from './build/contracts/content-virtual-modules.js';
6
- export { isServerOnlyModuleSpecifier } from './build/contracts/server-only-specifier.js';
6
+ export { isServerOnlyModuleSpecifier } from './utils/file-roles.js';
7
+ export { isNodeBuiltinSpecifier } from './utils/node-builtin.js';
7
8
  export { shouldBuildPagesUnifiedGraph } from './build/cache/pages-unified-graph-build.js';
8
9
  export { BuildQueue } from './build/runtime/build-queue.js';
9
10
  export { buildServerModule } from './build/server-module.js';
package/src/build.js CHANGED
@@ -3,7 +3,8 @@ export { isLitStaticRenderWorkerThread } from './build/browser/lit-static-render
3
3
  export { restoreProductionBrowserBuild } from './static-site-generator/production-page-browser-graph-prebuild.js';
4
4
  export { resolveIntegrationDependencies, setupAppRuntimeIntegrations, setupAppRuntimePlugins, teardownAppRuntimeIntegrations, } from './build/build-adapter.js';
5
5
  export { CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, } from './build/contracts/content-virtual-modules.js';
6
- export { isServerOnlyModuleSpecifier } from './build/contracts/server-only-specifier.js';
6
+ export { isServerOnlyModuleSpecifier } from './utils/file-roles.js';
7
+ export { isNodeBuiltinSpecifier } from './utils/node-builtin.js';
7
8
  export { shouldBuildPagesUnifiedGraph } from './build/cache/pages-unified-graph-build.js';
8
9
  export { BuildQueue } from './build/runtime/build-queue.js';
9
10
  export { buildServerModule } from './build/server-module.js';
package/src/cli.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * What the `ecopages` CLI reads before it starts an app process.
3
+ *
4
+ * @remarks
5
+ * The CLI parent process only plans the launch and spawns the app, which loads the build and config modules
6
+ * itself. This entry keeps the parent off the `build` and `config` barrels, so each command starts without
7
+ * loading the bundler.
8
+ * @module
9
+ */
10
+ export { ECOPAGES_DEV_RESTART_EXIT_CODE, ECOPAGES_DEV_RESTART_REASON_ENV, ECOPAGES_ENTRY_WATCH_ENV, getDevEnvFileNames, resolveDevelopmentRecoveryWatch, } from './dev/development-restart.js';
11
+ export { ENTRY_COMMAND_FLAGS, getEntryCommandFlagNames } from './utils/entry-command-flags.js';
12
+ export { getEcopagesEnv, isEcopagesEnvEnabled } from './env.js';
13
+ export { resolveEcoConfigPath, resolveEmittedEcoConfigPath } from './config/resolve-eco-config-path.js';
14
+ export { assertProductionConfigIdentity, resolveProductionDistDir, resolveProductionServerEntry, } from './build/server-bundle-deploy-manifest.js';
package/src/cli.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * What the `ecopages` CLI reads before it starts an app process.
3
+ *
4
+ * @remarks
5
+ * The CLI parent process only plans the launch and spawns the app, which loads the build and config modules
6
+ * itself. This entry keeps the parent off the `build` and `config` barrels, so each command starts without
7
+ * loading the bundler.
8
+ * @module
9
+ */
10
+ export { ECOPAGES_DEV_RESTART_EXIT_CODE, ECOPAGES_DEV_RESTART_REASON_ENV, ECOPAGES_ENTRY_WATCH_ENV, getDevEnvFileNames, resolveDevelopmentRecoveryWatch, } from './dev/development-restart.js';
11
+ export { ENTRY_COMMAND_FLAGS, getEntryCommandFlagNames } from './utils/entry-command-flags.js';
12
+ export { getEcopagesEnv, isEcopagesEnvEnabled } from './env.js';
13
+ export { resolveEcoConfigPath, resolveEmittedEcoConfigPath } from './config/resolve-eco-config-path.js';
14
+ export { assertProductionConfigIdentity, resolveProductionDistDir, resolveProductionServerEntry, } from './build/server-bundle-deploy-manifest.js';
@@ -16,6 +16,7 @@ import type { CustomElementScriptPreloadScopeState } from '../../route-renderer/
16
16
  import type { DevelopmentInvalidationService } from '../../dev/invalidation/development-invalidation.service.js';
17
17
  import type { DevelopmentStylesheetService } from '../../dev/stylesheets/development-stylesheet.service.js';
18
18
  import type { PageCacheService } from '../../page-cache/page-cache-service.js';
19
+ import type { RouteRegistry } from '../../router/server/route-registry.js';
19
20
  import type { IHmrManager } from '../../types/contracts.js';
20
21
  export { requireAppRuntime } from '../../utils/app-runtime.js';
21
22
  export type { RegisteredScriptEntrypointChangeHandler } from '../../types/contracts.js';
@@ -94,6 +95,18 @@ export interface AppRuntime {
94
95
  requestPipelineMetrics: RequestPipelineMetricsState;
95
96
  origin: string;
96
97
  hmr: IHmrManager | null;
98
+ /**
99
+ * The Route Registry of the running server, `null` until the server creates it.
100
+ */
101
+ router: RouteRegistry | null;
102
+ /**
103
+ * Absolute source paths of the modules a rendered Page references as a Layout.
104
+ *
105
+ * @remarks
106
+ * Filled during route preparation, so it only grows within a session and holds the Layouts that were
107
+ * rendered. A Layout is whatever a Page passes as `eco.page({ layout })`, never a folder.
108
+ */
109
+ layoutFiles: Set<string>;
97
110
  /**
98
111
  * Processed and bundled dependencies of the production build, by dependency key, shared by every
99
112
  * asset-processing service.
@@ -77,6 +77,8 @@ export function createAppRuntime(appConfig, options = {}) {
77
77
  requestPipelineMetrics: createRequestPipelineMetricsState(),
78
78
  origin: appConfig.baseUrl,
79
79
  hmr: null,
80
+ router: null,
81
+ layoutFiles: new Set(),
80
82
  processedAssets: new ProcessedAssetLedger(appConfig.rootDir),
81
83
  processedStylesheets: new ProcessedStylesheetCache(),
82
84
  staticGenerationActive: false,
@@ -7,7 +7,7 @@ import { appLogger } from '../../global/app-logger.js';
7
7
  import { HTML_PAGES_INTEGRATION_NAME } from '../../html-pages/html-page-module.js';
8
8
  import { HtmlPagesPlugin } from '../../html-pages/html-pages.plugin.js';
9
9
  import { invariant } from '../../utils/invariant.js';
10
- import { ENDPOINT_FILE_EXTENSIONS, findEndpointFileExtension } from '../../utils/endpoint-file-extensions.js';
10
+ import { FILE_ROLE_SUFFIXES, matchRoleSuffix } from '../../utils/file-roles.js';
11
11
  import { DEFAULT_ECOPAGES_DIST_DIR, DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT, DEFAULT_ECOPAGES_WORK_DIR, } from '../../constants.js';
12
12
  import { assertResponseHeaderRules } from '../../adapters/shared/http/response-headers.js';
13
13
  import { collectConfigModuleFiles } from '../config-module-files.js';
@@ -16,7 +16,10 @@ import { listProductionServerModuleKeysFromDist } from '../../build/server/serve
16
16
  import { findStylesheetProcessor } from '../../plugins/stylesheet-kinds.js';
17
17
  import { toRootRelativePath } from '../../utils/root-relative-path.js';
18
18
  import { CLIENT_OUTPUT_DIR, SERVER_BUNDLE_DIR } from '../../utils/resolve-entry-file.js';
19
+ import { DEFAULT_PAGES_DIR } from '../../router/server/pages-dir.js';
19
20
  const finalizedPluginInstances = new WeakSet();
21
+ /** Options that named a folder the framework used to treat as a role. */
22
+ const REMOVED_DIRECTORY_OPTIONS = ['layoutsDir', 'componentsDir'];
20
23
  /**
21
24
  * Rejects values that are not a `defineConfig(...)` object.
22
25
  *
@@ -30,6 +33,12 @@ function assertUserConfig(userConfig, configFilePath) {
30
33
  const source = configFilePath ? ` from ${configFilePath}` : '';
31
34
  throw new Error(`Expected a defineConfig(...) object but received an already finalized app config${source}. Export defineConfig(...) from eco.config.ts and let createApp() finalize it.`);
32
35
  }
36
+ for (const option of REMOVED_DIRECTORY_OPTIONS) {
37
+ if (option in userConfig) {
38
+ const source = configFilePath ? ` in ${configFilePath}` : '';
39
+ throw new Error(`The ${option} option${source} was removed. Layouts and components are found from the files that reference them, so no folder carries meaning. Delete ${option} from the config; src/layouts and src/components stay as conventions, and any folder works.`);
40
+ }
41
+ }
33
42
  if ('configFilePath' in userConfig) {
34
43
  throw new Error('finalizeEcoPagesConfig() takes the user config first: finalizeEcoPagesConfig(userConfig, { configFilePath }).');
35
44
  }
@@ -69,10 +78,8 @@ function resolveEmittedConfigRootDir(rootDir, configFilePath, distDirName, cwd)
69
78
  function resolveDirectories(userConfig) {
70
79
  return {
71
80
  srcDir: userConfig.srcDir || 'src',
72
- pagesDir: userConfig.pagesDir || 'pages',
81
+ pagesDir: userConfig.pagesDir || DEFAULT_PAGES_DIR,
73
82
  includesDir: userConfig.includesDir || 'includes',
74
- componentsDir: userConfig.componentsDir || 'components',
75
- layoutsDir: userConfig.layoutsDir || 'layouts',
76
83
  publicDir: userConfig.publicDir || 'public',
77
84
  distDir: userConfig.distDir || DEFAULT_ECOPAGES_DIST_DIR,
78
85
  workDir: userConfig.workDir || DEFAULT_ECOPAGES_WORK_DIR,
@@ -122,8 +129,8 @@ function collectTemplateExtensions(integrations) {
122
129
  appLogger.debug('Both kitajs and react integrations are enabled. Use per-file JSX import source/pragma consistently (e.g. `/** @jsxImportSource react */` for React files and `/** @jsxImportSource @kitajs/html */` for Kita files).');
123
130
  }
124
131
  for (const integration of integrations) {
125
- const reserved = integration.extensions.find((extension) => findEndpointFileExtension(extension));
126
- invariant(reserved === undefined, `Integration "${integration.name}" registers "${reserved}", which is reserved for endpoint files: ${ENDPOINT_FILE_EXTENSIONS.join(', ')}.`);
132
+ const reserved = integration.extensions.find((extension) => matchRoleSuffix(extension));
133
+ invariant(reserved === undefined, `Integration "${integration.name}" registers "${reserved}", which is reserved for role files: ${FILE_ROLE_SUFFIXES.join(', ')}.`);
127
134
  }
128
135
  const extensions = integrations.flatMap((integration) => integration.extensions);
129
136
  const duplicateExtension = findDuplicate(extensions);
@@ -214,9 +221,7 @@ function createAbsolutePaths(config, configFilePath, configModuleFiles) {
214
221
  srcDir,
215
222
  distDir: path.resolve(config.rootDir, config.distDir, CLIENT_OUTPUT_DIR),
216
223
  workDir: path.resolve(config.rootDir, config.workDir),
217
- componentsDir: path.join(srcDir, config.componentsDir),
218
224
  includesDir,
219
- layoutsDir: path.join(srcDir, config.layoutsDir),
220
225
  pagesDir,
221
226
  publicDir: path.join(srcDir, config.publicDir),
222
227
  htmlTemplatePath: resolveSemanticTemplatePath(includesDir, 'html', config.templatesExt, config.rootDir, config.distDir),
@@ -49,11 +49,6 @@ export type EcoPagesAppConfig = {
49
49
  * @default "includes"
50
50
  */
51
51
  includesDir: string;
52
- /**
53
- * The directory where the layouts are located
54
- * @default "layouts"
55
- */
56
- layoutsDir: string;
57
52
  /**
58
53
  * The directory where the output will be located
59
54
  * @default "dist"
@@ -74,11 +69,6 @@ export type EcoPagesAppConfig = {
74
69
  * The templates extensions based on the integrations
75
70
  */
76
71
  templatesExt: string[];
77
- /**
78
- * The directory where the components are located
79
- * @default "components"
80
- */
81
- componentsDir: string;
82
72
  /**
83
73
  * The robots.txt configuration
84
74
  */
@@ -131,12 +121,10 @@ export type EcoPagesAppConfig = {
131
121
  * restarts on the same set.
132
122
  */
133
123
  configModuleFiles: string[];
134
- componentsDir: string;
135
124
  /** Public output directory served by the runtime (`<distDir>/client`). */
136
125
  distDir: string;
137
126
  workDir: string;
138
127
  includesDir: string;
139
- layoutsDir: string;
140
128
  pagesDir: string;
141
129
  projectDir: string;
142
130
  publicDir: string;
@@ -1,5 +1,7 @@
1
1
  export declare const DEFAULT_ECO_CONFIG_FILENAME = "eco.config.ts";
2
2
  export declare const ECOPAGES_CONFIG_FILE_ENV = "ECOPAGES_CONFIG_FILE";
3
+ /** The file name of the config module `ecopages build` emits into the server bundle. */
4
+ export declare const EMITTED_ECO_CONFIG_FILENAME = "eco.config.mjs";
3
5
  /**
4
6
  * Resolves the project root used when `EcoPagesUserConfig.rootDir` is omitted.
5
7
  *
@@ -3,9 +3,10 @@ import { getEcopagesEnv } from '../env.js';
3
3
  import { fileSystem } from '@ecopages/file-system';
4
4
  import { SERVER_BUNDLE_DIR } from '../utils/resolve-entry-file.js';
5
5
  import { getProductionServerBundleDir } from '../utils/server-bundle-context.js';
6
- import { EMITTED_ECO_CONFIG_FILENAME } from './server-config-bundle.js';
7
6
  export const DEFAULT_ECO_CONFIG_FILENAME = 'eco.config.ts';
8
7
  export const ECOPAGES_CONFIG_FILE_ENV = 'ECOPAGES_CONFIG_FILE';
8
+ /** The file name of the config module `ecopages build` emits into the server bundle. */
9
+ export const EMITTED_ECO_CONFIG_FILENAME = 'eco.config.mjs';
9
10
  /**
10
11
  * Resolves the project root used when `EcoPagesUserConfig.rootDir` is omitted.
11
12
  *
@@ -1,6 +1,5 @@
1
1
  import type { BuildSuccess } from '../build/contracts/build-contracts.js';
2
2
  import type { EcoPagesAppConfig } from '../config/internal-types.js';
3
- export declare const EMITTED_ECO_CONFIG_FILENAME = "eco.config.mjs";
4
3
  export interface BundleEcoConfigModuleResult {
5
4
  emittedConfigPath: string;
6
5
  buildResult: BuildSuccess;
@@ -3,7 +3,7 @@ import { fileSystem } from '@ecopages/file-system';
3
3
  import { createServerBuildRequest } from '../build/runtime/build-request-policy.js';
4
4
  import { buildOrThrow } from '../build/runtime/build-queue.js';
5
5
  import { getServerBundleOutputPaths } from '../build/server-bundle-deploy-manifest.js';
6
- export const EMITTED_ECO_CONFIG_FILENAME = 'eco.config.mjs';
6
+ import { EMITTED_ECO_CONFIG_FILENAME } from './resolve-eco-config-path.js';
7
7
  /**
8
8
  * Compiles the selected Ecopages config module for production server startup.
9
9
  */
@@ -72,12 +72,6 @@ export type EcoPagesUserConfig = {
72
72
  * @default 'includes'
73
73
  */
74
74
  includesDir?: string;
75
- /**
76
- * Directory containing layout components, relative to `srcDir`.
77
- *
78
- * @default 'layouts'
79
- */
80
- layoutsDir?: string;
81
75
  /**
82
76
  * Output root for the production build, relative to `rootDir`. Public files are written to `client/` and private server output to `server/` beneath it.
83
77
  *
@@ -90,12 +84,6 @@ export type EcoPagesUserConfig = {
90
84
  * @default '.eco'
91
85
  */
92
86
  workDir?: string;
93
- /**
94
- * Directory containing island and client components, relative to `srcDir`.
95
- *
96
- * @default 'components'
97
- */
98
- componentsDir?: string;
99
87
  /**
100
88
  * Configuration for automatic `robots.txt` generation.
101
89
  */