@ecopages/core 0.3.2 → 0.5.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 (79) hide show
  1. package/README.md +19 -3
  2. package/package.json +3 -3
  3. package/src/adapters/node/create-app.d.ts +19 -19
  4. package/src/adapters/node/create-app.js +26 -40
  5. package/src/adapters/node/dev-session.d.ts +3 -1
  6. package/src/adapters/node/dev-session.js +4 -1
  7. package/src/adapters/node/server-adapter.js +5 -1
  8. package/src/adapters/shared/http/api-request-pipeline.js +2 -2
  9. package/src/adapters/shared/http/define-api-handler.d.ts +41 -26
  10. package/src/adapters/shared/http/define-api-handler.js +15 -1
  11. package/src/adapters/shared/http/endpoint-route-handler.d.ts +46 -0
  12. package/src/adapters/shared/http/endpoint-route-handler.js +96 -0
  13. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +20 -3
  14. package/src/adapters/shared/runtime/server-request-pipeline.js +46 -12
  15. package/src/adapters/shared/runtime/server-route-handler.d.ts +8 -3
  16. package/src/adapters/shared/runtime/server-route-handler.js +16 -10
  17. package/src/adapters/shared/runtime/server-static-builder.d.ts +14 -1
  18. package/src/adapters/shared/runtime/server-static-builder.js +13 -2
  19. package/src/assets/app-browser-client-build.js +8 -21
  20. package/src/assets/app-browser-client-manifest.d.ts +0 -1
  21. package/src/assets/app-browser-client-manifest.js +1 -20
  22. package/src/build/contracts/content-virtual-modules.d.ts +9 -3
  23. package/src/build/contracts/content-virtual-modules.js +11 -5
  24. package/src/build/contracts.d.ts +1 -1
  25. package/src/build/contracts.js +1 -1
  26. package/src/build/rolldown/rolldown-plugin-bridge.js +2 -2
  27. package/src/build/server-bundle-deploy-manifest.d.ts +1 -1
  28. package/src/build/server-bundle-deploy-manifest.js +1 -1
  29. package/src/build.d.ts +1 -1
  30. package/src/build.js +1 -1
  31. package/src/config/assembly/finalize-config.js +5 -0
  32. package/src/dev/transform-server/dev-transform-server.js +1 -1
  33. package/src/dev/transform-server/dev-transform-vendor-registry.d.ts +29 -6
  34. package/src/dev/transform-server/dev-transform-vendor-registry.js +101 -53
  35. package/src/errors/http-error.d.ts +9 -0
  36. package/src/errors/http-error.js +11 -0
  37. package/src/html/html-transformer.service.d.ts +0 -21
  38. package/src/html/html-transformer.service.js +0 -32
  39. package/src/html-pages/html-page-renderer.d.ts +2 -1
  40. package/src/html-pages/html-page-renderer.js +5 -3
  41. package/src/index.d.ts +1 -1
  42. package/src/index.js +1 -1
  43. package/src/integration.d.ts +1 -2
  44. package/src/integration.js +0 -1
  45. package/src/islands/island-host.d.ts +1 -2
  46. package/src/islands/island-host.js +1 -2
  47. package/src/plugins/integration-plugin.d.ts +1 -1
  48. package/src/plugins/processor.d.ts +1 -1
  49. package/src/plugins/tsconfig-import-resolver.d.ts +3 -1
  50. package/src/plugins/tsconfig-import-resolver.js +4 -2
  51. package/src/processor.d.ts +1 -1
  52. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.d.ts +2 -44
  53. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +14 -89
  54. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +4 -16
  55. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +2 -10
  56. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +3 -5
  57. package/src/route-renderer/orchestration/integration-renderer.d.ts +20 -44
  58. package/src/route-renderer/orchestration/integration-renderer.js +52 -115
  59. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.d.ts +3 -4
  60. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.js +4 -15
  61. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.d.ts +22 -0
  62. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.js +45 -0
  63. package/src/route-renderer/orchestration/page-browser-graph/grouped-graph-build-plan.d.ts +0 -1
  64. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +4 -3
  65. package/src/router/server/route-registry.d.ts +20 -9
  66. package/src/router/server/route-registry.js +52 -30
  67. package/src/router/server/segment-path-matcher.d.ts +8 -0
  68. package/src/router/server/segment-path-matcher.js +15 -0
  69. package/src/static-site-generator/production-page-browser-graph-prebuild.js +0 -4
  70. package/src/static-site-generator/static-site-generator.js +1 -1
  71. package/src/types/build-types.d.ts +6 -0
  72. package/src/types/contracts.d.ts +93 -65
  73. package/src/types/contracts.js +4 -1
  74. package/src/types/eco-api-types.d.ts +1 -1
  75. package/src/types/public-types.d.ts +1 -1
  76. package/src/utils/endpoint-file-extensions.d.ts +11 -0
  77. package/src/utils/endpoint-file-extensions.js +13 -0
  78. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.d.ts +0 -12
  79. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.js +0 -32
