@bleedingdev/modern-js-plugin-bff 3.5.0-ultramodern.28 → 3.5.0-ultramodern.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cjs/runtime/effect/adapter.js +9 -40
  2. package/dist/cjs/runtime/effect/backend-federation-manifest.js +287 -0
  3. package/dist/cjs/runtime/effect/backend-federation.js +189 -0
  4. package/dist/cjs/runtime/effect/dispatch.js +116 -0
  5. package/dist/cjs/runtime/effect/edge.js +58 -69
  6. package/dist/cjs/runtime/effect/endpoint-contracts.js +7 -12
  7. package/dist/cjs/runtime/effect/entry-shape.js +87 -0
  8. package/dist/cjs/runtime/effect/handler.js +15 -16
  9. package/dist/cjs/runtime/effect/index.js +91 -15
  10. package/dist/cjs/runtime/effect/module.js +23 -80
  11. package/dist/esm/runtime/effect/adapter.mjs +10 -41
  12. package/dist/esm/runtime/effect/backend-federation-manifest.mjs +237 -0
  13. package/dist/esm/runtime/effect/backend-federation.mjs +132 -0
  14. package/dist/esm/runtime/effect/dispatch.mjs +63 -0
  15. package/dist/esm/runtime/effect/edge.mjs +17 -63
  16. package/dist/esm/runtime/effect/endpoint-contracts.mjs +7 -12
  17. package/dist/esm/runtime/effect/entry-shape.mjs +36 -0
  18. package/dist/esm/runtime/effect/handler.mjs +1 -4
  19. package/dist/esm/runtime/effect/index.mjs +3 -0
  20. package/dist/esm/runtime/effect/module.mjs +23 -80
  21. package/dist/esm-node/runtime/effect/adapter.mjs +10 -41
  22. package/dist/esm-node/runtime/effect/backend-federation-manifest.mjs +238 -0
  23. package/dist/esm-node/runtime/effect/backend-federation.mjs +133 -0
  24. package/dist/esm-node/runtime/effect/dispatch.mjs +64 -0
  25. package/dist/esm-node/runtime/effect/edge.mjs +17 -63
  26. package/dist/esm-node/runtime/effect/endpoint-contracts.mjs +7 -12
  27. package/dist/esm-node/runtime/effect/entry-shape.mjs +37 -0
  28. package/dist/esm-node/runtime/effect/handler.mjs +1 -4
  29. package/dist/esm-node/runtime/effect/index.mjs +3 -0
  30. package/dist/esm-node/runtime/effect/module.mjs +23 -80
  31. package/dist/types/runtime/effect/backend-federation-manifest.d.ts +60 -0
  32. package/dist/types/runtime/effect/backend-federation.d.ts +60 -0
  33. package/dist/types/runtime/effect/dispatch.d.ts +17 -0
  34. package/dist/types/runtime/effect/edge.d.ts +9 -8
  35. package/dist/types/runtime/effect/endpoint-contracts.d.ts +2 -2
  36. package/dist/types/runtime/effect/entry-shape.d.ts +31 -0
  37. package/dist/types/runtime/effect/handler.d.ts +1 -17
  38. package/dist/types/runtime/effect/index.d.ts +3 -0
  39. package/package.json +25 -13
@@ -1,70 +1,14 @@
1
- import { createSafeFailureResponse } from "../safe-failure.mjs";
1
+ import { dispatchEffectBffRequestWithContext } from "./dispatch.mjs";
2
2
  import { runWithEffectContext, useEffectContext, useOperationContext } from "./edge-context.mjs";
3
3
  import { resolveEffectBffModuleHandler } from "./module.mjs";
4
- import { createEffectOperationContext } from "./operation-context.mjs";
5
4
  export * from "./handler.mjs";
