@ecopages/core 0.9.0 → 0.10.1

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 (53) hide show
  1. package/package.json +3 -3
  2. package/src/adapters/node/create-app.d.ts +4 -4
  3. package/src/adapters/shared/http/api-request-pipeline.js +8 -6
  4. package/src/adapters/shared/http/define-api-handler.d.ts +8 -8
  5. package/src/adapters/shared/http/file-route-middleware-pipeline.d.ts +10 -11
  6. package/src/adapters/shared/http/file-route-middleware-pipeline.js +5 -6
  7. package/src/adapters/shared/http/fs-server-response-matcher.js +12 -4
  8. package/src/adapters/shared/http/run-middleware-chain.d.ts +29 -2
  9. package/src/adapters/shared/http/run-middleware-chain.js +108 -10
  10. package/src/adapters/shared/runtime/render-context.js +2 -21
  11. package/src/build/runtime/build-request-policy.js +4 -1
  12. package/src/build.d.ts +1 -0
  13. package/src/build.js +1 -0
  14. package/src/declarations.d.ts +2 -0
  15. package/src/eco/eco.browser.js +6 -26
  16. package/src/eco/eco.js +5 -16
  17. package/src/eco/page-data-hooks.d.ts +27 -0
  18. package/src/eco/page-data-hooks.js +64 -0
  19. package/src/eco/page-layout-normalization.d.ts +2 -2
  20. package/src/index.d.ts +1 -0
  21. package/src/index.js +1 -0
  22. package/src/integration.d.ts +1 -1
  23. package/src/integration.js +1 -1
  24. package/src/middleware/create-middleware.d.ts +41 -0
  25. package/src/middleware/create-middleware.js +72 -0
  26. package/src/plugins/eco-component-meta-plugin.d.ts +33 -0
  27. package/src/plugins/eco-component-meta-plugin.js +170 -23
  28. package/src/route-renderer/error-pages/error-page-renderer.js +29 -1
  29. package/src/route-renderer/explicit-view-render-preparation.d.ts +18 -0
  30. package/src/route-renderer/explicit-view-render-preparation.js +53 -7
  31. package/src/route-renderer/orchestration/document-shell/layout-shell-props.service.d.ts +15 -5
  32. package/src/route-renderer/orchestration/document-shell/layout-shell-props.service.js +27 -15
  33. package/src/route-renderer/orchestration/integration-renderer.d.ts +3 -1
  34. package/src/route-renderer/orchestration/integration-renderer.js +10 -6
  35. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.builder.js +0 -3
  36. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.d.ts +4 -0
  37. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +6 -1
  38. package/src/route-renderer/page-loading/page-module-loader.d.ts +27 -7
  39. package/src/route-renderer/page-loading/page-module-loader.js +46 -15
  40. package/src/route-renderer/page-loading/resolved-page-dependencies.js +14 -9
  41. package/src/static-site-generator/static-site-generator.d.ts +0 -1
  42. package/src/static-site-generator/static-site-generator.js +6 -6
  43. package/src/types/contracts.d.ts +196 -140
  44. package/src/types/eco-api-types.d.ts +76 -46
  45. package/src/types/locals-brand.d.ts +9 -0
  46. package/src/types/locals-brand.js +9 -0
  47. package/src/types/middleware-types.d.ts +143 -0
  48. package/src/types/middleware-types.js +1 -0
  49. package/src/types/public-types.d.ts +3 -2
  50. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.utils.d.ts +0 -4
  51. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.utils.js +0 -30
  52. package/src/utils/locals-utils.d.ts +0 -15
  53. package/src/utils/locals-utils.js +0 -34
package/src/eco/eco.js CHANGED
@@ -8,6 +8,8 @@ import { applyPageLayoutConfig, mergeLayoutDependencies, normalizePageLayouts }
8
8
  import { getComponentIdentity, getComponentOwner } from './component-identity.js';
9
9
  import { attachDiscoveredDependencies } from './discovered-dependencies.js';
10
10
  import { DATA_HOOKS_MIGRATION_URL } from './migration-docs.js';
11
+ import { flattenMiddleware } from '../middleware/create-middleware.js';
12
+ import { attachPageOptions } from './page-data-hooks.js';
11
13
  /**
12
14
  * Creates a component factory with lazy-trigger support and foreign-child-runtime
13
15
  * interception.
@@ -136,9 +138,8 @@ function assertNoRenamedPageOptions(options) {
136
138
  */