package/src/build.d.ts CHANGED
@@ -3,7 +3,7 @@ export { createBrowserRuntimePlugin, DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME, getBro
3
3
  export { getHostScopedJsxOwnershipPlugins } from './build/browser/jsx-ownership-plugins.js';
4
4
  export { isLitStaticRenderWorkerThread } from './build/browser/lit-static-render-worker-context.js';
5
5
  export { type BuildAdapter, type BuildExecutor, type BuildOptions, type BuildResult, setupAppRuntimeIntegrations, setupAppRuntimePlugins, teardownAppRuntimeIntegrations, } from './build/build-adapter.js';
6
- export { CONTENT_BROWSER_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 { 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';
7
7
  export { isServerOnlyModuleSpecifier } from './build/contracts/server-only-specifier.js';
8
8
  export { BuildQueue } from './build/runtime/build-queue.js';
9
9
  export { buildServerModule } from './build/server-module.js';
package/src/build.js CHANGED
@@ -3,7 +3,7 @@ export { createBrowserRuntimePlugin, DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME, getBro
3
3
  export { getHostScopedJsxOwnershipPlugins } from './build/browser/jsx-ownership-plugins.js';
4
4
  export { isLitStaticRenderWorkerThread } from './build/browser/lit-static-render-worker-context.js';
5
5
  export { setupAppRuntimeIntegrations, setupAppRuntimePlugins, teardownAppRuntimeIntegrations, } from './build/build-adapter.js';
6
- export { CONTENT_BROWSER_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 { 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';
7
7
  export { isServerOnlyModuleSpecifier } from './build/contracts/server-only-specifier.js';
8
8
  export { BuildQueue } from './build/runtime/build-queue.js';
9
9
  export { buildServerModule } from './build/server-module.js';
@@ -7,6 +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
11
  import { DEFAULT_ECOPAGES_DIST_DIR, DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT, DEFAULT_ECOPAGES_WORK_DIR, } from '../../constants.js';
11
12
  import { collectConfigModuleFiles } from '../config-module-files.js';
12
13
  import { DEFAULT_ECO_CONFIG_FILENAME, resolveUserConfigRootDir } from '../resolve-eco-config-path.js';
@@ -84,6 +85,10 @@ function collectTemplateExtensions(integrations) {
84
85
  if (names.has('kitajs') && names.has('react')) {
85
86
  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).');
86
87
  }
88
+ for (const integration of integrations) {
89
+ const reserved = integration.extensions.find((extension) => findEndpointFileExtension(extension));
90
+ invariant(reserved === undefined, `Integration "${integration.name}" registers "${reserved}", which is reserved for endpoint files: ${ENDPOINT_FILE_EXTENSIONS.join(', ')}.`);
91
+ }
87
92
  const extensions = integrations.flatMap((integration) => integration.extensions);
88
93
  const duplicateExtension = findDuplicate(extensions);
89
94
  invariant(duplicateExtension === undefined, `Integration extensions must be unique: "${duplicateExtension}" is registered by more than one Integration.`);
@@ -126,7 +126,7 @@ export class DevTransformServer {
126
126
  }
127
127
  async tryHandleRequest(request) {
128
128
  const url = new URL(request.url);
129
- const vendorResponse = this.vendorRegistry.tryHandleVendorRequest(url.pathname, request.headers.get('If-None-Match'));
129
+ const vendorResponse = await this.vendorRegistry.tryHandleVendorRequest(url.pathname, request.headers.get('If-None-Match'));
130
130
  if (vendorResponse) {
131
131
  return vendorResponse;
132
132
  }
@@ -6,23 +6,46 @@ export type DevTransformVendorRegistryOptions = {
6
6
  };
7
7
  /**
8
8
  * Lazily prebundles bare npm imports into process-local `/assets/vendors/*` chunks.
9
+ *
10
+ * @remarks
11
+ * A vendor bundle keeps the ESM imports of other packages external and points them at those packages' own
12
+ * vendor URLs, so a package shared by several vendors, such as a framework core, loads once in the browser
13
+ * and keeps one module identity. `require()` calls stay bundled, since a vendor URL is an ES module that
14
+ * `require()` cannot load.
9
15
  */
10
16
  export declare class DevTransformVendorRegistry {
11
17
  private readonly appConfig;
12
18
  private readonly browserBundleService;
13
19
  private readonly resolveVendorBundlePlugins?;
14
- private readonly cache;
15
- private readonly inFlight;
20
+ private records;
21
+ private recordsByUrl;
16
22
  constructor(options: DevTransformVendorRegistryOptions);
17
23
  resolveVendorUrl(specifier: string): Promise<string>;
18
24
  /**
19
25
  * @remarks
20
- * Responses carry `no-cache` and a content `ETag`, so browsers revalidate each
21
- * load and get `304` while `ifNoneMatch` still matches the in-memory bundle.
26
+ * A vendor that another vendor references may still be building when the browser asks for it, so the
27
+ * request waits for that build. Responses carry `no-cache` and a content `ETag`, so browsers revalidate
28
+ * each load and get `304` while `ifNoneMatch` still matches the in-memory bundle.
22
29
  */
23
- tryHandleVendorRequest(pathname: string, ifNoneMatch?: string | null): Response | null;
30
+ tryHandleVendorRequest(pathname: string, ifNoneMatch?: string | null): Promise<Response | null>;
24
31
  invalidateAll(): void;
32
+ /**
33
+ * Returns the record for a package entry, starting its build when no build exists yet.
34
+ *
35
+ * @remarks
36
+ * The build is not awaited here: two vendors that import each other would otherwise wait on each other.
37
+ * Failures are kept on the record and reported to whoever awaits the build or requests the URL.
38
+ */
39
+ private ensureVendor;
25
40
  private createVendorResponse;
26
- private prebundleSpecifier;
41
+ private prebundle;
42
+ /**
43
+ * Points the ESM imports of other packages inside one vendor bundle at those packages' vendor URLs.
44
+ *
45
+ * @remarks
46
+ * It runs after the vendor plugins, so a specifier the browser runtime manifest owns keeps the manifest's
47
+ * URL. Each dependency resolves from its importer, where a strict install places it.
48
+ */
49
+ private createSharedPackagePlugin;
27
50
  private resolvePackageEntry;
28
51
  }
@@ -2,7 +2,7 @@ import { contentHash } from '../../utils/content-hash.js';
2
2
  import path from 'node:path';
3
3
  import { RESOLVED_ASSETS_VENDORS_DIR } from '../../constants.js';
4
4
  import { resolveAppBuildPlugins } from '../../build/runtime/build-request-policy.js';
5
- import { resolveBarePackageBrowserEntry } from '../../plugins/tsconfig-import-resolver.js';
5
+ import { isBarePackageImportSpecifier, resolveBarePackageBrowserEntry, } from '../../plugins/tsconfig-import-resolver.js';
6
6
  import { toPackageRootSpecifier } from '../../plugins/package-specifier.js';
7
7
  import { BrowserBundleService } from '../../assets/browser-bundle.service.js';
8
8
  import { assertBuildSucceeded } from '../../build/build-log.js';
@@ -16,62 +16,89 @@ function getVendorBundleConditions(specifier) {
16
16
  }
17
17
  /**
18
18
  * Lazily prebundles bare npm imports into process-local `/assets/vendors/*` chunks.
19
+ *
20
+ * @remarks
21
+ * A vendor bundle keeps the ESM imports of other packages external and points them at those packages' own
22
+ * vendor URLs, so a package shared by several vendors, such as a framework core, loads once in the browser
23
+ * and keeps one module identity. `require()` calls stay bundled, since a vendor URL is an ES module that
24
+ * `require()` cannot load.
19
25
  */
20
26
  export class DevTransformVendorRegistry {
21
27
  appConfig;
22
28
  browserBundleService;
23
29
  resolveVendorBundlePlugins;
24
- cache = new Map();
25
- inFlight = new Map();
30
+ records = new Map();
31
+ recordsByUrl = new Map();
26
32
  constructor(options) {
27
33
  this.appConfig = options.appConfig;
28
34
  this.browserBundleService = new BrowserBundleService(options.appConfig);
29
35
  this.resolveVendorBundlePlugins = options.resolveVendorBundlePlugins;
30
36
  }
31
37
  async resolveVendorUrl(specifier) {
32
- const cached = this.cache.get(specifier);
33
- if (cached) {
34
- return cached.url;
35
- }
36
- const pending = this.inFlight.get(specifier);
37
- if (pending) {
38
- return (await pending).url;
39
- }
40
- const promise = this.prebundleSpecifier(specifier)
41
- .then((entry) => {
42
- if (this.inFlight.get(specifier) === promise) {
43
- this.cache.set(specifier, entry);
44
- }
45
- return entry;
46
- })
47
- .finally(() => {
48
- if (this.inFlight.get(specifier) === promise) {
49
- this.inFlight.delete(specifier);
50
- }
51
- });
52
- this.inFlight.set(specifier, promise);
53
- return (await promise).url;
38
+ const entryPath = this.resolvePackageEntry(specifier, this.appConfig.rootDir);
39
+ const record = this.ensureVendor(specifier, entryPath);
40
+ await record.build;
41
+ return record.url;
54
42
  }
55
43
  /**
56
44
  * @remarks
57
- * Responses carry `no-cache` and a content `ETag`, so browsers revalidate each
58
- * load and get `304` while `ifNoneMatch` still matches the in-memory bundle.
45
+ * A vendor that another vendor references may still be building when the browser asks for it, so the
46
+ * request waits for that build. Responses carry `no-cache` and a content `ETag`, so browsers revalidate
47
+ * each load and get `304` while `ifNoneMatch` still matches the in-memory bundle.
59
48
  */
60
- tryHandleVendorRequest(pathname, ifNoneMatch) {
61
- const prefix = `/${RESOLVED_ASSETS_VENDORS_DIR}/`;
62
- if (!pathname.startsWith(prefix)) {
49
+ async tryHandleVendorRequest(pathname, ifNoneMatch) {
50
+ if (!pathname.startsWith(`/${RESOLVED_ASSETS_VENDORS_DIR}/`)) {
63
51
  return null;
64
52
  }
65
- const fileName = pathname.slice(prefix.length);
66
- if (!fileName || fileName.includes('..')) {
53
+ const record = this.recordsByUrl.get(pathname);
54
+ if (!record) {
67
55
  return null;
68
56
  }
69
- const entry = [...this.cache.values()].find((cachedEntry) => cachedEntry.url === pathname);
70
- return entry ? this.createVendorResponse(entry, ifNoneMatch) : null;
57
+ try {
58
+ return this.createVendorResponse(await record.build, ifNoneMatch);
59
+ }
60
+ catch (error) {
61
+ return new Response(error instanceof Error ? error.message : String(error), {
62
+ status: 500,
63
+ headers: { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' },
64
+ });
65
+ }
71
66
  }
72
67
  invalidateAll() {
73
- this.cache.clear();
74
- this.inFlight.clear();
68
+ this.records = new Map();
69
+ this.recordsByUrl = new Map();
70
+ }
71
+ /**
72
+ * Returns the record for a package entry, starting its build when no build exists yet.
73
+ *
74
+ * @remarks
75
+ * The build is not awaited here: two vendors that import each other would otherwise wait on each other.
76
+ * Failures are kept on the record and reported to whoever awaits the build or requests the URL.
77
+ */
78
+ ensureVendor(specifier, entryPath) {
79
+ const existing = this.records.get(entryPath);
80
+ if (existing) {
81
+ return existing;
82
+ }
83
+ const records = this.records;
84
+ const record = {
85
+ specifier,
86
+ entryPath,
87
+ url: `/${RESOLVED_ASSETS_VENDORS_DIR}/${sanitizeSpecifierForFileName(specifier)}.${contentHash(entryPath, 8)}.js`,
88
+ build: Promise.resolve(undefined),
89
+ };
90
+ record.build = this.prebundle(record).then((entry) => {
91
+ if (this.records === records)
92
+ record.entry = entry;
93
+ return entry;
94
+ }, (error) => {
95
+ record.error = error;
96
+ throw error;
97
+ });
98
+ record.build.catch(() => { });
99
+ this.records.set(entryPath, record);
100
+ this.recordsByUrl.set(record.url, record);
101
+ return record;
75
102
  }
76
103
  createVendorResponse(entry, ifNoneMatch) {
77
104
  const etag = `"${contentHash(entry.content, 16)}"`;
@@ -83,38 +110,62 @@ export class DevTransformVendorRegistry {
83
110
  headers: { ...headers, 'Content-Type': 'application/javascript' },
84
111
  });
85
112
  }
86
- async prebundleSpecifier(specifier) {
87
- const resolvedEntry = this.resolvePackageEntry(specifier);
88
- const fileName = `${sanitizeSpecifierForFileName(specifier)}.${hashVendorSpecifier(specifier)}.js`;
89
- const url = `/${RESOLVED_ASSETS_VENDORS_DIR}/${fileName}`;
113
+ async prebundle(record) {
90
114
  const vendorPlugins = this.resolveVendorBundlePlugins ? await this.resolveVendorBundlePlugins() : [];
91
115
  const result = await this.browserBundleService.bundle({
92
116
  lane: 'build',
93
- entrypoints: [resolvedEntry.path],
117
+ entrypoints: [record.entryPath],
94
118
  outdir: path.join(this.appConfig.absolutePaths.workDir, 'vendor-memory'),
95
- naming: fileName,
119
+ naming: path.basename(record.url),
96
120
  writeToDisk: false,
97
121
  minify: false,
98
122
  externalPackages: false,
99
123
  treeshaking: true,
100
124
  splitting: false,
101
- conditions: [...getVendorBundleConditions(specifier)],
125
+ conditions: [...getVendorBundleConditions(record.specifier)],
102
126
  excludeAppBuildPlugins: resolveAppBuildPlugins(this.appConfig, 'browser').map((plugin) => plugin.name),
103
- plugins: [...vendorPlugins],
127
+ plugins: [...vendorPlugins, this.createSharedPackagePlugin(record)],
104
128
  });
105
- assertBuildSucceeded(result, (details) => formatVendorPrebundleError(specifier, details));
129
+ assertBuildSucceeded(result, (details) => formatVendorPrebundleError(record.specifier, details));
106
130
  const output = result.outputs.find((candidate) => typeof candidate.content === 'string');
107
131
  if (!output || typeof output.content !== 'string') {
108
- throw new Error(`[dev-transform] Vendor prebundle produced no in-memory JavaScript for ${specifier}`);
132
+ throw new Error(`[dev-transform] Vendor prebundle produced no in-memory JavaScript for ${record.specifier}`);
109
133
  }
110
- return { url, content: output.content };
134
+ return { url: record.url, content: output.content };
111
135
  }
112
- resolvePackageEntry(specifier) {
113
- const resolved = resolveBarePackageBrowserEntry(this.appConfig.rootDir, specifier);
136
+ /**
137
+ * Points the ESM imports of other packages inside one vendor bundle at those packages' vendor URLs.
138
+ *
139
+ * @remarks
140
+ * It runs after the vendor plugins, so a specifier the browser runtime manifest owns keeps the manifest's
141
+ * URL. Each dependency resolves from its importer, where a strict install places it.
142
+ */
143
+ createSharedPackagePlugin(record) {
144
+ return {
145
+ name: 'ecopages-dev-vendor-shared-packages',
146
+ environments: ['browser'],
147
+ setup: (build) => {
148
+ build.onResolve({ filter: /.*/u }, (args) => {
149
+ if (!args.importer || args.namespace)
150
+ return undefined;
151
+ if (args.kind !== 'import-statement' && args.kind !== 'dynamic-import')
152
+ return undefined;
153
+ if (!isBarePackageImportSpecifier(args.path))
154
+ return undefined;
155
+ const dependency = resolveBarePackageBrowserEntry(this.appConfig.rootDir, args.path, path.dirname(args.importer));
156
+ if (!dependency || dependency.path === record.entryPath)
157
+ return undefined;
158
+ return { path: this.ensureVendor(args.path, dependency.path).url, external: true };
159
+ });
160
+ },
161
+ };
162
+ }
163
+ resolvePackageEntry(specifier, fromDirectory) {
164
+ const resolved = resolveBarePackageBrowserEntry(this.appConfig.rootDir, specifier, fromDirectory);
114
165
  if (!resolved) {
115
166
  throw new Error(`[dev-transform] Unable to resolve bare import "${specifier}" for vendor prebundle`);
116
167
  }
117
- return { path: resolved.path };
168
+ return resolved.path;
118
169
  }
119
170
  }
120
171
  function formatVendorPrebundleError(specifier, details) {
@@ -130,9 +181,6 @@ function formatVendorPrebundleError(specifier, details) {
130
181
  function sanitizeSpecifierForFileName(specifier) {
131
182
  return specifier.replaceAll(/^@/gu, '').replaceAll(/[/:@]/gu, '-');
132
183
  }
133
- function hashVendorSpecifier(specifier) {
134
- return contentHash(specifier, 8);
135
- }
136
184
  /**
137
185
  * Whether an `If-None-Match` header matches `etag` under the weak comparison of
138
186
  * RFC 9110: any listed tag equal to it once `W/` is stripped, or `*`.
@@ -22,6 +22,15 @@ export declare class HttpError extends Error {
22
22
  * Prefer this over `instanceof` when catching errors from app page bundles.
23
23
  */
24
24
  static isHttpError(error: unknown): error is HttpError;
25
+ /**
26
+ * Answers with an error's status and JSON body, whichever `HttpError` class threw it.
27
+ *
28
+ * @remarks
29
+ * An error that passed {@link HttpError.isHttpError} may come from an app bundle's own copy of
30
+ * this class, or be a duck-typed object without `toResponse()`, so the response is rebuilt from
31
+ * its fields.
32
+ */
33
+ static responseFor(error: HttpError): Response;
25
34
  /**
26
35
  * Serialize error to JSON for API responses.
27
36
  */
@@ -27,6 +27,17 @@ export class HttpError extends Error {
27
27
  error.name === 'HttpError' &&
28
28
  typeof error.status === 'number');
29
29
  }
30
+ /**
31
+ * Answers with an error's status and JSON body, whichever `HttpError` class threw it.
32
+ *
33
+ * @remarks
34
+ * An error that passed {@link HttpError.isHttpError} may come from an app bundle's own copy of
35
+ * this class, or be a duck-typed object without `toResponse()`, so the response is rebuilt from
36
+ * its fields.
37
+ */
38
+ static responseFor(error) {
39
+ return new HttpError(error.status, error.message, error.details).toResponse();
40
+ }
30
41
  /**
31
42
  * Serialize error to JSON for API responses.
32
43
  */
@@ -1,4 +1,3 @@
1
- import type { ProcessedAsset } from '../assets/asset-processing-service/assets.types.js';
2
1
  import type { PagePackageResult } from '../types/contracts.js';
3
2
  export type HtmlDocumentContributionPlacement = 'head-prepend' | 'head-append' | 'body-prepend' | 'body-append';
4
3
  export type HtmlDocumentContribution = {
@@ -26,30 +25,10 @@ export declare class HtmlTransformerService {
26
25
  * Sets attributes on the first `<html>` start tag.
27
26
  */
28
27
  applyAttributesToHtmlElement(html: string, attributes: Record<string, string>): string;
29
- /**
30
- * Sets attributes on the element that directly follows the `<body>` start tag.
31
- *
32
- * @remarks
33
- * Nothing is stamped when text or a comment comes first (whitespace aside).
34
- */
35
- applyAttributesToFirstBodyElement(html: string, attributes: Record<string, string>): string;
36
- /**
37
- * Removes duplicate processed assets while preserving first-seen order.
38
- *
39
- * @remarks
40
- * Dedupe keys include structural asset fields and HTML attributes so repeated
41
- * orchestration passes can merge assets safely without collapsing distinct tag
42
- * variants.
43
- */
44
- dedupeProcessedAssets(assets: ProcessedAsset[]): ProcessedAsset[];
45
28
  /**
46
29
  * Injects page assets and document contributions into a streaming HTML response.
47
30
  */
48
31
  transform(res: Response, input?: PageAssetInjection): Response;
49
- /**
50
- * Injects page assets and document contributions into a complete HTML string.
51
- */
52
- injectPageAssets(html: string, input?: PageAssetInjection): string;
53
32
  /**
54
33
  * @remarks
55
34
  * Each slot is inserted as one joined string, so contributions and assets keep
@@ -43,44 +43,12 @@ export class HtmlTransformerService {
43
43
  applyAttributesToHtmlElement(html, attributes) {
44
44
  return stampAttributes(html, attributes, (element) => element.tagName === 'html');
45
45
  }
46
- /**
47
- * Sets attributes on the element that directly follows the `<body>` start tag.
48
- *
49
- * @remarks
50
- * Nothing is stamped when text or a comment comes first (whitespace aside).
51
- */
52
- applyAttributesToFirstBodyElement(html, attributes) {
53
- let insideBody = false;
54
- return stampAttributes(html, attributes, (element) => {
55
- if (insideBody)
56
- return true;
57
- insideBody = element.tagName === 'body';
58
- return false;
59
- }, { leadingOnly: true });
60
- }
61
- /**
62
- * Removes duplicate processed assets while preserving first-seen order.
63
- *
64
- * @remarks
65
- * Dedupe keys include structural asset fields and HTML attributes so repeated
66
- * orchestration passes can merge assets safely without collapsing distinct tag
67
- * variants.
68
- */
69
- dedupeProcessedAssets(assets) {
70
- return dedupeProcessedAssets(assets);
71
- }
72
46
  /**
73
47
  * Injects page assets and document contributions into a streaming HTML response.
74
48
  */
75
49
  transform(res, input = {}) {
76
50
  return this.createRewriter(input.contributions ?? [], input.pagePackage).transform(res);
77
51
  }
78
- /**
79
- * Injects page assets and document contributions into a complete HTML string.
80
- */
81
- injectPageAssets(html, input = {}) {
82
- return this.createRewriter(input.contributions ?? [], input.pagePackage).transform(html);
83
- }
84
52
  /**
85
53
  * @remarks
86
54
  * Each slot is inserted as one joined string, so contributions and assets keep
@@ -31,10 +31,11 @@ export declare class HtmlPageRenderer extends StringMarkupRenderer {
31
31
  * A direct call reconciles here, so the Page head is never dropped.
32
32
  */
33
33
  render(options: IntegrationRendererRenderOptions): Promise<RouteRendererBody>;
34
+ renderRouteBody(options: InternalIntegrationRendererRenderOptions): Promise<RouteRendererBody>;
34
35
  /**
35
36
  * Renders the Page body and retains its head until core document contributions have been applied.
36
37
  */
37
- renderRouteBody(options: InternalIntegrationRendererRenderOptions): Promise<RouteRendererBody>;
38
+ protected renderRouteDocument(options: IntegrationRendererRenderOptions): Promise<RouteRendererBody>;
38
39
  private finalizeHtmlPageDocument;
39
40
  private renderHtmlPage;
40
41
  /**
@@ -86,13 +86,15 @@ export class HtmlPageRenderer extends StringMarkupRenderer {
86
86
  * A direct call reconciles here, so the Page head is never dropped.
87
87
  */
88
88
  async render(options) {
89
- const { html, head } = await this.renderHtmlPage(options);
90
- return reconcileHtmlPageDocument(html, head);
89
+ return this.finalizeHtmlPageDocument(await super.render(options), options);
90
+ }
91
+ async renderRouteBody(options) {
92
+ return super.render(options);
91
93
  }
92
94
  /**
93
95
  * Renders the Page body and retains its head until core document contributions have been applied.
94
96
  */
95
- async renderRouteBody(options) {
97
+ async renderRouteDocument(options) {
96
98
  const rendered = await this.renderHtmlPage(options);
97
99
  this.renderedHeads.set(options, rendered.head);
98
100
  return rendered.html;
package/src/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export type * from './types/public-types.js';
2
2
  export { eco } from './eco/eco.js';
3
- export { defineApiHandler, defineGroupHandler, defineGet, definePost, definePut, defineDelete, definePatch, defineOptions, defineHead, json, html, redirect, type GroupHandler, } from './adapters/shared/http/define-api-handler.js';
3
+ export { defineApiHandler, defineGroupHandler, defineGet, definePost, definePut, defineDelete, definePatch, defineOptions, defineHead, defineQuery, json, html, redirect, type GroupHandler, } from './adapters/shared/http/define-api-handler.js';
4
4
  export { attributeMdxComponentIdentity } from './plugins/eco-component-meta-plugin.js';
5
5
  export { bindComponentIdentity, getComponentIdentity, getComponentOwner, type ComponentIdentity, } from './eco/component-identity.js';
6
6
  export { attachDiscoveredDependencies } from './eco/discovered-dependencies.js';
package/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { eco } from './eco/eco.js';
2
- export { defineApiHandler, defineGroupHandler, defineGet, definePost, definePut, defineDelete, definePatch, defineOptions, defineHead, json, html, redirect, } from './adapters/shared/http/define-api-handler.js';
2
+ export { defineApiHandler, defineGroupHandler, defineGet, definePost, definePut, defineDelete, definePatch, defineOptions, defineHead, defineQuery, json, html, redirect, } from './adapters/shared/http/define-api-handler.js';
3
3
  export { attributeMdxComponentIdentity } from './plugins/eco-component-meta-plugin.js';
4
4
  export { bindComponentIdentity, getComponentIdentity, getComponentOwner, } from './eco/component-identity.js';
5
5
  export { attachDiscoveredDependencies } from './eco/discovered-dependencies.js';
@@ -6,12 +6,11 @@ export { type ForeignChildInterceptionInput, type ForeignChildInterceptionResult
6
6
  export { ensurePageConfigLayouts } from './eco/page-layout-normalization.js';
7
7
  export { collectJsxExtensions, createJsxImportSourcePragma, filterJsxSourceExtensions, isJsxSourceExtension, } from './plugins/jsx-import-source.utils.js';
8
8
  export { resolveDocumentShellLayouts, resolveInnermostPageLayout, resolveLayoutEntryProps, resolveLayoutShellProps, resolvePageLayoutComponents, type DocumentShellLayoutResolutionInput, type LayoutShellPropsContext, } from './route-renderer/orchestration/document-shell/layout-shell-props.service.js';
9
- export { mergePageBrowserGraph } from './route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.js';
10
9
  export { isRegisteredDevTransformEntrypoint, isRegisteredScriptEntrypoint } from './hmr/hmr-entrypoint-output.js';
11
10
  export { type HmrRegisteredEntrypointsContext } from './hmr/hmr-registered-entrypoints-context.js';
12
11
  export { HmrStrategy, HmrStrategyType } from './hmr/hmr-strategy.js';
13
12
  export { type DefinedIntegration, defineIntegration } from './plugins/define-integration.js';
14
- export { type AnyIntegrationPlugin, type EcoBuildOnLoadArgs, type EcoBuildOnLoadResult, type EcoBuildOnResolveArgs, type EcoBuildOnResolveResult, type EcoBuildPlugin, type EcoBuildPluginBuilder, IntegrationPlugin, type IntegrationPluginConfig, type IntegrationRendererBase, type IntegrationRuntimeContext, mergeIntegrationOptions, type StaticExportContext, type StaticExportRelease, } from './plugins/integration-plugin.js';
13
+ export { type AnyIntegrationPlugin, type EcoBuildOnLoadArgs, type EcoBuildOnLoadResult, type EcoBuildImportKind, type EcoBuildOnResolveArgs, type EcoBuildOnResolveResult, type EcoBuildPlugin, type EcoBuildPluginBuilder, IntegrationPlugin, type IntegrationPluginConfig, type IntegrationRendererBase, type IntegrationRuntimeContext, mergeIntegrationOptions, type StaticExportContext, type StaticExportRelease, } from './plugins/integration-plugin.js';
15
14
  export { CUSTOM_ELEMENT_SSR_PRELOAD_CACHE_SCOPES, CustomElementScriptPreloader, type CustomElementScriptPreloadScopeState, type CustomElementSsrPreloadComponent, invalidateCustomElementScriptPreload, } from './route-renderer/orchestration/custom-element-scripts/custom-element-script-preloader.js';
16
15
  export { createCustomElementServerModuleImporter, createSharedServerModuleImporter, } from './route-renderer/orchestration/custom-element-scripts/custom-element-server-module-importer.js';
17
16
  export { createCustomElementSsrPipelineImporter } from './route-renderer/orchestration/custom-element-scripts/custom-element-ssr-preload-entrypoint.js';
@@ -5,7 +5,6 @@ export { getComponentRenderContext, runWithComponentRenderContext, } from './eco
5
5
  export { ensurePageConfigLayouts } from './eco/page-layout-normalization.js';
6
6
  export { collectJsxExtensions, createJsxImportSourcePragma, filterJsxSourceExtensions, isJsxSourceExtension, } from './plugins/jsx-import-source.utils.js';
7
7
  export { resolveDocumentShellLayouts, resolveInnermostPageLayout, resolveLayoutEntryProps, resolveLayoutShellProps, resolvePageLayoutComponents, } from './route-renderer/orchestration/document-shell/layout-shell-props.service.js';
8
- export { mergePageBrowserGraph } from './route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.js';
9
8
  export { isRegisteredDevTransformEntrypoint, isRegisteredScriptEntrypoint } from './hmr/hmr-entrypoint-output.js';
10
9
  export {} from './hmr/hmr-registered-entrypoints-context.js';
11
10
  export { HmrStrategy, HmrStrategyType } from './hmr/hmr-strategy.js';
@@ -27,8 +27,7 @@ export declare function componentRenderHasIslandBootstrap(assets: Array<{
27
27
  *
28
28
  * @param ownAssets - Assets of the component and its same-Integration nested components, excluding Foreign Children
29
29
  * and the Foreign Subtrees rendered inside it.
30
- * @remarks The decision ignores `result.assets`, which usually also carries Foreign Subtree assets: a component
31
- * without scripts that wraps an island is not an island itself.
30
+ * @remarks A component without scripts that wraps an island is not an island itself.
32
31
  */
33
32
  export declare function finalizeIslandComponentRender<T extends {
34
33
  canAttachAttributes: boolean;
@@ -46,8 +46,7 @@ export function componentRenderHasIslandBootstrap(assets) {
46
46
  *
47
47
  * @param ownAssets - Assets of the component and its same-Integration nested components, excluding Foreign Children
48
48
  * and the Foreign Subtrees rendered inside it.
49
- * @remarks The decision ignores `result.assets`, which usually also carries Foreign Subtree assets: a component
50
- * without scripts that wraps an island is not an island itself.
49
+ * @remarks A component without scripts that wraps an island is not an island itself.
51
50
  */
52
51
  export function finalizeIslandComponentRender(input, result, ownAssets) {
53
52
  const componentInstanceId = input.integrationContext?.componentInstanceId;
@@ -7,7 +7,7 @@ import type { IntegrationRenderer, IntegrationRendererOptions } from '../route-r
7
7
  import { AssetProcessingService } from '../assets/asset-processing-service/asset-processing.service.js';
8
8
  import type { AssetDefinition, ProcessedAsset } from '../assets/asset-processing-service/assets.types.js';
9
9
  import type { StaticExportContext, StaticExportRelease } from '../static-site-generator/static-export-context.js';
10
- export type { EcoBuildLoader, EcoBuildOnLoadArgs, EcoBuildOnLoadResult, EcoBuildOnResolveArgs, EcoBuildOnResolveResult, EcoBuildPlugin, EcoBuildPluginBuilder, } from '../build/contracts/build-types.js';
10
+ export type { EcoBuildLoader, EcoBuildOnLoadArgs, EcoBuildOnLoadResult, EcoBuildImportKind, EcoBuildOnResolveArgs, EcoBuildOnResolveResult, EcoBuildPlugin, EcoBuildPluginBuilder, } from '../build/contracts/build-types.js';
11
11
  export type { PageBrowserGraphContribution, PageBrowserGraphContributionContext } from '../types/contracts.js';
12
12
  export type { StaticExportContext, StaticExportRelease } from '../static-site-generator/static-export-context.js';
13
13
  export type { HtmlDocumentContribution, HtmlDocumentContributionContext, } from '../route-renderer/orchestration/integration-renderer.js';
@@ -1,7 +1,7 @@
1
1
  import type { EcoBuildPlugin } from '../build/contracts/build-types.js';
2
2
  import type { EcoPagesAppConfig, IClientBridge } from '../config/internal-types.js';
3
3
  import { GENERATED_BASE_PATHS } from '../constants.js';
4
- export type { EcoBuildLoader, EcoBuildOnLoadArgs, EcoBuildOnLoadResult, EcoBuildOnResolveArgs, EcoBuildOnResolveResult, EcoBuildPlugin, EcoBuildPluginBuilder, } from '../build/contracts/build-types.js';
4
+ export type { EcoBuildLoader, EcoBuildOnLoadArgs, EcoBuildOnLoadResult, EcoBuildImportKind, EcoBuildOnResolveArgs, EcoBuildOnResolveResult, EcoBuildPlugin, EcoBuildPluginBuilder, } from '../build/contracts/build-types.js';
5
5
  export declare const PROCESSOR_ERRORS: {
6
6
  readonly CACHE_DIRECTORY_NOT_SET: "Cache directory not set in context";
7
7
  };
@@ -11,6 +11,8 @@ export declare function isBarePackageImportSpecifier(specifier: string, projectR
11
11
  /**
12
12
  * Resolves a bare npm package entry for browser vendor prebundles.
13
13
  *
14
+ * @param fromDirectory - Where resolution starts. Defaults to `projectRoot`; a vendor's own dependency
15
+ * resolves from the importing file's directory, since strict installs do not expose it at the root.
14
16
  * @returns The entry `path` and the installed package's root `package.json`
15
17
  * (`packageJsonPath`), which stays the root manifest when the entry sits below a
16
18
  * nested one such as `cjs/package.json`.
@@ -22,7 +24,7 @@ export declare function isBarePackageImportSpecifier(specifier: string, projectR
22
24
  * export condition so legacy UMD `exports.browser` entries cannot win during
23
25
  * Rolldown bundling.
24
26
  */
25
- export declare function resolveBarePackageBrowserEntry(projectRoot: string, specifier: string): {
27
+ export declare function resolveBarePackageBrowserEntry(projectRoot: string, specifier: string, fromDirectory?: string): {
26
28
  path: string;
27
29
  packageJsonPath?: string;
28
30
  } | undefined;
@@ -153,6 +153,8 @@ function getBrowserPackageResolver(projectRoot, mainFields, conditionNames) {
153
153
  /**
154
154
  * Resolves a bare npm package entry for browser vendor prebundles.
155
155
  *
156
+ * @param fromDirectory - Where resolution starts. Defaults to `projectRoot`; a vendor's own dependency
157
+ * resolves from the importing file's directory, since strict installs do not expose it at the root.
156
158
  * @returns The entry `path` and the installed package's root `package.json`
157
159
  * (`packageJsonPath`), which stays the root manifest when the entry sits below a
158
160
  * nested one such as `cjs/package.json`.
@@ -164,11 +166,11 @@ function getBrowserPackageResolver(projectRoot, mainFields, conditionNames) {
164
166
  * export condition so legacy UMD `exports.browser` entries cannot win during
165
167
  * Rolldown bundling.
166
168
  */
167
- export function resolveBarePackageBrowserEntry(projectRoot, specifier) {
169
+ export function resolveBarePackageBrowserEntry(projectRoot, specifier, fromDirectory = projectRoot) {
168
170
  const browserFirst = usesBrowserFirstPackageResolution(specifier);
169
171
  const mainFields = browserFirst ? BROWSER_FIRST_MAIN_FIELDS : MODULE_FIRST_MAIN_FIELDS;
170
172
  const conditionNames = browserFirst ? BROWSER_FIRST_CONDITION_NAMES : MODULE_FIRST_CONDITION_NAMES;
171
- const result = getBrowserPackageResolver(projectRoot, mainFields, conditionNames).sync(projectRoot, specifier);
173
+ const result = getBrowserPackageResolver(projectRoot, mainFields, conditionNames).sync(fromDirectory, specifier);
172
174
  if (result.error || !result.path) {
173
175
  return undefined;
174
176
  }
@@ -1,4 +1,4 @@
1
1
  export { writeHashedBrowserAsset } from './assets/hashed-browser-asset.js';
2
2
  export type { AssetDefinition, ProcessedAsset } from './types/asset-types.js';
3
- export { type EcoBuildOnLoadResult, type EcoBuildOnResolveArgs, type EcoBuildPlugin, type EcoBuildPluginBuilder, mergeProcessorOptions, Processor, type ProcessorConfig, type ProcessorContext, type ProcessorWatchChanges, type ProcessorWatchConfig, resolveGeneratedPath, writeGeneratedTypesPackage, } from './plugins/processor.js';
3
+ export { type EcoBuildOnLoadResult, type EcoBuildImportKind, type EcoBuildOnResolveArgs, type EcoBuildPlugin, type EcoBuildPluginBuilder, mergeProcessorOptions, Processor, type ProcessorConfig, type ProcessorContext, type ProcessorWatchChanges, type ProcessorWatchConfig, resolveGeneratedPath, writeGeneratedTypesPackage, } from './plugins/processor.js';
4
4
  export { getEcopagesEnv, isDevelopmentRuntime, isEcopagesEnvDisabled, isEcopagesEnvEnabled, isProductionRuntime, type EcopagesBooleanEnvironmentVariable, type EcopagesEnvironmentVariable, } from './env.js';