6
- function normalizePrefix(prefix) {
7
- if (!prefix || '/' === prefix) return '';
8
- return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
9
- }
10
- function removePrefixFromPath(pathname, prefix) {
11
- const normalized = normalizePrefix(prefix);
12
- if (!normalized || pathname !== normalized && !pathname.startsWith(`${normalized}/`)) return pathname;
13
- const sliced = pathname.slice(normalized.length);
14
- return sliced.startsWith('/') ? sliced : `/${sliced}`;
15
- }
16
- function matchesPrefix(pathname, prefix) {
17
- const normalized = normalizePrefix(prefix);
18
- return !normalized || pathname === normalized || pathname.startsWith(`${normalized}/`);
19
- }
20
- function createRequestForMountedPrefix(req, prefix) {
21
- const url = new URL(req.url);
22
- const nextPath = removePrefixFromPath(url.pathname, prefix);
23
- if (nextPath === url.pathname) return req;
24
- url.pathname = nextPath;
25
- return new Request(url, req);
26
- }
27
- function createEdgeEffectContext(originalRequest, effectRequest, options) {
28
- const originalPath = options.path || new URL(originalRequest.url).pathname;
29
- const method = options.method || originalRequest.method;
30
- return {
31
- request: effectRequest,
32
- env: options.env || {},
33
- path: originalPath,
34
- method,
35
- operationContext: createEffectOperationContext({
36
- request: effectRequest,
37
- env: options.env || {},
38
- path: originalPath,
39
- method
40
- })
41
- };
42
- }
43
- function createRuntimeErrorResponse(error) {
44
- return createSafeFailureResponse(error);
45
- }
46
5
  async function dispatchEffectBffRequest(handler, request, options = {}) {
47
- const requestPathname = new URL(request.url).pathname;
48
- if (!matchesPrefix(requestPathname, options.prefix)) return new Response(null, {
49
- status: 404
6
+ return dispatchEffectBffRequestWithContext(handler, request, {
7
+ ...options,
8
+ runWithEffectContext: runWithEffectContext
50
9
  });
51
- const effectRequest = createRequestForMountedPrefix(request, options.prefix);
52
- const effectContext = createEdgeEffectContext(request, effectRequest, options);
53
- try {
54
- const response = await runWithEffectContext(effectContext, ()=>handler(effectRequest, effectContext));
55
- if (!(response instanceof Response)) throw new Error('[BFF][Effect] Effect handler must return a Response instance.');
56
- return new Response(response.body, response);
57
- } catch (error) {
58
- if (error instanceof Response) return new Response(error.body, error);
59
- if (options.onError) {
60
- const errorResponse = await options.onError(error, effectContext);
61
- if (errorResponse instanceof Response) return errorResponse;
62
- }
63
- return createRuntimeErrorResponse(error);
64
- }
65
10
  }
66
- const createEffectBffTestHandler = createEffectBffEdgeHandler;
67
- async function createEffectBffEdgeHandler(options) {
11
+ async function createEffectBffEdgeDispatcher(options) {
68
12
  const loaded = await resolveEffectBffModuleHandler(options.module, {
69
13
  openapi: options.openapi,
70
14
  dataPlatform: options.dataPlatform,
@@ -72,7 +16,7 @@ async function createEffectBffEdgeHandler(options) {
72
16
  });
73
17
  if (!loaded) throw new Error('[BFF][Effect] Invalid Effect edge module. Export defineEffectBff(...) or a { api, layer } HttpApi module.');
74
18
  return {
75
- handler: (request, dispatchOptions = {})=>dispatchEffectBffRequest(loaded.handler, request, {
19
+ dispatch: (request, dispatchOptions = {})=>dispatchEffectBffRequest(loaded.handler, request, {
76
20
  ...dispatchOptions,
77
21
  prefix: options.prefix,
78
22
  onError: options.onError
@@ -82,4 +26,14 @@ async function createEffectBffEdgeHandler(options) {
82
26
  }
83
27
  };
84
28
  }
85
- export { createEffectBffEdgeHandler, createEffectBffTestHandler, createEffectOperationContext, dispatchEffectBffRequest, runWithEffectContext, useEffectContext, useOperationContext };
29
+ const createEffectBffTestHandler = createEffectBffEdgeHandler;
30
+ async function createEffectBffEdgeHandler(options) {
31
+ const dispatcher = await createEffectBffEdgeDispatcher(options);
32
+ return {
33
+ handler: dispatcher.dispatch,
34
+ dispose: dispatcher.dispose
35
+ };
36
+ }
37
+ export { BACKEND_FEDERATION_CONTRACT_VERSION, BACKEND_FEDERATION_EFFECT_EXPOSE, BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_NODE_ADAPTER_VERSION, createBackendFederationLoadEntryPlugin, createBackendFederationRuntime, loadBackendFederatedEffectApi } from "./backend-federation.mjs";
38
+ export { createEffectOperationContext } from "./operation-context.mjs";
39
+ export { createEffectBffEdgeDispatcher, createEffectBffEdgeHandler, createEffectBffTestHandler, dispatchEffectBffRequest, runWithEffectContext, useEffectContext, useOperationContext };
@@ -1,4 +1,5 @@
1
1
  import { createOperationContractHash } from "@modern-js/bff-core";
2
+ import { classifyEffectBffEntryModule, isValidatorAwareHandlerFactory } from "./entry-shape.mjs";
2
3
  function ensureLeadingSlash(pathname) {
3
4
  return pathname.startsWith('/') ? pathname : `/${pathname}`;
4
5
  }
@@ -48,19 +49,13 @@ function createEffectOperationContractSource(endpoint) {
48
49
  routePath: endpoint.routePath
49
50
  };
50
51
  }
51
- function isRecord(value) {
52
- return 'object' == typeof value && null !== value;
53
- }
54
52
  async function extractHttpApiFromModule(mod, isHttpApi) {
55
- if (!isRecord(mod)) return null;
56
- if (isHttpApi(mod.api)) return mod.api;
57
- const entry = mod.default;
58
- if (isRecord(entry) && isHttpApi(entry.api)) return entry.api;
59
- if ('function' == typeof entry && 0 === entry.length) {
60
- const output = await entry();
61
- if (isRecord(output) && isHttpApi(output.api)) return output.api;
62
- }
63
- return null;
53
+ const facts = classifyEffectBffEntryModule(mod, {
54
+ isRequestHandler: (value)=>'function' == typeof value,
55
+ isValidatorAwareHandlerFactory: isValidatorAwareHandlerFactory,
56
+ isHttpApi
57
+ });
58
+ return !facts?.legacyShape && facts?.api !== void 0 && facts.hasRuntimeLayer && (void 0 === facts.createHandler || facts.createHandlerValidatorAware) ? facts.api : null;
64
59
  }
65
60
  function createEffectEndpointContractHash(endpoint, requestId) {
66
61
  return createOperationContractHash(createEffectOperationContractSource(endpoint), requestId);
@@ -0,0 +1,36 @@
1
+ const EFFECT_VALIDATOR_AWARE_FACTORY = Symbol.for('modernjs.effect.validatorAware');
2
+ function isValidatorAwareHandlerFactory(factory) {
3
+ return Boolean('function' == typeof factory && factory[EFFECT_VALIDATOR_AWARE_FACTORY]);
4
+ }
5
+ const strictEffectApproachMessage = '[BFF][Effect] strictEffectApproach is enforced: Effect API entries export defineEffectBff(...) or { api, layer } HttpApi module. Raw handler exports, default request handlers, unbranded custom createHandler factories not valid Effect API entries.';
6
+ function isEffectEntryRecord(value) {
7
+ return 'object' == typeof value && null !== value;
8
+ }
9
+ function classifyEffectBffEntryModule(value, predicates) {
10
+ if (!isEffectEntryRecord(value)) return null;
11
+ const rootModule = value;
12
+ if (predicates.isRequestHandler(rootModule.handler)) return createEntryShapeFacts(rootModule, predicates, '`handler` export');
13
+ const defaultEntry = rootModule.default;
14
+ if (predicates.isRequestHandler(defaultEntry)) return createEntryShapeFacts(rootModule, predicates, 'default request handler');
15
+ const module = isEffectEntryRecord(defaultEntry) ? {
16
+ ...rootModule,
17
+ ...defaultEntry
18
+ } : rootModule;
19
+ if (predicates.isRequestHandler(module.handler)) return createEntryShapeFacts(module, predicates, '`handler` export');
20
+ return createEntryShapeFacts(module, predicates);
21
+ }
22
+ function createEntryShapeFacts(module, predicates, legacyShape) {
23
+ const createHandler = 'function' == typeof module.createHandler ? module.createHandler : void 0;
24
+ const api = predicates.isHttpApi(module.api) ? module.api : void 0;
25
+ const hasRuntimeLayer = void 0 !== module.layer;
26
+ return {
27
+ module,
28
+ legacyShape,
29
+ createHandler,
30
+ createHandlerValidatorAware: void 0 !== createHandler && predicates.isValidatorAwareHandlerFactory(createHandler),
31
+ api,
32
+ layer: module.layer,
33
+ hasRuntimeLayer
34
+ };
35
+ }
36
+ export { EFFECT_VALIDATOR_AWARE_FACTORY, classifyEffectBffEntryModule, isEffectEntryRecord, isValidatorAwareHandlerFactory, strictEffectApproachMessage };
@@ -3,6 +3,7 @@ import { HttpRouter, HttpServer, HttpServerResponse, HttpTraceContext } from "ef
3
3
  import { HttpApiBuilder, OpenApi } from "effect/unstable/httpapi";
4
4
  import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
5
5
  import { DEFAULT_DATA_BATCH_ENDPOINT, DEFAULT_DATA_BATCH_HEADER, DEFAULT_DATA_ENVELOPE_HEADER, decodeRequestEnvelopeHeader, validateRequestEnvelope, validateSelectionPlan } from "../data-platform/index.mjs";
6
+ import { EFFECT_VALIDATOR_AWARE_FACTORY, isValidatorAwareHandlerFactory } from "./entry-shape.mjs";
6
7
  import * as __rspack_external_effect_Config_29be8a92 from "effect/Config";
7
8
  import * as __rspack_external_effect_Effect_194ac36c from "effect/Effect";
8
9
  import * as __rspack_external_effect_Option_4d691636 from "effect/Option";
@@ -14,10 +15,6 @@ import * as __rspack_external_effect_Context_f1289ca3 from "effect/Context";
14
15
  const emptyEffectServiceContext = __rspack_external_effect_Context_f1289ca3.empty();
15
16
  const isEffectServiceContext = (context)=>'object' == typeof context && null !== context && 'mapUnsafe' in context;
16
17
  const toEffectServiceContext = (context)=>isEffectServiceContext(context) ? context : emptyEffectServiceContext;
17
- const EFFECT_VALIDATOR_AWARE_FACTORY = Symbol.for('modernjs.effect.validatorAware');
18
- function isValidatorAwareHandlerFactory(factory) {
19
- return 'function' == typeof factory && true === factory[EFFECT_VALIDATOR_AWARE_FACTORY];
20
- }
21
18
  function normalizeOpenApiPath(pathname) {
22
19
  if (!pathname.startsWith('/')) return `/${pathname}`;
23
20
  return pathname;
@@ -1,5 +1,8 @@
1
1
  import * as __rspack_external__effect_opentelemetry_8bbbb5af from "@effect/opentelemetry";
2
+ export * from "./backend-federation.mjs";
2
3
  export * from "./handler.mjs";
4
+ export { BACKEND_FEDERATION_CONTRACT_VERSION, BACKEND_FEDERATION_EFFECT_EXPOSE, BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_NODE_ADAPTER_VERSION, createBackendFederationLoadEntryPlugin, createBackendFederationRuntime, loadBackendFederatedEffectApi } from "./backend-federation.mjs";
5
+ export { BackendFederationManifestAdapterError, loadBackendFederatedEffectApiFromManifest, loadBackendFederationManifest, resolveBackendFederationRemoteFromManifest } from "./backend-federation-manifest.mjs";
3
6
  export { createEffectOperationContext, runWithEffectContext, useEffectContext, useOperationContext } from "./context.mjs";
4
7
  export { createEffectBffEdgeHandler, createEffectBffTestHandler, dispatchEffectBffRequest } from "./edge.mjs";
5
8
  export { __rspack_external__effect_opentelemetry_8bbbb5af as OpenTelemetry };
@@ -1,23 +1,14 @@
1
1
  import { HttpApi } from "effect/unstable/httpapi";
2
- import { createHttpApiHandler, isValidatorAwareHandlerFactory } from "./handler.mjs";
2
+ import { classifyEffectBffEntryModule, isValidatorAwareHandlerFactory, strictEffectApproachMessage } from "./entry-shape.mjs";
3
+ import { createHttpApiHandler } from "./handler.mjs";
3
4
  import * as __rspack_external_effect_Context_f1289ca3 from "effect/Context";
4
- function isRecord(value) {
5
- return 'object' == typeof value && null !== value;
6
- }
7
- function includesRuntimeExports(value) {
8
- return 'api' in value || 'layer' in value || 'createHandler' in value || 'handler' in value;
9
- }
10
5
  function isRequestHandler(value) {
11
6
  return 'function' == typeof value;
12
7
  }
13
- function isEffectApiDefinition(module) {
14
- return HttpApi.isHttpApi(module.api) && void 0 !== module.layer;
15
- }
16
8
  function isEffectServiceContext(context) {
17
9
  return 'object' == typeof context && null !== context && 'mapUnsafe' in context;
18
10
  }
19
11
  const emptyEffectServiceContext = __rspack_external_effect_Context_f1289ca3.empty();
20
- const strictEffectApproachMessage = '[BFF][Effect] strictEffectApproach is enforced: Effect API entries must export defineEffectBff(...) or a { api, layer } HttpApi module. Raw handler exports, default request handlers, and unbranded custom createHandler factories are not valid Effect API entries.';
21
12
  function rejectLegacyEffectModuleShape(options, shape) {
22
13
  options.onWarning?.(`${strictEffectApproachMessage} Rejected ${shape}.`);
23
14
  return true;
@@ -40,41 +31,21 @@ function createLoadedHttpApiHandler(webHandler) {
40
31
  dispose: webHandler.dispose
41
32
  };
42
33
  }
43
- function resolveNormalizedEffectBffModuleHandler(normalizedModule, options = {}) {
44
- if (isRequestHandler(normalizedModule.handler)) {
45
- if (rejectLegacyEffectModuleShape(options, '`handler` export')) return null;
46
- return {
47
- handler: normalizedModule.handler
48
- };
49
- }
50
- const entry = normalizedModule.default;
51
- if (isRequestHandler(entry)) {
52
- if (rejectLegacyEffectModuleShape(options, 'default request handler')) return null;
53
- return {
54
- handler: entry
55
- };
56
- }
57
- if (isRecord(entry)) normalizedModule = {
58
- ...normalizedModule,
59
- ...entry
60
- };
61
- if (isRecord(entry) && 'handler' in entry) {
62
- const maybeHandler = entry.handler;
63
- if (isRequestHandler(maybeHandler)) normalizedModule = {
64
- ...normalizedModule,
65
- handler: maybeHandler
66
- };
67
- }
68
- if (isRequestHandler(normalizedModule.handler)) {
69
- if (rejectLegacyEffectModuleShape(options, '`handler` export')) return null;
70
- return {
71
- handler: normalizedModule.handler
72
- };
34
+ function classifyEffectBffRuntimeEntryShape(module) {
35
+ return classifyEffectBffEntryModule(module, {
36
+ isRequestHandler: isRequestHandler,
37
+ isValidatorAwareHandlerFactory: isValidatorAwareHandlerFactory,
38
+ isHttpApi: HttpApi.isHttpApi
39
+ });
40
+ }
41
+ function resolveClassifiedEffectBffModuleHandler(facts, options = {}) {
42
+ if (!facts) return null;
43
+ if (facts.legacyShape) {
44
+ if (rejectLegacyEffectModuleShape(options, facts.legacyShape)) return null;
73
45
  }
74
- if ('function' == typeof normalizedModule.createHandler) {
75
- const factory = normalizedModule.createHandler;
76
- const validatorAware = isValidatorAwareHandlerFactory(factory);
77
- if (!validatorAware && rejectLegacyEffectModuleShape(options, 'unbranded `createHandler` export')) return null;
46
+ if ('function' == typeof facts.createHandler) {
47
+ if (!facts.createHandlerValidatorAware && rejectLegacyEffectModuleShape(options, 'unbranded `createHandler` export')) return null;
48
+ const factory = facts.createHandler;
78
49
  const webHandler = factory({
79
50
  openapi: options.openapi,
80
51
  dataPlatform: options.dataPlatform,
@@ -82,11 +53,11 @@ function resolveNormalizedEffectBffModuleHandler(normalizedModule, options = {})
82
53
  });
83
54
  return createLoadedHandler(webHandler);
84
55
  }
85
- if (isEffectApiDefinition(normalizedModule)) {
56
+ if (void 0 !== facts.api && facts.hasRuntimeLayer) {
86
57
  options.onWarning?.('[BFF][Effect] Detected { api, layer } export without createHandler. Prefer `defineEffectBff(...)` from @modern-js/plugin-bff/server to avoid module instance mismatch.');
87
58
  const webHandler = createHttpApiHandler({
88
- api: normalizedModule.api,
89
- layer: normalizedModule.layer,
59
+ api: facts.api,
60
+ layer: facts.layer,
90
61
  openapi: options.openapi,
91
62
  dataPlatform: options.dataPlatform,
92
63
  validateRequest: options.validateRequest
@@ -95,38 +66,10 @@ function resolveNormalizedEffectBffModuleHandler(normalizedModule, options = {})
95
66
  }
96
67
  return null;
97
68
  }
69
+ function resolveNormalizedEffectBffModuleHandler(normalizedModule, options = {}) {
70
+ return resolveClassifiedEffectBffModuleHandler(classifyEffectBffRuntimeEntryShape(normalizedModule), options);
71
+ }
98
72
  function resolveEffectBffModuleHandler(mod, options = {}) {
99
- let normalizedModule = mod;
100
- const mergeRuntimeExports = (value)=>{
101
- if (!isRecord(value) || !includesRuntimeExports(value)) return;
102
- normalizedModule = {
103
- ...normalizedModule,
104
- ...value
105
- };
106
- };
107
- if (isRequestHandler(normalizedModule.handler)) {
108
- if (rejectLegacyEffectModuleShape(options, '`handler` export')) return Promise.resolve(null);
109
- return Promise.resolve({
110
- handler: normalizedModule.handler
111
- });
112
- }
113
- const entry = normalizedModule.default;
114
- if (isRequestHandler(entry)) {
115
- if (rejectLegacyEffectModuleShape(options, 'default request handler')) return Promise.resolve(null);
116
- return Promise.resolve({
117
- handler: entry
118
- });
119
- }
120
- if ('function' == typeof entry && 0 === entry.length) return Promise.resolve(entry()).then((out)=>{
121
- if (isRequestHandler(out)) {
122
- if (rejectLegacyEffectModuleShape(options, 'default factory returning a request handler')) return null;
123
- return {
124
- handler: out
125
- };
126
- }
127
- mergeRuntimeExports(out);
128
- return resolveNormalizedEffectBffModuleHandler(normalizedModule, options);
129
- });
130
- return Promise.resolve(resolveNormalizedEffectBffModuleHandler(normalizedModule, options));
73
+ return Promise.resolve(resolveNormalizedEffectBffModuleHandler(mod, options));
131
74
  }
132
75
  export { resolveEffectBffModuleHandler };
@@ -5,7 +5,8 @@ import { HttpApi } from "effect/unstable/httpapi";
5
5
  import path from "path";
6
6
  import { checkCrossProjectPolicyForRequest, resolveAdapterCrossProjectPolicy } from "../../utils/crossProjectServerPolicy.mjs";
7
7
  import { createSafeFailureResponse } from "../safe-failure.mjs";
8
- import { createEffectOperationContext, runWithEffectContext } from "./context.mjs";
8
+ import { runWithEffectContext } from "./context.mjs";
9
+ import { dispatchEffectBffRequestWithContext } from "./dispatch.mjs";
9
10
  import { collectEffectEndpoints, extractHttpApiFromModule, toOperationContractSources } from "./endpoint-contracts.mjs";
10
11
  import { resolveEffectBffModuleHandler } from "./module.mjs";
11
12
  const before = [
@@ -28,26 +29,6 @@ function resolveJsOrTsEntry(entryWithoutOrWithExt) {
28
29
  if (JS_OR_TS_EXTS.includes(extension)) return fs.existsSync(entryWithoutOrWithExt) ? entryWithoutOrWithExt : void 0;
29
30
  return findExists(JS_OR_TS_EXTS.map((ext)=>`${entryWithoutOrWithExt}${ext}`));
30
31
  }
31
- function normalizePrefix(prefix) {
32
- if ('/' === prefix) return '';
33
- return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
34
- }
35
- function removePrefixFromPath(pathname, prefix) {
36
- const normalized = normalizePrefix(prefix);
37
- if (!normalized || pathname !== normalized && !pathname.startsWith(`${normalized}/`)) return pathname;
38
- const sliced = pathname.slice(normalized.length);
39
- return sliced.startsWith('/') ? sliced : `/${sliced}`;
40
- }
41
- function createRequestForMountedPrefix(req, prefix) {
42
- const url = new URL(req.url);
43
- const nextPath = removePrefixFromPath(url.pathname, prefix);
44
- if (nextPath === url.pathname) return req;
45
- url.pathname = nextPath;
46
- return new Request(url, req);
47
- }
48
- function maybeResponse(value) {
49
- return value instanceof Response;
50
- }
51
32
  class EffectAdapter {
52
33
  resolveEntryFile() {
53
34
  const { appDirectory, apiDirectory } = this.api.getServerContext();
@@ -193,26 +174,14 @@ class EffectAdapter {
193
174
  if (enableHandleWeb) return void await next();
194
175
  return this.handleRuntimeError(new Error('[BFF][Effect] Missing Effect entry. Define api/index or configure bff.effect.entry.'), c);
195
176
  }
196
- let response;
197
- try {
198
- const effectRequest = createRequestForMountedPrefix(c.req.raw, prefix);
199
- const effectContext = {
200
- request: effectRequest,
201
- env: c.env,
202
- path: c.req.path,
203
- method: c.req.method,
204
- operationContext: createEffectOperationContext({
205
- request: effectRequest,
206
- env: c.env,
207
- path: c.req.path,
208
- method: c.req.method
209
- })
210
- };
211
- response = await runWithEffectContext(effectContext, ()=>this.handler.length > 1 ? this.handler(effectRequest, effectContext) : this.handler(effectRequest));
212
- } catch (error) {
213
- return this.handleRuntimeError(error, c);
214
- }
215
- if (!maybeResponse(response)) return this.handleRuntimeError(new Error('[BFF][Effect] Effect handler must return a Response instance.'), c);
177
+ const response = await dispatchEffectBffRequestWithContext(this.handler, c.req.raw, {
178
+ prefix,
179
+ env: c.env,
180
+ path: c.req.path,
181
+ method: c.req.method,
182
+ runWithEffectContext: runWithEffectContext,
183
+ onError: (error)=>this.handleRuntimeError(error, c)
184
+ });
216
185
  if (404 === response.status && enableHandleWeb) return void await next();
217
186
  return new Response(response.body, response);
218
187
  }
@@ -0,0 +1,238 @@
1
+ import "node:module";
2
+ import { BACKEND_FEDERATION_CONTRACT_VERSION, BACKEND_FEDERATION_EFFECT_EXPOSE, BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_NODE_ADAPTER_VERSION, loadBackendFederatedEffectApi } from "./backend-federation.mjs";
3
+ const BACKEND_FEDERATION_MANIFEST_ADAPTER_FAILURE_EVENT = 'modernjs:microvertical-server-fallback';
4
+ class BackendFederationManifestAdapterError extends Error {
5
+ constructor(code, message, cause, details){
6
+ super(message), this.failureEvent = BACKEND_FEDERATION_MANIFEST_ADAPTER_FAILURE_EVENT;
7
+ this.name = 'BackendFederationManifestAdapterError';
8
+ this.code = code;
9
+ if (details) this.details = details;
10
+ if (void 0 !== cause) this.cause = cause;
11
+ }
12
+ }
13
+ function stringValue(value) {
14
+ return 'string' == typeof value && value.length > 0 ? value : void 0;
15
+ }
16
+ function isRecord(value) {
17
+ return 'object' == typeof value && null !== value;
18
+ }
19
+ function recordField(value, field) {
20
+ const fieldValue = value?.[field];
21
+ return isRecord(fieldValue) ? fieldValue : void 0;
22
+ }
23
+ function assertManifestAdapter(condition, code, message) {
24
+ if (!condition) throw new BackendFederationManifestAdapterError(code, message);
25
+ }
26
+ function assertVersionValue(actual, expected, label, details) {
27
+ if (void 0 === expected) return;
28
+ if (actual !== expected) throw new BackendFederationManifestAdapterError('version_mismatch', `[BFF][Effect] Backend federation ${label} mismatch: expected ${expected}, received ${actual ?? 'undefined'}.`, void 0, {
29
+ label,
30
+ expected,
31
+ received: actual,
32
+ ...details
33
+ });
34
+ }
35
+ function assertConsistentValue(left, right, label, details) {
36
+ if (void 0 === left || void 0 === right || left === right) return;
37
+ throw new BackendFederationManifestAdapterError('version_mismatch', `[BFF][Effect] Backend federation ${label} mismatch: expected ${left}, received ${right}.`, void 0, {
38
+ label,
39
+ expected: left,
40
+ received: right,
41
+ ...details
42
+ });
43
+ }
44
+ function getProcessEnv() {
45
+ return "u" > typeof process ? process.env : void 0;
46
+ }
47
+ function resolveManifestReference(options) {
48
+ if (options.manifestPath) return options.manifestPath;
49
+ if (options.manifestUrl) return options.manifestUrl;
50
+ if (!options.manifestEnv) return;
51
+ return options.env?.[options.manifestEnv] ?? getProcessEnv()?.[options.manifestEnv];
52
+ }
53
+ function isHttpUrl(value) {
54
+ return /^https?:\/\//iu.test(value);
55
+ }
56
+ async function readFileReference(reference) {
57
+ const [{ fileURLToPath }, fs] = await Promise.all([
58
+ import("node:url"),
59
+ import("node:fs/promises")
60
+ ]);
61
+ const filePath = reference.startsWith('file:') ? fileURLToPath(reference) : reference;
62
+ return fs.readFile(filePath, 'utf8');
63
+ }
64
+ async function withTimeout(promise, timeoutMs, label) {
65
+ if (!timeoutMs || timeoutMs <= 0) return promise;
66
+ let timeout;
67
+ try {
68
+ return await Promise.race([
69
+ promise,
70
+ new Promise((_, reject)=>{
71
+ timeout = setTimeout(()=>{
72
+ reject(new BackendFederationManifestAdapterError('timeout', `[BFF][Effect] ${label} timed out after ${timeoutMs}ms.`));
73
+ }, timeoutMs);
74
+ })
75
+ ]);
76
+ } finally{
77
+ if (timeout) clearTimeout(timeout);
78
+ }
79
+ }
80
+ function resolveRemoteEntryFromMetadata(manifest) {
81
+ const metaData = recordField(manifest, 'metaData');
82
+ const remoteEntry = recordField(metaData, 'remoteEntry');
83
+ const publicPath = stringValue(metaData?.publicPath) ?? stringValue(metaData?.ssrPublicPath);
84
+ const entryName = stringValue(remoteEntry?.name);
85
+ if (!publicPath || !entryName) return;
86
+ const entryPath = stringValue(remoteEntry?.path) ?? '';
87
+ const normalizedBase = publicPath.replace(/\/+$/u, '');
88
+ const normalizedPath = entryPath.replace(/^\/+|\/+$/gu, '');
89
+ return [
90
+ normalizedBase,
91
+ normalizedPath,
92
+ entryName
93
+ ].filter(Boolean).join('/');
94
+ }
95
+ function backendFederationMetadata(manifest) {
96
+ return recordField(manifest, 'backendFederation');
97
+ }
98
+ function versionBoundaryMetadata(manifest) {
99
+ return recordField(backendFederationMetadata(manifest), 'versionBoundary');
100
+ }
101
+ function deliveryUnitMetadata(record) {
102
+ return recordField(record, 'deliveryUnit');
103
+ }
104
+ function manifestDeliveryUnit(backendFederation, boundary) {
105
+ return {
106
+ boundary: deliveryUnitMetadata(boundary),
107
+ top: deliveryUnitMetadata(backendFederation)
108
+ };
109
+ }
110
+ function resolveExpectedBuildMarker(expected) {
111
+ if (void 0 !== expected.buildVersion && void 0 !== expected.buildMarker && expected.buildVersion !== expected.buildMarker) throw new BackendFederationManifestAdapterError('version_mismatch', `[BFF][Effect] Backend federation expected buildVersion/buildMarker mismatch: buildVersion ${expected.buildVersion}, buildMarker ${expected.buildMarker}.`, void 0, {
112
+ label: 'expected.buildVersion/buildMarker',
113
+ expected: expected.buildVersion,
114
+ received: expected.buildMarker
115
+ });
116
+ return expected.buildMarker;
117
+ }
118
+ function validateBackendFederationManifest(manifest, expected = {}) {
119
+ const expectedBuildMarker = resolveExpectedBuildMarker(expected);
120
+ const backendFederation = backendFederationMetadata(manifest);
121
+ assertManifestAdapter(backendFederation, 'manifest_invalid', '[BFF][Effect] Backend federation manifest must declare backendFederation metadata.');
122
+ assertManifestAdapter('effect' === backendFederation.runtimeFramework, 'strict_effect_required', '[BFF][Effect] Backend federation manifest must declare runtimeFramework: "effect".');
123
+ assertManifestAdapter(true === backendFederation.strictEffectApproach, 'strict_effect_required', '[BFF][Effect] Backend federation manifest must declare strictEffectApproach: true.');
124
+ assertVersionValue(stringValue(backendFederation.contractVersion), expected.contractVersion ?? BACKEND_FEDERATION_CONTRACT_VERSION, 'manifest contractVersion');
125
+ assertVersionValue(stringValue(backendFederation.nodeAdapterVersion), expected.nodeAdapterVersion ?? BACKEND_FEDERATION_NODE_ADAPTER_VERSION, 'manifest nodeAdapterVersion');
126
+ const boundary = versionBoundaryMetadata(manifest);
127
+ assertVersionValue(stringValue(backendFederation.name) ?? stringValue(manifest.name) ?? stringValue(manifest.id), expected.remoteName, 'manifest remoteName');
128
+ assertVersionValue(stringValue(boundary?.packageName), expected.packageName, 'versionBoundary.packageName');
129
+ assertVersionValue(stringValue(boundary?.version), expected.version, 'versionBoundary.version');
130
+ assertVersionValue(stringValue(boundary?.buildVersion), expected.buildVersion, 'versionBoundary.buildVersion');
131
+ assertConsistentValue(stringValue(manifest.version), stringValue(boundary?.version), 'manifest versionBoundary.version');
132
+ assertConsistentValue(stringValue(manifest.buildVersion), stringValue(boundary?.buildVersion), 'manifest versionBoundary.buildVersion');
133
+ const deliveryUnit = manifestDeliveryUnit(backendFederation, boundary);
134
+ assertConsistentValue(stringValue(deliveryUnit.boundary?.buildMarker), stringValue(boundary?.buildVersion), 'versionBoundary.deliveryUnit.buildMarker vs versionBoundary.buildVersion');
135
+ assertConsistentValue(stringValue(deliveryUnit.top?.unitId), stringValue(deliveryUnit.boundary?.unitId), 'backendFederation.deliveryUnit.unitId vs versionBoundary.deliveryUnit.unitId');
136
+ const manifestUnitId = stringValue(deliveryUnit.boundary?.unitId) ?? stringValue(deliveryUnit.top?.unitId);
137
+ assertVersionValue(manifestUnitId, expected.unitId, 'deliveryUnit.unitId');
138
+ assertVersionValue(stringValue(deliveryUnit.boundary?.buildMarker), expectedBuildMarker, 'deliveryUnit.buildMarker');
139
+ }
140
+ function validateLoadedBackendFederationContract(loaded, manifest, remote) {
141
+ const loadedContract = loaded.backendFederationContract;
142
+ const backendFederation = backendFederationMetadata(manifest);
143
+ const boundary = versionBoundaryMetadata(manifest);
144
+ const compatibility = recordField(loadedContract, 'compatibility');
145
+ assertManifestAdapter(compatibility, 'version_mismatch', `[BFF][Effect] Backend federation expose ${remote.name}/${remote.expose?.replace(/^\.\//u, '')} must declare compatibility metadata.`);
146
+ assertVersionValue(stringValue(loadedContract?.role), 'microvertical-server', 'expose role');
147
+ assertVersionValue(stringValue(loadedContract?.name), remote.name, 'expose name');
148
+ assertVersionValue(stringValue(compatibility.contractVersion), stringValue(backendFederation?.contractVersion), 'expose contractVersion');
149
+ assertVersionValue(stringValue(compatibility.nodeAdapterVersion), stringValue(backendFederation?.nodeAdapterVersion), 'expose nodeAdapterVersion');
150
+ assertVersionValue(stringValue(compatibility.packageName), stringValue(boundary?.packageName), 'expose packageName');
151
+ assertVersionValue(stringValue(compatibility.build), stringValue(boundary?.buildVersion), 'expose buildVersion');
152
+ const deliveryUnit = manifestDeliveryUnit(backendFederation, boundary);
153
+ const manifestUnitId = stringValue(deliveryUnit.boundary?.unitId) ?? stringValue(deliveryUnit.top?.unitId);
154
+ const manifestBuildMarker = stringValue(deliveryUnit.boundary?.buildMarker);
155
+ assertConsistentValue(manifestUnitId, stringValue(compatibility.unitId), 'deliveryUnit.unitId vs expose compatibility.unitId');
156
+ assertConsistentValue(manifestBuildMarker, stringValue(compatibility.build), 'deliveryUnit.buildMarker vs expose compatibility.build');
157
+ }
158
+ function classifyLoadError(error) {
159
+ const message = error instanceof Error ? error.message : String(error);
160
+ if (message.includes('strictEffectApproach') || message.includes('runtimeFramework')) return 'strict_effect_required';
161
+ return 'remote_unavailable';
162
+ }
163
+ async function loadBackendFederationManifest(options) {
164
+ if (options.manifest) return options.manifest;
165
+ const reference = resolveManifestReference(options);
166
+ if (!reference) throw new BackendFederationManifestAdapterError('manifest_unavailable', `[BFF][Effect] Backend federation manifest reference is missing. Pass manifest, manifestPath, manifestUrl, or manifestEnv for ${BACKEND_FEDERATION_MANIFEST_FILE}.`);
167
+ try {
168
+ const source = isHttpUrl(reference) ? await (async ()=>{
169
+ const fetchManifest = options.fetch ?? globalThis.fetch;
170
+ if (!fetchManifest) throw new BackendFederationManifestAdapterError('manifest_unavailable', `[BFF][Effect] Backend federation manifest ${reference} requires a fetch implementation.`);
171
+ const response = await withTimeout(fetchManifest(reference), options.timeoutMs, `Backend federation manifest ${reference}`);
172
+ if (!response.ok) throw new BackendFederationManifestAdapterError('manifest_unavailable', `[BFF][Effect] Backend federation manifest ${reference} returned HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}.`);
173
+ return response.text();
174
+ })() : await withTimeout(readFileReference(reference), options.timeoutMs, `Backend federation manifest ${reference}`);
175
+ const manifest = JSON.parse(source);
176
+ assertManifestAdapter(isRecord(manifest), 'manifest_invalid', `[BFF][Effect] Backend federation manifest ${reference} must be a JSON object.`);
177
+ return manifest;
178
+ } catch (error) {
179
+ if (error instanceof BackendFederationManifestAdapterError) throw error;
180
+ throw new BackendFederationManifestAdapterError('manifest_unavailable', `[BFF][Effect] Backend federation manifest ${reference} could not be loaded.`, error);
181
+ }
182
+ }
183
+ function resolveBackendFederationRemoteFromManifest(manifest, remoteOverride = {}) {
184
+ const backendFederation = backendFederationMetadata(manifest);
185
+ const entry = recordField(manifest, 'entry');
186
+ const metaData = recordField(manifest, 'metaData');
187
+ const remoteEntry = recordField(metaData, 'remoteEntry');
188
+ const remoteName = remoteOverride.name ?? stringValue(backendFederation?.name) ?? stringValue(manifest.name) ?? stringValue(manifest.id);
189
+ const remoteEntryUrl = remoteOverride.entry ?? stringValue(backendFederation?.containerEntry) ?? stringValue(entry?.url) ?? resolveRemoteEntryFromMetadata(manifest);
190
+ const remoteType = remoteOverride.type ?? stringValue(backendFederation?.remoteType) ?? stringValue(entry?.type) ?? stringValue(remoteEntry?.type) ?? 'module';
191
+ const expose = remoteOverride.expose ?? stringValue(backendFederation?.expose) ?? BACKEND_FEDERATION_EFFECT_EXPOSE;
192
+ assertManifestAdapter(remoteName, 'manifest_invalid', '[BFF][Effect] Backend federation manifest must declare a remote name.');
193
+ assertManifestAdapter(remoteEntryUrl, 'manifest_invalid', '[BFF][Effect] Backend federation manifest must declare a backend remote entry URL.');
194
+ assertManifestAdapter(expose === BACKEND_FEDERATION_EFFECT_EXPOSE, 'manifest_invalid', `[BFF][Effect] Backend federation manifest expose must be ${BACKEND_FEDERATION_EFFECT_EXPOSE}.`);
195
+ return {
196
+ name: remoteName,
197
+ entry: remoteEntryUrl,
198
+ type: remoteType,
199
+ ...remoteOverride.entryGlobalName ? {
200
+ entryGlobalName: remoteOverride.entryGlobalName
201
+ } : {},
202
+ expose,
203
+ ...remoteOverride.shareScope ? {
204
+ shareScope: remoteOverride.shareScope
205
+ } : {}
206
+ };
207
+ }
208
+ async function loadBackendFederatedEffectApiFromManifest(options) {
209
+ let manifest;
210
+ let remote;
211
+ try {
212
+ manifest = await loadBackendFederationManifest(options);
213
+ validateBackendFederationManifest(manifest, options.expected);
214
+ remote = resolveBackendFederationRemoteFromManifest(manifest, options.remote);
215
+ const loaded = await withTimeout(loadBackendFederatedEffectApi({
216
+ hostName: options.hostName,
217
+ remote,
218
+ ...options.plugins ? {
219
+ plugins: options.plugins
220
+ } : {},
221
+ ...options.runtime ? {
222
+ runtime: options.runtime
223
+ } : {}
224
+ }), options.timeoutMs, `Backend federation remote ${remote.name}`).catch((error)=>{
225
+ throw new BackendFederationManifestAdapterError(classifyLoadError(error), `[BFF][Effect] Backend federation remote ${remote?.name ?? 'unknown'} could not load ${remote?.expose ?? BACKEND_FEDERATION_EFFECT_EXPOSE}.`, error);
226
+ });
227
+ validateLoadedBackendFederationContract(loaded, manifest, remote);
228
+ return loaded;
229
+ } catch (error) {
230
+ const adapterError = error instanceof BackendFederationManifestAdapterError ? error : new BackendFederationManifestAdapterError('remote_unavailable', '[BFF][Effect] Backend federation manifest adapter failed.', error);
231
+ if (options.fallback) return options.fallback(adapterError, {
232
+ manifest,
233
+ remote
234
+ });
235
+ throw adapterError;
236
+ }
237
+ }
238
+ export { BACKEND_FEDERATION_MANIFEST_ADAPTER_FAILURE_EVENT, BackendFederationManifestAdapterError, loadBackendFederatedEffectApiFromManifest, loadBackendFederationManifest, resolveBackendFederationRemoteFromManifest };