137
139
  function page(options) {
138
140
  assertNoRenamedPageOptions(options);
139
- const { layout, dependencies: dependenciesInput, render, paths, props, metadata, cache, requires, middleware, } = options;
141
+ const { layout, dependencies: dependenciesInput, render, middleware } = options;
140
142
  const layoutEntries = normalizePageLayouts(layout);
141
- const resolveDependencies = typeof dependenciesInput === 'function' ? dependenciesInput : undefined;
142
143
  const staticDependencies = typeof dependenciesInput === 'function'
143
144
  ? mergeLayoutDependencies(undefined, layoutEntries)
144
145
  : mergeLayoutDependencies(dependenciesInput, layoutEntries);
@@ -152,21 +153,9 @@ function page(options) {
152
153
  if (pageComponent.config) {
153
154
  applyPageLayoutConfig(pageComponent.config, layoutEntries);
154
155
  }
155
- if (paths)
156
- pageComponent.paths = paths;
157
- if (props)
158
- pageComponent.props = props;
159
- if (metadata)
160
- pageComponent.metadata = metadata;
161
- if (resolveDependencies)
162
- pageComponent.resolveDependencies = resolveDependencies;
163
- if (cache)
164
- pageComponent.cache = cache;
165
- if (requires)
166
- pageComponent.requires = requires;
167
156
  if (middleware)
168
- pageComponent.middleware = middleware;
169
- return pageComponent;
157
+ flattenMiddleware(middleware, 'page middleware');
158
+ return attachPageOptions(pageComponent, options);
170
159
  }
171
160
  /**
172
161
  * The eco namespace - provides factories for components and pages
@@ -0,0 +1,27 @@
1
+ import type { DynamicEcoPageComponent, EcoComponent, EcoPageComponent, PagePropsFor } from '../types/contracts.js';
2
+ import type { PageOptions } from '../types/eco-api-types.js';
3
+ /**
4
+ * Adds the options `eco.page()` keeps on the Page to its rendered component.
5
+ *
6
+ * @remarks
7
+ * The `props` and dependency hooks are kept by Cache Strategy, so the result is the matching member of
8
+ * {@link EcoPageComponent}: a Dynamic Page's hooks take the request context, any other Page's the build context.
9
+ */
10
+ export declare function attachPageOptions<T, E>(component: EcoComponent<PagePropsFor<T>>, options: PageOptions<T, E>): EcoPageComponent<T>;
11
+ /**
12
+ * Whether a loaded Page declares `cache: 'dynamic'`, read from an untyped module export or a typed Page.
13
+ *
14
+ * @remarks
15
+ * It narrows to the Dynamic Page member of {@link EcoPageComponent}, so code that holds a loaded module calls it
16
+ * instead of reading `cache` itself.
17
+ */
18
+ export declare function isDynamicPage(page: unknown): page is DynamicEcoPageComponent<any>;
19
+ /**
20
+ * Throws when a Page's `props` hook returned a key that {@link NoRouteProps} bars.
21
+ *
22
+ * @remarks
23
+ * The hook's type rejects those keys; this catches a hook whose types do not, such as one that returns `any` or a
24
+ * Page written in JavaScript. A `null` or `undefined` result passes, and so does a barred key set to `undefined`, which
25
+ * the type allows and the route overwrites.
26
+ */
27
+ export declare function assertNoRouteProps(props: unknown, source: string): void;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Adds the options `eco.page()` keeps on the Page to its rendered component.
3
+ *
4
+ * @remarks
5
+ * The `props` and dependency hooks are kept by Cache Strategy, so the result is the matching member of
6
+ * {@link EcoPageComponent}: a Dynamic Page's hooks take the request context, any other Page's the build context.
7
+ */
8
+ export function attachPageOptions(component, options) {
9
+ const statics = options.cache === 'dynamic' ? createDynamicStatics(options) : createStaticStatics(options);
10
+ if (options.paths)
11
+ statics.paths = options.paths;
12
+ if (options.metadata)
13
+ statics.metadata = options.metadata;
14
+ if (options.middleware)
15
+ statics.middleware = options.middleware;
16
+ return Object.assign(component, statics);
17
+ }
18
+ function createDynamicStatics(options) {
19
+ const statics = { cache: 'dynamic' };
20
+ if (options.props)
21
+ statics.props = options.props;
22
+ if (typeof options.dependencies === 'function')
23
+ statics.resolveDependencies = options.dependencies;
24
+ return statics;
25
+ }
26
+ function createStaticStatics(options) {
27
+ const statics = {};
28
+ if (options.cache)
29
+ statics.cache = options.cache;
30
+ if (options.props)
31
+ statics.props = options.props;
32
+ if (typeof options.dependencies === 'function')
33
+ statics.resolveDependencies = options.dependencies;
34
+ return statics;
35
+ }
36
+ /**
37
+ * Whether a loaded Page declares `cache: 'dynamic'`, read from an untyped module export or a typed Page.
38
+ *
39
+ * @remarks
40
+ * It narrows to the Dynamic Page member of {@link EcoPageComponent}, so code that holds a loaded module calls it
41
+ * instead of reading `cache` itself.
42
+ */
43
+ export function isDynamicPage(page) {
44
+ return typeof page === 'function' && 'cache' in page && page.cache === 'dynamic';
45
+ }
46
+ /** The keys of {@link NoRouteProps}, listed once so the type and this check cannot drift apart. */
47
+ const ROUTE_PROPS = { params: true, query: true };
48
+ /**
49
+ * Throws when a Page's `props` hook returned a key that {@link NoRouteProps} bars.
50
+ *
51
+ * @remarks
52
+ * The hook's type rejects those keys; this catches a hook whose types do not, such as one that returns `any` or a
53
+ * Page written in JavaScript. A `null` or `undefined` result passes, and so does a barred key set to `undefined`, which
54
+ * the type allows and the route overwrites.
55
+ */
56
+ export function assertNoRouteProps(props, source) {
57
+ if (typeof props !== 'object' || props === null)
58
+ return;
59
+ for (const key of Object.keys(ROUTE_PROPS)) {
60
+ if (Object.hasOwn(props, key) && Reflect.get(props, key) !== undefined) {
61
+ throw new Error(`[ecopages] The props hook of ${source} returned "${key}", a key render receives from the route. Rename the prop.`);
62
+ }
63
+ }
64
+ }
@@ -1,8 +1,8 @@
1
- import type { EcoComponentConfig, EcoComponentDependencies, EcoPageLayoutEntry, EcoPageLayouts } from '../types/contracts.js';
1
+ import type { EcoComponentConfig, EcoComponentDependencies, EcoPageLayoutEntry, EcoPageLayouts, LayoutRequestContext } from '../types/contracts.js';
2
2
  /**
3
3
  * Normalizes `layout` page options to an outer→inner stack of layout entries.
4
4
  */
5
- export declare function normalizePageLayouts<E>(layout?: EcoPageLayouts<E>): EcoPageLayoutEntry[];
5
+ export declare function normalizePageLayouts<E>(layout?: EcoPageLayouts<E, LayoutRequestContext>): EcoPageLayoutEntry[];
6
6
  /**
7
7
  * Merges `eco.layout()` components into `dependencies.components` without duplicates.
8
8
  *
package/src/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export type * from './types/public-types.js';
2
2
  export { eco } from './eco/eco.js';
3
+ export { composeMiddleware, createMiddleware } from './middleware/create-middleware.js';
3
4
  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
5
  export { createViewReference } from './build/server/view-reference.js';
5
6
  export { VIEW_REFERENCE, isViewReference } from './types/view-reference.js';
package/src/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { eco } from './eco/eco.js';
2
+ export { composeMiddleware, createMiddleware } from './middleware/create-middleware.js';
2
3
  export { defineApiHandler, defineGroupHandler, defineGet, definePost, definePut, defineDelete, definePatch, defineOptions, defineHead, defineQuery, json, html, redirect, } from './adapters/shared/http/define-api-handler.js';
3
4
  export { createViewReference } from './build/server/view-reference.js';
4
5
  export { VIEW_REFERENCE, isViewReference } from './types/view-reference.js';
@@ -6,7 +6,7 @@ export { type ForeignChildInterceptionInput, type ForeignChildInterceptionResult
6
6
  export { ensurePageConfigLayouts } from './eco/page-layout-normalization.js';
7
7
  export { moveMdxMetadataOntoPage } from './eco/mdx-page-metadata.js';
8
8
  export { collectJsxExtensions, createJsxImportSourcePragma, filterJsxSourceExtensions, isJsxSourceExtension, } from './plugins/jsx-import-source.utils.js';
9
- export { resolveDocumentShellLayouts, resolveInnermostPageLayout, resolveLayoutEntryProps, resolveLayoutShellProps, resolvePageLayoutComponents, type DocumentShellLayoutResolutionInput, type LayoutShellPropsContext, } from './route-renderer/orchestration/document-shell/layout-shell-props.service.js';
9
+ export { resolveDocumentShellLayouts, resolveInnermostPageLayout, resolveLayoutEntryProps, resolveRenderLayouts, resolvePageLayoutComponents, type DocumentShellLayoutResolutionInput, type LayoutShellPropsContext, } from './route-renderer/orchestration/document-shell/layout-shell-props.service.js';
10
10
  export { LayoutChildrenNotRenderedError } from './route-renderer/orchestration/document-shell/layout-children-not-rendered-error.js';
11
11
  export { isRegisteredDevTransformEntrypoint, isRegisteredScriptEntrypoint } from './hmr/hmr-entrypoint-output.js';
12
12
  export { type HmrRegisteredEntrypointsContext } from './hmr/hmr-registered-entrypoints-context.js';
@@ -5,7 +5,7 @@ export { getComponentRenderContext, runWithComponentRenderContext, } from './eco
5
5
  export { ensurePageConfigLayouts } from './eco/page-layout-normalization.js';
6
6
  export { moveMdxMetadataOntoPage } from './eco/mdx-page-metadata.js';
7
7
  export { collectJsxExtensions, createJsxImportSourcePragma, filterJsxSourceExtensions, isJsxSourceExtension, } from './plugins/jsx-import-source.utils.js';
8
- export { resolveDocumentShellLayouts, resolveInnermostPageLayout, resolveLayoutEntryProps, resolveLayoutShellProps, resolvePageLayoutComponents, } from './route-renderer/orchestration/document-shell/layout-shell-props.service.js';
8
+ export { resolveDocumentShellLayouts, resolveInnermostPageLayout, resolveLayoutEntryProps, resolveRenderLayouts, resolvePageLayoutComponents, } from './route-renderer/orchestration/document-shell/layout-shell-props.service.js';
9
9
  export { LayoutChildrenNotRenderedError } from './route-renderer/orchestration/document-shell/layout-children-not-rendered-error.js';
10
10
  export { isRegisteredDevTransformEntrypoint, isRegisteredScriptEntrypoint } from './hmr/hmr-entrypoint-output.js';
11
11
  export {} from './hmr/hmr-registered-entrypoints-context.js';
@@ -0,0 +1,41 @@
1
+ import type { MiddlewareHandler } from '../adapters/shared/http/run-middleware-chain.js';
2
+ import type { AnyEcoMiddleware, EcoMiddleware, MiddlewareLocalsAfter, MiddlewareStage, MiddlewareStageInput, ProvidedBy, RuntimeMiddlewareStage, StageResult } from '../types/middleware-types.js';
3
+ /**
4
+ * Creates one middleware from a stage.
5
+ *
6
+ * @remarks
7
+ * The stage continues with `next(locals)` and the locals it passes become typed `locals` for everything after
8
+ * it, with no declaration: the type is read from the `next` calls in the body. Returning a bare `Response` or
9
+ * throwing one stops the request. `next` resolves to the response of the later stages, so a stage can still
10
+ * edit it after `await next()`.
11
+ */
12
+ export declare function createMiddleware<TResult extends StageResult | Promise<StageResult>>(stage: MiddlewareStage<{}, TResult>): EcoMiddleware<ProvidedBy<Awaited<TResult>>>;
13
+ /**
14
+ * Composes middleware and inline stages into one middleware, in order.
15
+ *
16
+ * @remarks
17
+ * Each stage is either a middleware or an inline function whose `ctx.locals` is typed from everything provided
18
+ * by the stages before it, so a dependent stage needs no annotation. The result is itself a middleware: list
19
+ * it in `middleware`, or use it as a stage of another composition. A later stage that provides the same key
20
+ * wins, as it does at runtime. Overloads cover four stages; nest a composition to go further.
21
+ */
22
+ export declare function composeMiddleware<A extends MiddlewareStageInput<{}>>(a: A): EcoMiddleware<MiddlewareLocalsAfter<{}, A>>;
23
+ export declare function composeMiddleware<A extends MiddlewareStageInput<{}>, B extends MiddlewareStageInput<MiddlewareLocalsAfter<{}, A>>>(a: A, b: B): EcoMiddleware<MiddlewareLocalsAfter<MiddlewareLocalsAfter<{}, A>, B>>;
24
+ export declare function composeMiddleware<A extends MiddlewareStageInput<{}>, B extends MiddlewareStageInput<MiddlewareLocalsAfter<{}, A>>, C extends MiddlewareStageInput<MiddlewareLocalsAfter<MiddlewareLocalsAfter<{}, A>, B>>>(a: A, b: B, c: C): EcoMiddleware<MiddlewareLocalsAfter<MiddlewareLocalsAfter<MiddlewareLocalsAfter<{}, A>, B>, C>>;
25
+ export declare function composeMiddleware<A extends MiddlewareStageInput<{}>, B extends MiddlewareStageInput<MiddlewareLocalsAfter<{}, A>>, C extends MiddlewareStageInput<MiddlewareLocalsAfter<MiddlewareLocalsAfter<{}, A>, B>>, D extends MiddlewareStageInput<MiddlewareLocalsAfter<MiddlewareLocalsAfter<MiddlewareLocalsAfter<{}, A>, B>, C>>>(a: A, b: B, c: C, d: D): EcoMiddleware<MiddlewareLocalsAfter<MiddlewareLocalsAfter<MiddlewareLocalsAfter<MiddlewareLocalsAfter<{}, A>, B>, C>, D>>;
26
+ /**
27
+ * Flattens a middleware list into the ordered functions a request pipeline runs.
28
+ *
29
+ * @remarks
30
+ * A plain `(ctx, next)` function is one stage. A middleware made by `createMiddleware` or `composeMiddleware`
31
+ * contributes its stages, in order. Every declared stage runs, so the same stage reached twice is rejected: it
32
+ * would run twice, and the locals the types promise after it would no longer match what a stage in between left
33
+ * behind. Declare a shared guard once, in the composition that owns it. A stage is typed for the context it reads,
34
+ * so the pipeline that runs it names that context as `TContext`; this is the one place the two are joined.
35
+ *
36
+ * @throws When one stage appears twice, naming both positions and `label`, or when an entry is an object neither
37
+ * factory made.
38
+ */
39
+ export declare function flattenMiddleware<TContext extends {
40
+ readonly locals: object;
41
+ }>(entries: readonly (AnyEcoMiddleware | RuntimeMiddlewareStage)[] | undefined, label?: string): MiddlewareHandler<TContext>[];
@@ -0,0 +1,72 @@
1
+ import { localsBrand } from '../types/locals-brand.js';
2
+ /**
3
+ * Creates one middleware from a stage.
4
+ *
5
+ * @remarks
6
+ * The stage continues with `next(locals)` and the locals it passes become typed `locals` for everything after
7
+ * it, with no declaration: the type is read from the `next` calls in the body. Returning a bare `Response` or
8
+ * throwing one stops the request. `next` resolves to the response of the later stages, so a stage can still
9
+ * edit it after `await next()`.
10
+ */
11
+ export function createMiddleware(stage) {
12
+ return brand([stage]);
13
+ }
14
+ export function composeMiddleware(...stages) {
15
+ return brand(assertNoDuplicateStages(collectStages(stages), 'composition'));
16
+ }
17
+ /**
18
+ * The key of the stages each made middleware holds.
19
+ *
20
+ * @remarks
21
+ * The stages are a non-enumerable property, so a copy such as `{ ...auth }` carries the brand but no stages and is
22
+ * rejected when listed, instead of proving locals it never provides. The key is registered with `Symbol.for`, so a
23
+ * Page module that loads its own copy of the package still lists middleware the server's copy can run.
24
+ */
25
+ const stagesKey = Symbol.for('ecopages.middlewareStages');
26
+ function brand(stages) {
27
+ const made = { [localsBrand]: (locals) => locals };
28
+ Object.defineProperty(made, stagesKey, { value: stages });
29
+ return made;
30
+ }
31
+ function stagesOf(entry) {
32
+ return Object.getOwnPropertyDescriptor(entry, stagesKey)?.value;
33
+ }
34
+ /**
35
+ * Flattens a middleware list into the ordered functions a request pipeline runs.
36
+ *
37
+ * @remarks
38
+ * A plain `(ctx, next)` function is one stage. A middleware made by `createMiddleware` or `composeMiddleware`
39
+ * contributes its stages, in order. Every declared stage runs, so the same stage reached twice is rejected: it
40
+ * would run twice, and the locals the types promise after it would no longer match what a stage in between left
41
+ * behind. Declare a shared guard once, in the composition that owns it. A stage is typed for the context it reads,
42
+ * so the pipeline that runs it names that context as `TContext`; this is the one place the two are joined.
43
+ *
44
+ * @throws When one stage appears twice, naming both positions and `label`, or when an entry is an object neither
45
+ * factory made.
46
+ */
47
+ export function flattenMiddleware(entries, label = 'middleware list') {
48
+ return assertNoDuplicateStages(collectStages(entries ?? []), label);
49
+ }
50
+ function collectStages(entries) {
51
+ return entries.flatMap((entry) => {
52
+ if (typeof entry === 'function') {
53
+ return [entry];
54
+ }
55
+ const stages = stagesOf(entry);
56
+ if (!stages) {
57
+ throw new Error('[ecopages] A middleware list holds an object that createMiddleware or composeMiddleware did not make. List the middleware itself, not a copy of it.');
58
+ }
59
+ return [...stages];
60
+ });
61
+ }
62
+ function assertNoDuplicateStages(stages, label) {
63
+ const firstSeen = new Map();
64
+ stages.forEach((stage, index) => {
65
+ const first = firstSeen.get(stage);
66
+ if (first !== undefined) {
67
+ throw new Error(`[ecopages] The ${label} runs the same middleware stage twice, at positions ${first} and ${index}. Declare a shared guard once, in the composition that owns it.`);
68
+ }
69
+ firstSeen.set(stage, index);
70
+ });
71
+ return stages;
72
+ }
@@ -1,7 +1,9 @@
1
1
  import type { EcoPagesAppConfig } from '../config/internal-types.js';
2
2
  import type { EcoBuildOnTransformResult, EcoBuildPlugin } from '../build/contracts/build-types.js';
3
+ import type { BuildEnvironment } from '../build/contracts/build-contracts.js';
3
4
  import { type StylesheetKinds } from './stylesheet-kinds.js';
4
5
  import { type DiscoveryCache, type DiscoveryOptions } from './component-import-discovery.js';
6
+ import type { ComponentIdentity } from '../types/component-identity.js';
5
7
  /**
6
8
  * Options for the plugin that attributes Eco Component identities.
7
9
  *
@@ -11,6 +13,15 @@ import { type DiscoveryCache, type DiscoveryOptions } from './component-import-d
11
13
  */
12
14
  export interface EcoComponentDirPluginOptions {
13
15
  config: EcoPagesAppConfig;
16
+ /**
17
+ * The environment the build compiles for.
18
+ *
19
+ * @remarks
20
+ * A browser build gets no plain-module Component imports: only server-side collection reads the discovered
21
+ * Components, and in the browser such an import would load the Component's module for nothing, including one
22
+ * another Integration owns into a React island.
23
+ */
24
+ environment: BuildEnvironment;
14
25
  }
15
26
  /**
16
27
  * Whether the component meta transform moves the side-effect stylesheet imports of `filePath`
@@ -47,6 +58,11 @@ export type ComponentIdentityAttributionOptions = {
47
58
  stylesheets?: StylesheetKinds;
48
59
  /** The real path of `projectRoot`, when the caller already resolved it; resolved from `projectRoot` otherwise. */
49
60
  canonicalProjectRoot?: string;
61
+ /**
62
+ * Whether the discovered Components of plain modules are imported into the declaring module so collection can
63
+ * read them; defaults to `true`. A browser build turns it off, since nothing there reads them.
64
+ */
65
+ plainModuleComponentImports?: boolean;
50
66
  };
51
67
  /**
52
68
  * Attributes real `eco.*()` factory calls with canonical component identity.
@@ -60,6 +76,23 @@ export type ComponentIdentityAttributionOptions = {
60
76
  * loses its side-effect stylesheet imports (see {@link stripPlainModuleStylesheetImports}).
61
77
  */
62
78
  export declare function attributeComponentIdentity(contents: string, filePath: string, options: ComponentIdentityAttributionOptions): EcoBuildOnTransformResult;
79
+ /**
80
+ * Reads, without transforming the module, the identity of each export whose value is an `eco.*()` call.
81
+ *
82
+ * @remarks
83
+ * The identities are the ones {@link attributeComponentIdentity} binds when it builds the same source, so a
84
+ * browser graph can name a Component another Integration owns without importing its module. An export counts only
85
+ * when its value is the call itself: `export const X = eco.component(...)`, `export default eco.component(...)`, or
86
+ * a top-level `const` holding the call that an `export { local as name }` or `export default local` names. A value
87
+ * a function returns, or any other expression, has no entry, and so does a module that does not parse. A call whose
88
+ * options are not an object literal, or set `integration` or spread another object, has no entry either, since its
89
+ * Component may belong to another Integration than the file.
90
+ * `filePath` is compared as given, so pass the real path the bundler reports.
91
+ */
92
+ export declare function readExportedComponentIdentities(contents: string, filePath: string, options: {
93
+ integration: string;
94
+ projectRoot: string;
95
+ }): Map<string, ComponentIdentity>;
63
96
  /**
64
97
  * Attributes a compiled MDX module with canonical component identity and discovered dependencies.
65
98
  *
@@ -122,9 +122,11 @@ function createSourceKeyResolver(projectRoot, canonicalProjectRoot) {
122
122
  * `file` is the root-relative source key and `id` hashes it, so an emitted module names its source the same
123
123
  * wherever the app was built and keeps working after the app folder moves.
124
124
  */
125
- function createIdentityLiteral(identitySource, sourceKey, integration) {
126
- const id = BigInt(`0x${contentHash(identitySource, 16)}`).toString(36);
127
- return `{ id: ${JSON.stringify(id)}, file: ${JSON.stringify(sourceKey)}, integration: ${JSON.stringify(integration)} }`;
125
+ function createIdentity(identitySource, sourceKey, integration) {
126
+ return { id: BigInt(`0x${contentHash(identitySource, 16)}`).toString(36), file: sourceKey, integration };
127
+ }
128
+ function createIdentityLiteral({ id, file, integration }) {
129
+ return `{ id: ${JSON.stringify(id)}, file: ${JSON.stringify(file)}, integration: ${JSON.stringify(integration)} }`;
128
130
  }
129
131
  function createNamedImportEdit(program, sourceModule, importedName) {
130
132
  const importedNames = typeof importedName === 'string' ? [importedName] : [...importedName];
@@ -281,6 +283,23 @@ function stripPlainModuleStylesheetImports(program, filePath, options) {
281
283
  }
282
284
  return edits;
283
285
  }
286
+ /** The first argument of each `eco.*()` call not yet bound, with the identity literal to bind it to. */
287
+ function collectFactoryArguments(program, sourceKey, integration) {
288
+ const factoryArguments = [];
289
+ for (const [call, identity] of collectCallIdentities(program, sourceKey, integration)) {
290
+ const firstArgument = Array.isArray(call.arguments) ? call.arguments[0] : undefined;
291
+ if (!isAstNode(firstArgument) || isIdentityBinding(firstArgument))
292
+ continue;
293
+ if (typeof firstArgument.start !== 'number' || typeof firstArgument.end !== 'number')
294
+ continue;
295
+ factoryArguments.push({
296
+ start: firstArgument.start,
297
+ end: firstArgument.end,
298
+ identityLiteral: createIdentityLiteral(identity),
299
+ });
300
+ }
301
+ return factoryArguments;
302
+ }
284
303
  /**
285
304
  * Attributes real `eco.*()` factory calls with canonical component identity.
286
305
  *
@@ -319,24 +338,7 @@ export function attributeComponentIdentity(contents, filePath, options) {
319
338
  }
320
339
  const { toCanonicalSourceKey } = createSourceKeyResolver(projectRoot, options.canonicalProjectRoot);
321
340
  const sourceKey = toCanonicalSourceKey(filePath);
322
- const factoryArguments = [];
323
- const bindingOccurrences = new Map();
324
- walkEcoFactoryCalls(program, '', (node, binding) => {
325
- const occurrence = bindingOccurrences.get(binding) ?? 0;
326
- bindingOccurrences.set(binding, occurrence + 1);
327
- if (!Array.isArray(node.arguments))
328
- return;
329
- const firstArgument = node.arguments[0];
330
- if (!isAstNode(firstArgument) || isIdentityBinding(firstArgument))
331
- return;
332
- if (typeof firstArgument.start !== 'number' || typeof firstArgument.end !== 'number')
333
- return;
334
- factoryArguments.push({
335
- start: firstArgument.start,
336
- end: firstArgument.end,
337
- identityLiteral: createIdentityLiteral(`${sourceKey}:${binding}:${occurrence}`, sourceKey, integration),
338
- });
339
- });
341
+ const factoryArguments = collectFactoryArguments(program, sourceKey, integration);
340
342
  if (factoryArguments.length === 0) {
341
343
  return applySourceEdits(contents, [], filePath, { prepend: pragma });
342
344
  }
@@ -346,7 +348,9 @@ export function attributeComponentIdentity(contents, filePath, options) {
346
348
  cache: options.discoveryCache,
347
349
  stylesheets: options.stylesheets,
348
350
  });
349
- const plainModuleImports = createPlainModuleComponentImports(discovered);
351
+ const plainModuleImports = options.plainModuleComponentImports === false
352
+ ? { locals: [], code: '' }
353
+ : createPlainModuleComponentImports(discovered);
350
354
  const discoveryArgument = serializeDiscoveryArgument(discovered, toCanonicalSourceKey, plainModuleImports.locals);
351
355
  const edits = factoryArguments.map((firstArgument) => ({
352
356
  start: firstArgument.start,
@@ -402,6 +406,148 @@ function buildMdxIdentityAppend(options) {
402
406
  appended += `attachDiscoveredDependencies(config);\nif (typeof MDXContent === 'function') MDXContent.config = config;\n`;
403
407
  return appended;
404
408
  }
409
+ /** The expression under TypeScript `as`, `satisfies` and non-null wrappers, and parentheses. */
410
+ function unwrapExpression(value) {
411
+ let current = node(value);
412
+ while (current &&
413
+ (current.type === 'TSAsExpression' ||
414
+ current.type === 'TSSatisfiesExpression' ||
415
+ current.type === 'TSNonNullExpression' ||
416
+ current.type === 'ParenthesizedExpression')) {
417
+ current = node(current.expression);
418
+ }
419
+ return current;
420
+ }
421
+ /**
422
+ * Reads, without transforming the module, the identity of each export whose value is an `eco.*()` call.
423
+ *
424
+ * @remarks
425
+ * The identities are the ones {@link attributeComponentIdentity} binds when it builds the same source, so a
426
+ * browser graph can name a Component another Integration owns without importing its module. An export counts only
427
+ * when its value is the call itself: `export const X = eco.component(...)`, `export default eco.component(...)`, or
428
+ * a top-level `const` holding the call that an `export { local as name }` or `export default local` names. A value
429
+ * a function returns, or any other expression, has no entry, and so does a module that does not parse. A call whose
430
+ * options are not an object literal, or set `integration` or spread another object, has no entry either, since its
431
+ * Component may belong to another Integration than the file.
432
+ * `filePath` is compared as given, so pass the real path the bundler reports.
433
+ */
434
+ export function readExportedComponentIdentities(contents, filePath, options) {
435
+ if (!contents.includes('eco.'))
436
+ return new Map();
437
+ let program;
438
+ try {
439
+ program = parseModuleSource(filePath, contents, { sourceType: 'module' }).program;
440
+ }
441
+ catch {
442
+ return new Map();
443
+ }
444
+ const sourceKey = createSourceKeyResolver(options.projectRoot).toCanonicalSourceKey(filePath);
445
+ const callIdentities = collectCallIdentities(program, sourceKey, options.integration);
446
+ if (callIdentities.size === 0)
447
+ return new Map();
448
+ const identityOf = (value) => {
449
+ const expression = unwrapExpression(value);
450
+ return expression && ownedByFile(expression) ? callIdentities.get(expression) : undefined;
451
+ };
452
+ const statements = nodes(program.body);
453
+ return collectExportIdentities(statements, identityOf, collectConstIdentities(statements, identityOf));
454
+ }
455
+ /**
456
+ * The identity each `eco.*()` call gets, in source order.
457
+ *
458
+ * @remarks
459
+ * The one place calls are numbered: {@link attributeComponentIdentity} binds these identities and
460
+ * {@link readExportedComponentIdentities} reads them, so the two cannot disagree.
461
+ */
462
+ function collectCallIdentities(program, sourceKey, integration) {
463
+ const identities = new Map();
464
+ const bindingOccurrences = new Map();
465
+ walkEcoFactoryCalls(program, '', (call, binding) => {
466
+ const occurrence = bindingOccurrences.get(binding) ?? 0;
467
+ bindingOccurrences.set(binding, occurrence + 1);
468
+ identities.set(call, createIdentity(`${sourceKey}:${binding}:${occurrence}`, sourceKey, integration));
469
+ });
470
+ return identities;
471
+ }
472
+ /**
473
+ * Whether an `eco.*()` call's Component belongs to the Integration that owns its file: its options are an object
474
+ * literal with neither an `integration` property nor a spread that could carry one.
475
+ */
476
+ function ownedByFile(call) {
477
+ const options = Array.isArray(call.arguments) ? node(call.arguments[0]) : undefined;
478
+ if (options?.type !== 'ObjectExpression')
479
+ return false;
480
+ return !nodes(options.properties).some((property) => {
481
+ if ((property.type !== 'Property' && property.type !== 'ObjectProperty') || property.computed)
482
+ return true;
483
+ const key = node(property.key);
484
+ return key !== undefined && (key.name ?? key.value) === 'integration';
485
+ });
486
+ }
487
+ /** The identity of each top-level `const`, exported or not, whose initializer is an `eco.*()` call. */
488
+ function collectConstIdentities(statements, identityOf) {
489
+ const identities = new Map();
490
+ for (const statement of statements) {
491
+ const declaration = statement.type === 'ExportNamedDeclaration' ? node(statement.declaration) : statement;
492
+ if (declaration?.type !== 'VariableDeclaration' || declaration.kind !== 'const')
493
+ continue;
494
+ for (const declarator of nodes(declaration.declarations)) {
495
+ const id = node(declarator.id);
496
+ const identity = identityOf(declarator.init);
497
+ if (id?.type === 'Identifier' && identity)
498
+ identities.set(String(id.name), identity);
499
+ }
500
+ }
501
+ return identities;
502
+ }
503
+ function exportedName(value) {
504
+ const exported = node(value);
505
+ if (!exported)
506
+ return undefined;
507
+ return exported.type === 'Identifier' ? String(exported.name) : String(exported.value);
508
+ }
509
+ /** The names a local `export` statement gives a top-level `const`, with the const's name. */
510
+ function localExportNames(statement) {
511
+ const names = [];
512
+ const declaration = node(statement.declaration);
513
+ if (declaration?.type === 'VariableDeclaration') {
514
+ for (const declarator of nodes(declaration.declarations)) {
515
+ const id = node(declarator.id);
516
+ if (id?.type === 'Identifier')
517
+ names.push([String(id.name), String(id.name)]);
518
+ }
519
+ }
520
+ for (const specifier of nodes(statement.specifiers)) {
521
+ const local = node(specifier.local);
522
+ const exported = exportedName(specifier.exported);
523
+ if (specifier.exportKind !== 'type' && local?.type === 'Identifier' && exported) {
524
+ names.push([exported, String(local.name)]);
525
+ }
526
+ }
527
+ return names;
528
+ }
529
+ /** The identity of each export whose value is an `eco.*()` call, directly or through a top-level `const`. */
530
+ function collectExportIdentities(statements, identityOf, constIdentities) {
531
+ const identities = new Map();
532
+ for (const statement of statements) {
533
+ if (statement.type === 'ExportDefaultDeclaration') {
534
+ const declaration = node(statement.declaration);
535
+ const local = declaration?.type === 'Identifier' ? constIdentities.get(String(declaration.name)) : undefined;
536
+ const identity = identityOf(declaration) ?? local;
537
+ if (identity)
538
+ identities.set('default', identity);
539
+ continue;
540
+ }
541
+ if (statement.type !== 'ExportNamedDeclaration' || statement.source || statement.exportKind === 'type')
542
+ continue;
543
+ for (const [exported, local] of localExportNames(statement)) {
544
+ const identity = constIdentities.get(local);
545
+ if (identity)
546
+ identities.set(exported, identity);
547
+ }
548
+ }
549
+ return identities;
550
+ }
405
551
  /**
406
552
  * Attributes a compiled MDX module with canonical component identity and discovered dependencies.
407
553
  *
@@ -431,7 +577,7 @@ export function attributeMdxComponentIdentity(contents, filePath, integration, p
431
577
  const discovered = discoverComponentImports(program, filePath, projectRoot, { stylesheets });
432
578
  const { toSourceKey } = createSourceKeyResolver(projectRoot);
433
579
  const sourceKey = toSourceKey(filePath);
434
- const identityLiteral = createIdentityLiteral(sourceKey, sourceKey, integration);
580
+ const identityLiteral = createIdentityLiteral(createIdentity(sourceKey, sourceKey, integration));
435
581
  const plainModuleImports = createPlainModuleComponentImports(discovered);
436
582
  const discoveryArgument = serializeDiscoveryArgument(discovered, toSourceKey, plainModuleImports.locals);
437
583
  const edits = buildMdxConfigIdentityEdits({
@@ -531,6 +677,7 @@ export function createEcoComponentMetaPlugin(options) {
531
677
  integration: integration?.name,
532
678
  projectRoot: rootDir,
533
679
  canonicalProjectRoot: canonicalRoot,
680
+ plainModuleComponentImports: options.environment !== 'browser',
534
681
  jsxImportSource: integration?.jsxImportSource,
535
682
  integrationOf,
536
683
  stripPlainModuleStylesheets,