@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.
- package/dist/cjs/runtime/effect/adapter.js +9 -40
- package/dist/cjs/runtime/effect/backend-federation-manifest.js +287 -0
- package/dist/cjs/runtime/effect/backend-federation.js +189 -0
- package/dist/cjs/runtime/effect/dispatch.js +116 -0
- package/dist/cjs/runtime/effect/edge.js +58 -69
- package/dist/cjs/runtime/effect/endpoint-contracts.js +7 -12
- package/dist/cjs/runtime/effect/entry-shape.js +87 -0
- package/dist/cjs/runtime/effect/handler.js +15 -16
- package/dist/cjs/runtime/effect/index.js +91 -15
- package/dist/cjs/runtime/effect/module.js +23 -80
- package/dist/esm/runtime/effect/adapter.mjs +10 -41
- package/dist/esm/runtime/effect/backend-federation-manifest.mjs +237 -0
- package/dist/esm/runtime/effect/backend-federation.mjs +132 -0
- package/dist/esm/runtime/effect/dispatch.mjs +63 -0
- package/dist/esm/runtime/effect/edge.mjs +17 -63
- package/dist/esm/runtime/effect/endpoint-contracts.mjs +7 -12
- package/dist/esm/runtime/effect/entry-shape.mjs +36 -0
- package/dist/esm/runtime/effect/handler.mjs +1 -4
- package/dist/esm/runtime/effect/index.mjs +3 -0
- package/dist/esm/runtime/effect/module.mjs +23 -80
- package/dist/esm-node/runtime/effect/adapter.mjs +10 -41
- package/dist/esm-node/runtime/effect/backend-federation-manifest.mjs +238 -0
- package/dist/esm-node/runtime/effect/backend-federation.mjs +133 -0
- package/dist/esm-node/runtime/effect/dispatch.mjs +64 -0
- package/dist/esm-node/runtime/effect/edge.mjs +17 -63
- package/dist/esm-node/runtime/effect/endpoint-contracts.mjs +7 -12
- package/dist/esm-node/runtime/effect/entry-shape.mjs +37 -0
- package/dist/esm-node/runtime/effect/handler.mjs +1 -4
- package/dist/esm-node/runtime/effect/index.mjs +3 -0
- package/dist/esm-node/runtime/effect/module.mjs +23 -80
- package/dist/types/runtime/effect/backend-federation-manifest.d.ts +60 -0
- package/dist/types/runtime/effect/backend-federation.d.ts +60 -0
- package/dist/types/runtime/effect/dispatch.d.ts +17 -0
- package/dist/types/runtime/effect/edge.d.ts +9 -8
- package/dist/types/runtime/effect/endpoint-contracts.d.ts +2 -2
- package/dist/types/runtime/effect/entry-shape.d.ts +31 -0
- package/dist/types/runtime/effect/handler.d.ts +1 -17
- package/dist/types/runtime/effect/index.d.ts +3 -0
- package/package.json +25 -13
|
@@ -32,26 +32,17 @@ __webpack_require__.d(__webpack_exports__, {
|
|
|
32
32
|
});
|
|
33
33
|
const Context_namespaceObject = require("effect/Context");
|
|
34
34
|
const httpapi_namespaceObject = require("effect/unstable/httpapi");
|
|
35
|
+
const external_entry_shape_js_namespaceObject = require("./entry-shape.js");
|
|
35
36
|
const external_handler_js_namespaceObject = require("./handler.js");
|
|
36
|
-
function isRecord(value) {
|
|
37
|
-
return 'object' == typeof value && null !== value;
|
|
38
|
-
}
|
|
39
|
-
function includesRuntimeExports(value) {
|
|
40
|
-
return 'api' in value || 'layer' in value || 'createHandler' in value || 'handler' in value;
|
|
41
|
-
}
|
|
42
37
|
function isRequestHandler(value) {
|
|
43
38
|
return 'function' == typeof value;
|
|
44
39
|
}
|
|
45
|
-
function isEffectApiDefinition(module) {
|
|
46
|
-
return httpapi_namespaceObject.HttpApi.isHttpApi(module.api) && void 0 !== module.layer;
|
|
47
|
-
}
|
|
48
40
|
function isEffectServiceContext(context) {
|
|
49
41
|
return 'object' == typeof context && null !== context && 'mapUnsafe' in context;
|
|
50
42
|
}
|
|
51
43
|
const emptyEffectServiceContext = Context_namespaceObject.empty();
|
|
52
|
-
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.';
|
|
53
44
|
function rejectLegacyEffectModuleShape(options, shape) {
|
|
54
|
-
options.onWarning?.(`${strictEffectApproachMessage} Rejected ${shape}.`);
|
|
45
|
+
options.onWarning?.(`${external_entry_shape_js_namespaceObject.strictEffectApproachMessage} Rejected ${shape}.`);
|
|
55
46
|
return true;
|
|
56
47
|
}
|
|
57
48
|
function callEffectBffRequestHandler(handler, request, context) {
|
|
@@ -72,41 +63,21 @@ function createLoadedHttpApiHandler(webHandler) {
|
|
|
72
63
|
dispose: webHandler.dispose
|
|
73
64
|
};
|
|
74
65
|
}
|
|
75
|
-
function
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if (
|
|
84
|
-
|
|
85
|
-
return
|
|
86
|
-
handler: entry
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
if (isRecord(entry)) normalizedModule = {
|
|
90
|
-
...normalizedModule,
|
|
91
|
-
...entry
|
|
92
|
-
};
|
|
93
|
-
if (isRecord(entry) && 'handler' in entry) {
|
|
94
|
-
const maybeHandler = entry.handler;
|
|
95
|
-
if (isRequestHandler(maybeHandler)) normalizedModule = {
|
|
96
|
-
...normalizedModule,
|
|
97
|
-
handler: maybeHandler
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
if (isRequestHandler(normalizedModule.handler)) {
|
|
101
|
-
if (rejectLegacyEffectModuleShape(options, '`handler` export')) return null;
|
|
102
|
-
return {
|
|
103
|
-
handler: normalizedModule.handler
|
|
104
|
-
};
|
|
66
|
+
function classifyEffectBffRuntimeEntryShape(module) {
|
|
67
|
+
return (0, external_entry_shape_js_namespaceObject.classifyEffectBffEntryModule)(module, {
|
|
68
|
+
isRequestHandler,
|
|
69
|
+
isValidatorAwareHandlerFactory: external_entry_shape_js_namespaceObject.isValidatorAwareHandlerFactory,
|
|
70
|
+
isHttpApi: httpapi_namespaceObject.HttpApi.isHttpApi
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
function resolveClassifiedEffectBffModuleHandler(facts, options = {}) {
|
|
74
|
+
if (!facts) return null;
|
|
75
|
+
if (facts.legacyShape) {
|
|
76
|
+
if (rejectLegacyEffectModuleShape(options, facts.legacyShape)) return null;
|
|
105
77
|
}
|
|
106
|
-
if ('function' == typeof
|
|
107
|
-
|
|
108
|
-
const
|
|
109
|
-
if (!validatorAware && rejectLegacyEffectModuleShape(options, 'unbranded `createHandler` export')) return null;
|
|
78
|
+
if ('function' == typeof facts.createHandler) {
|
|
79
|
+
if (!facts.createHandlerValidatorAware && rejectLegacyEffectModuleShape(options, 'unbranded `createHandler` export')) return null;
|
|
80
|
+
const factory = facts.createHandler;
|
|
110
81
|
const webHandler = factory({
|
|
111
82
|
openapi: options.openapi,
|
|
112
83
|
dataPlatform: options.dataPlatform,
|
|
@@ -114,11 +85,11 @@ function resolveNormalizedEffectBffModuleHandler(normalizedModule, options = {})
|
|
|
114
85
|
});
|
|
115
86
|
return createLoadedHandler(webHandler);
|
|
116
87
|
}
|
|
117
|
-
if (
|
|
88
|
+
if (void 0 !== facts.api && facts.hasRuntimeLayer) {
|
|
118
89
|
options.onWarning?.('[BFF][Effect] Detected { api, layer } export without createHandler. Prefer `defineEffectBff(...)` from @modern-js/plugin-bff/server to avoid module instance mismatch.');
|
|
119
90
|
const webHandler = (0, external_handler_js_namespaceObject.createHttpApiHandler)({
|
|
120
|
-
api:
|
|
121
|
-
layer:
|
|
91
|
+
api: facts.api,
|
|
92
|
+
layer: facts.layer,
|
|
122
93
|
openapi: options.openapi,
|
|
123
94
|
dataPlatform: options.dataPlatform,
|
|
124
95
|
validateRequest: options.validateRequest
|
|
@@ -127,39 +98,11 @@ function resolveNormalizedEffectBffModuleHandler(normalizedModule, options = {})
|
|
|
127
98
|
}
|
|
128
99
|
return null;
|
|
129
100
|
}
|
|
101
|
+
function resolveNormalizedEffectBffModuleHandler(normalizedModule, options = {}) {
|
|
102
|
+
return resolveClassifiedEffectBffModuleHandler(classifyEffectBffRuntimeEntryShape(normalizedModule), options);
|
|
103
|
+
}
|
|
130
104
|
function resolveEffectBffModuleHandler(mod, options = {}) {
|
|
131
|
-
|
|
132
|
-
const mergeRuntimeExports = (value)=>{
|
|
133
|
-
if (!isRecord(value) || !includesRuntimeExports(value)) return;
|
|
134
|
-
normalizedModule = {
|
|
135
|
-
...normalizedModule,
|
|
136
|
-
...value
|
|
137
|
-
};
|
|
138
|
-
};
|
|
139
|
-
if (isRequestHandler(normalizedModule.handler)) {
|
|
140
|
-
if (rejectLegacyEffectModuleShape(options, '`handler` export')) return Promise.resolve(null);
|
|
141
|
-
return Promise.resolve({
|
|
142
|
-
handler: normalizedModule.handler
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
const entry = normalizedModule.default;
|
|
146
|
-
if (isRequestHandler(entry)) {
|
|
147
|
-
if (rejectLegacyEffectModuleShape(options, 'default request handler')) return Promise.resolve(null);
|
|
148
|
-
return Promise.resolve({
|
|
149
|
-
handler: entry
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
if ('function' == typeof entry && 0 === entry.length) return Promise.resolve(entry()).then((out)=>{
|
|
153
|
-
if (isRequestHandler(out)) {
|
|
154
|
-
if (rejectLegacyEffectModuleShape(options, 'default factory returning a request handler')) return null;
|
|
155
|
-
return {
|
|
156
|
-
handler: out
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
mergeRuntimeExports(out);
|
|
160
|
-
return resolveNormalizedEffectBffModuleHandler(normalizedModule, options);
|
|
161
|
-
});
|
|
162
|
-
return Promise.resolve(resolveNormalizedEffectBffModuleHandler(normalizedModule, options));
|
|
105
|
+
return Promise.resolve(resolveNormalizedEffectBffModuleHandler(mod, options));
|
|
163
106
|
}
|
|
164
107
|
exports.resolveEffectBffModuleHandler = __webpack_exports__.resolveEffectBffModuleHandler;
|
|
165
108
|
for(var __rspack_i in __webpack_exports__)if (-1 === [
|
|
@@ -3,7 +3,8 @@ import { HttpApi } from "effect/unstable/httpapi";
|
|
|
3
3
|
import path from "path";
|
|
4
4
|
import { checkCrossProjectPolicyForRequest, resolveAdapterCrossProjectPolicy } from "../../utils/crossProjectServerPolicy.mjs";
|
|
5
5
|
import { createSafeFailureResponse } from "../safe-failure.mjs";
|
|
6
|
-
import {
|
|
6
|
+
import { runWithEffectContext } from "./context.mjs";
|
|
7
|
+
import { dispatchEffectBffRequestWithContext } from "./dispatch.mjs";
|
|
7
8
|
import { collectEffectEndpoints, extractHttpApiFromModule, toOperationContractSources } from "./endpoint-contracts.mjs";
|
|
8
9
|
import { resolveEffectBffModuleHandler } from "./module.mjs";
|
|
9
10
|
const before = [
|
|
@@ -26,26 +27,6 @@ function resolveJsOrTsEntry(entryWithoutOrWithExt) {
|
|
|
26
27
|
if (JS_OR_TS_EXTS.includes(extension)) return fs.existsSync(entryWithoutOrWithExt) ? entryWithoutOrWithExt : void 0;
|
|
27
28
|
return findExists(JS_OR_TS_EXTS.map((ext)=>`${entryWithoutOrWithExt}${ext}`));
|
|
28
29
|
}
|
|
29
|
-
function normalizePrefix(prefix) {
|
|
30
|
-
if ('/' === prefix) return '';
|
|
31
|
-
return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
|
|
32
|
-
}
|
|
33
|
-
function removePrefixFromPath(pathname, prefix) {
|
|
34
|
-
const normalized = normalizePrefix(prefix);
|
|
35
|
-
if (!normalized || pathname !== normalized && !pathname.startsWith(`${normalized}/`)) return pathname;
|
|
36
|
-
const sliced = pathname.slice(normalized.length);
|
|
37
|
-
return sliced.startsWith('/') ? sliced : `/${sliced}`;
|
|
38
|
-
}
|
|
39
|
-
function createRequestForMountedPrefix(req, prefix) {
|
|
40
|
-
const url = new URL(req.url);
|
|
41
|
-
const nextPath = removePrefixFromPath(url.pathname, prefix);
|
|
42
|
-
if (nextPath === url.pathname) return req;
|
|
43
|
-
url.pathname = nextPath;
|
|
44
|
-
return new Request(url, req);
|
|
45
|
-
}
|
|
46
|
-
function maybeResponse(value) {
|
|
47
|
-
return value instanceof Response;
|
|
48
|
-
}
|
|
49
30
|
class EffectAdapter {
|
|
50
31
|
resolveEntryFile() {
|
|
51
32
|
const { appDirectory, apiDirectory } = this.api.getServerContext();
|
|
@@ -191,26 +172,14 @@ class EffectAdapter {
|
|
|
191
172
|
if (enableHandleWeb) return void await next();
|
|
192
173
|
return this.handleRuntimeError(new Error('[BFF][Effect] Missing Effect entry. Define api/index or configure bff.effect.entry.'), c);
|
|
193
174
|
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
operationContext: createEffectOperationContext({
|
|
203
|
-
request: effectRequest,
|
|
204
|
-
env: c.env,
|
|
205
|
-
path: c.req.path,
|
|
206
|
-
method: c.req.method
|
|
207
|
-
})
|
|
208
|
-
};
|
|
209
|
-
response = await runWithEffectContext(effectContext, ()=>this.handler.length > 1 ? this.handler(effectRequest, effectContext) : this.handler(effectRequest));
|
|
210
|
-
} catch (error) {
|
|
211
|
-
return this.handleRuntimeError(error, c);
|
|
212
|
-
}
|
|
213
|
-
if (!maybeResponse(response)) return this.handleRuntimeError(new Error('[BFF][Effect] Effect handler must return a Response instance.'), c);
|
|
175
|
+
const response = await dispatchEffectBffRequestWithContext(this.handler, c.req.raw, {
|
|
176
|
+
prefix,
|
|
177
|
+
env: c.env,
|
|
178
|
+
path: c.req.path,
|
|
179
|
+
method: c.req.method,
|
|
180
|
+
runWithEffectContext: runWithEffectContext,
|
|
181
|
+
onError: (error)=>this.handleRuntimeError(error, c)
|
|
182
|
+
});
|
|
214
183
|
if (404 === response.status && enableHandleWeb) return void await next();
|
|
215
184
|
return new Response(response.body, response);
|
|
216
185
|
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { BACKEND_FEDERATION_CONTRACT_VERSION, BACKEND_FEDERATION_EFFECT_EXPOSE, BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_NODE_ADAPTER_VERSION, loadBackendFederatedEffectApi } from "./backend-federation.mjs";
|
|
2
|
+
const BACKEND_FEDERATION_MANIFEST_ADAPTER_FAILURE_EVENT = 'modernjs:microvertical-server-fallback';
|
|
3
|
+
class BackendFederationManifestAdapterError extends Error {
|
|
4
|
+
constructor(code, message, cause, details){
|
|
5
|
+
super(message), this.failureEvent = BACKEND_FEDERATION_MANIFEST_ADAPTER_FAILURE_EVENT;
|
|
6
|
+
this.name = 'BackendFederationManifestAdapterError';
|
|
7
|
+
this.code = code;
|
|
8
|
+
if (details) this.details = details;
|
|
9
|
+
if (void 0 !== cause) this.cause = cause;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function stringValue(value) {
|
|
13
|
+
return 'string' == typeof value && value.length > 0 ? value : void 0;
|
|
14
|
+
}
|
|
15
|
+
function isRecord(value) {
|
|
16
|
+
return 'object' == typeof value && null !== value;
|
|
17
|
+
}
|
|
18
|
+
function recordField(value, field) {
|
|
19
|
+
const fieldValue = value?.[field];
|
|
20
|
+
return isRecord(fieldValue) ? fieldValue : void 0;
|
|
21
|
+
}
|
|
22
|
+
function assertManifestAdapter(condition, code, message) {
|
|
23
|
+
if (!condition) throw new BackendFederationManifestAdapterError(code, message);
|
|
24
|
+
}
|
|
25
|
+
function assertVersionValue(actual, expected, label, details) {
|
|
26
|
+
if (void 0 === expected) return;
|
|
27
|
+
if (actual !== expected) throw new BackendFederationManifestAdapterError('version_mismatch', `[BFF][Effect] Backend federation ${label} mismatch: expected ${expected}, received ${actual ?? 'undefined'}.`, void 0, {
|
|
28
|
+
label,
|
|
29
|
+
expected,
|
|
30
|
+
received: actual,
|
|
31
|
+
...details
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
function assertConsistentValue(left, right, label, details) {
|
|
35
|
+
if (void 0 === left || void 0 === right || left === right) return;
|
|
36
|
+
throw new BackendFederationManifestAdapterError('version_mismatch', `[BFF][Effect] Backend federation ${label} mismatch: expected ${left}, received ${right}.`, void 0, {
|
|
37
|
+
label,
|
|
38
|
+
expected: left,
|
|
39
|
+
received: right,
|
|
40
|
+
...details
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
function getProcessEnv() {
|
|
44
|
+
return "u" > typeof process ? process.env : void 0;
|
|
45
|
+
}
|
|
46
|
+
function resolveManifestReference(options) {
|
|
47
|
+
if (options.manifestPath) return options.manifestPath;
|
|
48
|
+
if (options.manifestUrl) return options.manifestUrl;
|
|
49
|
+
if (!options.manifestEnv) return;
|
|
50
|
+
return options.env?.[options.manifestEnv] ?? getProcessEnv()?.[options.manifestEnv];
|
|
51
|
+
}
|
|
52
|
+
function isHttpUrl(value) {
|
|
53
|
+
return /^https?:\/\//iu.test(value);
|
|
54
|
+
}
|
|
55
|
+
async function readFileReference(reference) {
|
|
56
|
+
const [{ fileURLToPath }, fs] = await Promise.all([
|
|
57
|
+
import("node:url"),
|
|
58
|
+
import("node:fs/promises")
|
|
59
|
+
]);
|
|
60
|
+
const filePath = reference.startsWith('file:') ? fileURLToPath(reference) : reference;
|
|
61
|
+
return fs.readFile(filePath, 'utf8');
|
|
62
|
+
}
|
|
63
|
+
async function withTimeout(promise, timeoutMs, label) {
|
|
64
|
+
if (!timeoutMs || timeoutMs <= 0) return promise;
|
|
65
|
+
let timeout;
|
|
66
|
+
try {
|
|
67
|
+
return await Promise.race([
|
|
68
|
+
promise,
|
|
69
|
+
new Promise((_, reject)=>{
|
|
70
|
+
timeout = setTimeout(()=>{
|
|
71
|
+
reject(new BackendFederationManifestAdapterError('timeout', `[BFF][Effect] ${label} timed out after ${timeoutMs}ms.`));
|
|
72
|
+
}, timeoutMs);
|
|
73
|
+
})
|
|
74
|
+
]);
|
|
75
|
+
} finally{
|
|
76
|
+
if (timeout) clearTimeout(timeout);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function resolveRemoteEntryFromMetadata(manifest) {
|
|
80
|
+
const metaData = recordField(manifest, 'metaData');
|
|
81
|
+
const remoteEntry = recordField(metaData, 'remoteEntry');
|
|
82
|
+
const publicPath = stringValue(metaData?.publicPath) ?? stringValue(metaData?.ssrPublicPath);
|
|
83
|
+
const entryName = stringValue(remoteEntry?.name);
|
|
84
|
+
if (!publicPath || !entryName) return;
|
|
85
|
+
const entryPath = stringValue(remoteEntry?.path) ?? '';
|
|
86
|
+
const normalizedBase = publicPath.replace(/\/+$/u, '');
|
|
87
|
+
const normalizedPath = entryPath.replace(/^\/+|\/+$/gu, '');
|
|
88
|
+
return [
|
|
89
|
+
normalizedBase,
|
|
90
|
+
normalizedPath,
|
|
91
|
+
entryName
|
|
92
|
+
].filter(Boolean).join('/');
|
|
93
|
+
}
|
|
94
|
+
function backendFederationMetadata(manifest) {
|
|
95
|
+
return recordField(manifest, 'backendFederation');
|
|
96
|
+
}
|
|
97
|
+
function versionBoundaryMetadata(manifest) {
|
|
98
|
+
return recordField(backendFederationMetadata(manifest), 'versionBoundary');
|
|
99
|
+
}
|
|
100
|
+
function deliveryUnitMetadata(record) {
|
|
101
|
+
return recordField(record, 'deliveryUnit');
|
|
102
|
+
}
|
|
103
|
+
function manifestDeliveryUnit(backendFederation, boundary) {
|
|
104
|
+
return {
|
|
105
|
+
boundary: deliveryUnitMetadata(boundary),
|
|
106
|
+
top: deliveryUnitMetadata(backendFederation)
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function resolveExpectedBuildMarker(expected) {
|
|
110
|
+
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, {
|
|
111
|
+
label: 'expected.buildVersion/buildMarker',
|
|
112
|
+
expected: expected.buildVersion,
|
|
113
|
+
received: expected.buildMarker
|
|
114
|
+
});
|
|
115
|
+
return expected.buildMarker;
|
|
116
|
+
}
|
|
117
|
+
function validateBackendFederationManifest(manifest, expected = {}) {
|
|
118
|
+
const expectedBuildMarker = resolveExpectedBuildMarker(expected);
|
|
119
|
+
const backendFederation = backendFederationMetadata(manifest);
|
|
120
|
+
assertManifestAdapter(backendFederation, 'manifest_invalid', '[BFF][Effect] Backend federation manifest must declare backendFederation metadata.');
|
|
121
|
+
assertManifestAdapter('effect' === backendFederation.runtimeFramework, 'strict_effect_required', '[BFF][Effect] Backend federation manifest must declare runtimeFramework: "effect".');
|
|
122
|
+
assertManifestAdapter(true === backendFederation.strictEffectApproach, 'strict_effect_required', '[BFF][Effect] Backend federation manifest must declare strictEffectApproach: true.');
|
|
123
|
+
assertVersionValue(stringValue(backendFederation.contractVersion), expected.contractVersion ?? BACKEND_FEDERATION_CONTRACT_VERSION, 'manifest contractVersion');
|
|
124
|
+
assertVersionValue(stringValue(backendFederation.nodeAdapterVersion), expected.nodeAdapterVersion ?? BACKEND_FEDERATION_NODE_ADAPTER_VERSION, 'manifest nodeAdapterVersion');
|
|
125
|
+
const boundary = versionBoundaryMetadata(manifest);
|
|
126
|
+
assertVersionValue(stringValue(backendFederation.name) ?? stringValue(manifest.name) ?? stringValue(manifest.id), expected.remoteName, 'manifest remoteName');
|
|
127
|
+
assertVersionValue(stringValue(boundary?.packageName), expected.packageName, 'versionBoundary.packageName');
|
|
128
|
+
assertVersionValue(stringValue(boundary?.version), expected.version, 'versionBoundary.version');
|
|
129
|
+
assertVersionValue(stringValue(boundary?.buildVersion), expected.buildVersion, 'versionBoundary.buildVersion');
|
|
130
|
+
assertConsistentValue(stringValue(manifest.version), stringValue(boundary?.version), 'manifest versionBoundary.version');
|
|
131
|
+
assertConsistentValue(stringValue(manifest.buildVersion), stringValue(boundary?.buildVersion), 'manifest versionBoundary.buildVersion');
|
|
132
|
+
const deliveryUnit = manifestDeliveryUnit(backendFederation, boundary);
|
|
133
|
+
assertConsistentValue(stringValue(deliveryUnit.boundary?.buildMarker), stringValue(boundary?.buildVersion), 'versionBoundary.deliveryUnit.buildMarker vs versionBoundary.buildVersion');
|
|
134
|
+
assertConsistentValue(stringValue(deliveryUnit.top?.unitId), stringValue(deliveryUnit.boundary?.unitId), 'backendFederation.deliveryUnit.unitId vs versionBoundary.deliveryUnit.unitId');
|
|
135
|
+
const manifestUnitId = stringValue(deliveryUnit.boundary?.unitId) ?? stringValue(deliveryUnit.top?.unitId);
|
|
136
|
+
assertVersionValue(manifestUnitId, expected.unitId, 'deliveryUnit.unitId');
|
|
137
|
+
assertVersionValue(stringValue(deliveryUnit.boundary?.buildMarker), expectedBuildMarker, 'deliveryUnit.buildMarker');
|
|
138
|
+
}
|
|
139
|
+
function validateLoadedBackendFederationContract(loaded, manifest, remote) {
|
|
140
|
+
const loadedContract = loaded.backendFederationContract;
|
|
141
|
+
const backendFederation = backendFederationMetadata(manifest);
|
|
142
|
+
const boundary = versionBoundaryMetadata(manifest);
|
|
143
|
+
const compatibility = recordField(loadedContract, 'compatibility');
|
|
144
|
+
assertManifestAdapter(compatibility, 'version_mismatch', `[BFF][Effect] Backend federation expose ${remote.name}/${remote.expose?.replace(/^\.\//u, '')} must declare compatibility metadata.`);
|
|
145
|
+
assertVersionValue(stringValue(loadedContract?.role), 'microvertical-server', 'expose role');
|
|
146
|
+
assertVersionValue(stringValue(loadedContract?.name), remote.name, 'expose name');
|
|
147
|
+
assertVersionValue(stringValue(compatibility.contractVersion), stringValue(backendFederation?.contractVersion), 'expose contractVersion');
|
|
148
|
+
assertVersionValue(stringValue(compatibility.nodeAdapterVersion), stringValue(backendFederation?.nodeAdapterVersion), 'expose nodeAdapterVersion');
|
|
149
|
+
assertVersionValue(stringValue(compatibility.packageName), stringValue(boundary?.packageName), 'expose packageName');
|
|
150
|
+
assertVersionValue(stringValue(compatibility.build), stringValue(boundary?.buildVersion), 'expose buildVersion');
|
|
151
|
+
const deliveryUnit = manifestDeliveryUnit(backendFederation, boundary);
|
|
152
|
+
const manifestUnitId = stringValue(deliveryUnit.boundary?.unitId) ?? stringValue(deliveryUnit.top?.unitId);
|
|
153
|
+
const manifestBuildMarker = stringValue(deliveryUnit.boundary?.buildMarker);
|
|
154
|
+
assertConsistentValue(manifestUnitId, stringValue(compatibility.unitId), 'deliveryUnit.unitId vs expose compatibility.unitId');
|
|
155
|
+
assertConsistentValue(manifestBuildMarker, stringValue(compatibility.build), 'deliveryUnit.buildMarker vs expose compatibility.build');
|
|
156
|
+
}
|
|
157
|
+
function classifyLoadError(error) {
|
|
158
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
159
|
+
if (message.includes('strictEffectApproach') || message.includes('runtimeFramework')) return 'strict_effect_required';
|
|
160
|
+
return 'remote_unavailable';
|
|
161
|
+
}
|
|
162
|
+
async function loadBackendFederationManifest(options) {
|
|
163
|
+
if (options.manifest) return options.manifest;
|
|
164
|
+
const reference = resolveManifestReference(options);
|
|
165
|
+
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}.`);
|
|
166
|
+
try {
|
|
167
|
+
const source = isHttpUrl(reference) ? await (async ()=>{
|
|
168
|
+
const fetchManifest = options.fetch ?? globalThis.fetch;
|
|
169
|
+
if (!fetchManifest) throw new BackendFederationManifestAdapterError('manifest_unavailable', `[BFF][Effect] Backend federation manifest ${reference} requires a fetch implementation.`);
|
|
170
|
+
const response = await withTimeout(fetchManifest(reference), options.timeoutMs, `Backend federation manifest ${reference}`);
|
|
171
|
+
if (!response.ok) throw new BackendFederationManifestAdapterError('manifest_unavailable', `[BFF][Effect] Backend federation manifest ${reference} returned HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}.`);
|
|
172
|
+
return response.text();
|
|
173
|
+
})() : await withTimeout(readFileReference(reference), options.timeoutMs, `Backend federation manifest ${reference}`);
|
|
174
|
+
const manifest = JSON.parse(source);
|
|
175
|
+
assertManifestAdapter(isRecord(manifest), 'manifest_invalid', `[BFF][Effect] Backend federation manifest ${reference} must be a JSON object.`);
|
|
176
|
+
return manifest;
|
|
177
|
+
} catch (error) {
|
|
178
|
+
if (error instanceof BackendFederationManifestAdapterError) throw error;
|
|
179
|
+
throw new BackendFederationManifestAdapterError('manifest_unavailable', `[BFF][Effect] Backend federation manifest ${reference} could not be loaded.`, error);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function resolveBackendFederationRemoteFromManifest(manifest, remoteOverride = {}) {
|
|
183
|
+
const backendFederation = backendFederationMetadata(manifest);
|
|
184
|
+
const entry = recordField(manifest, 'entry');
|
|
185
|
+
const metaData = recordField(manifest, 'metaData');
|
|
186
|
+
const remoteEntry = recordField(metaData, 'remoteEntry');
|
|
187
|
+
const remoteName = remoteOverride.name ?? stringValue(backendFederation?.name) ?? stringValue(manifest.name) ?? stringValue(manifest.id);
|
|
188
|
+
const remoteEntryUrl = remoteOverride.entry ?? stringValue(backendFederation?.containerEntry) ?? stringValue(entry?.url) ?? resolveRemoteEntryFromMetadata(manifest);
|
|
189
|
+
const remoteType = remoteOverride.type ?? stringValue(backendFederation?.remoteType) ?? stringValue(entry?.type) ?? stringValue(remoteEntry?.type) ?? 'module';
|
|
190
|
+
const expose = remoteOverride.expose ?? stringValue(backendFederation?.expose) ?? BACKEND_FEDERATION_EFFECT_EXPOSE;
|
|
191
|
+
assertManifestAdapter(remoteName, 'manifest_invalid', '[BFF][Effect] Backend federation manifest must declare a remote name.');
|
|
192
|
+
assertManifestAdapter(remoteEntryUrl, 'manifest_invalid', '[BFF][Effect] Backend federation manifest must declare a backend remote entry URL.');
|
|
193
|
+
assertManifestAdapter(expose === BACKEND_FEDERATION_EFFECT_EXPOSE, 'manifest_invalid', `[BFF][Effect] Backend federation manifest expose must be ${BACKEND_FEDERATION_EFFECT_EXPOSE}.`);
|
|
194
|
+
return {
|
|
195
|
+
name: remoteName,
|
|
196
|
+
entry: remoteEntryUrl,
|
|
197
|
+
type: remoteType,
|
|
198
|
+
...remoteOverride.entryGlobalName ? {
|
|
199
|
+
entryGlobalName: remoteOverride.entryGlobalName
|
|
200
|
+
} : {},
|
|
201
|
+
expose,
|
|
202
|
+
...remoteOverride.shareScope ? {
|
|
203
|
+
shareScope: remoteOverride.shareScope
|
|
204
|
+
} : {}
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
async function loadBackendFederatedEffectApiFromManifest(options) {
|
|
208
|
+
let manifest;
|
|
209
|
+
let remote;
|
|
210
|
+
try {
|
|
211
|
+
manifest = await loadBackendFederationManifest(options);
|
|
212
|
+
validateBackendFederationManifest(manifest, options.expected);
|
|
213
|
+
remote = resolveBackendFederationRemoteFromManifest(manifest, options.remote);
|
|
214
|
+
const loaded = await withTimeout(loadBackendFederatedEffectApi({
|
|
215
|
+
hostName: options.hostName,
|
|
216
|
+
remote,
|
|
217
|
+
...options.plugins ? {
|
|
218
|
+
plugins: options.plugins
|
|
219
|
+
} : {},
|
|
220
|
+
...options.runtime ? {
|
|
221
|
+
runtime: options.runtime
|
|
222
|
+
} : {}
|
|
223
|
+
}), options.timeoutMs, `Backend federation remote ${remote.name}`).catch((error)=>{
|
|
224
|
+
throw new BackendFederationManifestAdapterError(classifyLoadError(error), `[BFF][Effect] Backend federation remote ${remote?.name ?? 'unknown'} could not load ${remote?.expose ?? BACKEND_FEDERATION_EFFECT_EXPOSE}.`, error);
|
|
225
|
+
});
|
|
226
|
+
validateLoadedBackendFederationContract(loaded, manifest, remote);
|
|
227
|
+
return loaded;
|
|
228
|
+
} catch (error) {
|
|
229
|
+
const adapterError = error instanceof BackendFederationManifestAdapterError ? error : new BackendFederationManifestAdapterError('remote_unavailable', '[BFF][Effect] Backend federation manifest adapter failed.', error);
|
|
230
|
+
if (options.fallback) return options.fallback(adapterError, {
|
|
231
|
+
manifest,
|
|
232
|
+
remote
|
|
233
|
+
});
|
|
234
|
+
throw adapterError;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
export { BACKEND_FEDERATION_MANIFEST_ADAPTER_FAILURE_EVENT, BackendFederationManifestAdapterError, loadBackendFederatedEffectApiFromManifest, loadBackendFederationManifest, resolveBackendFederationRemoteFromManifest };
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
const BACKEND_FEDERATION_EFFECT_EXPOSE = './effect-api';
|
|
2
|
+
const BACKEND_FEDERATION_MANIFEST_FILE = 'backend-mf-manifest.json';
|
|
3
|
+
const BACKEND_FEDERATION_CONTRACT_VERSION = 'microvertical-server-effect-v1';
|
|
4
|
+
const BACKEND_FEDERATION_NODE_ADAPTER_VERSION = 'backend-mf-effect-v1';
|
|
5
|
+
function normalizeExpose(expose) {
|
|
6
|
+
return expose.replace(/^\.\//u, '');
|
|
7
|
+
}
|
|
8
|
+
function exposeForRemoteRequest(expose) {
|
|
9
|
+
return `./${normalizeExpose(expose)}`;
|
|
10
|
+
}
|
|
11
|
+
function isRecord(value) {
|
|
12
|
+
return 'object' == typeof value && null !== value;
|
|
13
|
+
}
|
|
14
|
+
function collectRemotes(options) {
|
|
15
|
+
const remotes = [
|
|
16
|
+
...options.remotes ?? []
|
|
17
|
+
];
|
|
18
|
+
if (options.remote) {
|
|
19
|
+
const existingIndex = remotes.findIndex((remote)=>remote.name === options.remote?.name);
|
|
20
|
+
if (existingIndex >= 0) remotes[existingIndex] = options.remote;
|
|
21
|
+
else remotes.push(options.remote);
|
|
22
|
+
}
|
|
23
|
+
return remotes;
|
|
24
|
+
}
|
|
25
|
+
function parseRemoteRequest(request) {
|
|
26
|
+
const [remoteName, ...exposeParts] = request.split('/');
|
|
27
|
+
if (!remoteName || 0 === exposeParts.length) throw new Error(`[BFF][Effect] Invalid backend federation request ${request}.`);
|
|
28
|
+
return {
|
|
29
|
+
remoteName,
|
|
30
|
+
expose: exposeForRemoteRequest(exposeParts.join('/'))
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function decodeDataUrl(url) {
|
|
34
|
+
const commaIndex = url.indexOf(',');
|
|
35
|
+
if (commaIndex < 0) throw new Error('[BFF][Effect] Invalid backend federation data URL entry.');
|
|
36
|
+
return decodeURIComponent(url.slice(commaIndex + 1));
|
|
37
|
+
}
|
|
38
|
+
async function readCommonJsEntrySource(remote) {
|
|
39
|
+
if (remote.entry.startsWith('data:')) return decodeDataUrl(remote.entry);
|
|
40
|
+
if (remote.entry.startsWith('http://') || remote.entry.startsWith('https://')) {
|
|
41
|
+
const response = await fetch(remote.entry);
|
|
42
|
+
if (!response.ok) throw new Error(`[BFF][Effect] Failed to load backend federation remote ${remote.name}: ${response.status}`);
|
|
43
|
+
return response.text();
|
|
44
|
+
}
|
|
45
|
+
throw new Error(`[BFF][Effect] Backend federation remote ${remote.name} cannot load CommonJS entry ${remote.entry}.`);
|
|
46
|
+
}
|
|
47
|
+
function evaluateCommonJsEntry(remote, source) {
|
|
48
|
+
const module = {
|
|
49
|
+
exports: {}
|
|
50
|
+
};
|
|
51
|
+
const exports = module.exports;
|
|
52
|
+
const evaluate = new Function('module', 'exports', 'globalThis', source);
|
|
53
|
+
evaluate(module, exports, globalThis);
|
|
54
|
+
const entry = module.exports.default ?? module.exports;
|
|
55
|
+
if (!isRecord(entry)) throw new Error(`[BFF][Effect] Backend federation remote ${remote.name} entry must load object module.`);
|
|
56
|
+
return entry;
|
|
57
|
+
}
|
|
58
|
+
async function importModuleEntry(remote) {
|
|
59
|
+
const entry = await import(remote.entry);
|
|
60
|
+
return entry.default ?? entry;
|
|
61
|
+
}
|
|
62
|
+
async function resolvePluginEntry(remote, plugins) {
|
|
63
|
+
for (const plugin of plugins ?? []){
|
|
64
|
+
const loadEntry = plugin.loadEntry;
|
|
65
|
+
if ('function' != typeof loadEntry) continue;
|
|
66
|
+
const entry = await loadEntry({
|
|
67
|
+
remoteInfo: remote
|
|
68
|
+
});
|
|
69
|
+
if (entry) return entry;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function loadBackendFederationEntry(remote, plugins) {
|
|
73
|
+
const pluginEntry = await resolvePluginEntry(remote, plugins);
|
|
74
|
+
if (pluginEntry) return pluginEntry;
|
|
75
|
+
if (remote.entryGlobalName) {
|
|
76
|
+
const globalEntry = globalThis[remote.entryGlobalName];
|
|
77
|
+
if (isRecord(globalEntry)) return globalEntry;
|
|
78
|
+
}
|
|
79
|
+
if ('module' === remote.type || remote.entry.startsWith('file:')) return importModuleEntry(remote);
|
|
80
|
+
return evaluateCommonJsEntry(remote, await readCommonJsEntrySource(remote));
|
|
81
|
+
}
|
|
82
|
+
async function loadBackendFederationExpose(remote, expose, options) {
|
|
83
|
+
const entry = await loadBackendFederationEntry(remote, options.plugins);
|
|
84
|
+
if ('function' == typeof entry.init) await entry.init({
|
|
85
|
+
hostName: options.hostName
|
|
86
|
+
});
|
|
87
|
+
if ('function' != typeof entry.get) throw new Error(`[BFF][Effect] Backend federation remote ${remote.name} entry must expose get().`);
|
|
88
|
+
const factory = await entry.get(expose);
|
|
89
|
+
if ('function' != typeof factory) throw new Error(`[BFF][Effect] Backend federation expose ${remote.name}/${normalizeExpose(expose)} must load factory function.`);
|
|
90
|
+
return factory();
|
|
91
|
+
}
|
|
92
|
+
function createBackendFederationRuntime(options) {
|
|
93
|
+
const remotes = collectRemotes(options);
|
|
94
|
+
return {
|
|
95
|
+
async loadRemote (request) {
|
|
96
|
+
const { remoteName, expose } = parseRemoteRequest(request);
|
|
97
|
+
const remote = remotes.find((candidate)=>candidate.name === remoteName);
|
|
98
|
+
if (!remote) throw new Error(`[BFF][Effect] Missing backend federation remote ${remoteName}.`);
|
|
99
|
+
return loadBackendFederationExpose(remote, expose, options);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function createBackendFederationLoadEntryPlugin(options) {
|
|
104
|
+
return {
|
|
105
|
+
name: 'modernjs-backend-federation-load-entry',
|
|
106
|
+
async loadEntry ({ remoteInfo }) {
|
|
107
|
+
return options.resolveEntry({
|
|
108
|
+
name: remoteInfo.name,
|
|
109
|
+
entry: remoteInfo.entry,
|
|
110
|
+
type: remoteInfo.type,
|
|
111
|
+
entryGlobalName: remoteInfo.entryGlobalName,
|
|
112
|
+
shareScope: remoteInfo.shareScope
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
async function loadBackendFederatedEffectApi(options) {
|
|
118
|
+
const remoteName = options.remote?.name ?? options.remoteName;
|
|
119
|
+
if (!remoteName) throw new Error('[BFF][Effect] Missing backend federation remote name.');
|
|
120
|
+
const runtime = options.runtime ?? createBackendFederationRuntime(options);
|
|
121
|
+
const expose = options.expose ?? options.remote?.expose ?? BACKEND_FEDERATION_EFFECT_EXPOSE;
|
|
122
|
+
const remoteRequest = `${remoteName}/${normalizeExpose(expose)}`;
|
|
123
|
+
const loaded = await runtime.loadRemote(remoteRequest);
|
|
124
|
+
if (!isRecord(loaded)) throw new Error(`[BFF][Effect] Backend federation expose ${remoteRequest} must load an object module.`);
|
|
125
|
+
const backendContract = loaded.backendFederationContract;
|
|
126
|
+
if (!isRecord(backendContract) || true !== backendContract.strictEffectApproach) throw new Error(`[BFF][Effect] Backend federation expose ${remoteRequest} must expose strict Effect metadata (strictEffectApproach: true).`);
|
|
127
|
+
if ('effect' !== backendContract.runtimeFramework) throw new Error(`[BFF][Effect] Backend federation expose ${remoteRequest} must expose strict Effect metadata (runtimeFramework: "effect").`);
|
|
128
|
+
if ('string' == typeof backendContract.name && backendContract.name !== remoteName) throw new Error(`[BFF][Effect] Backend federation expose ${remoteRequest} metadata name mismatch: expected ${remoteName}, received ${backendContract.name}.`);
|
|
129
|
+
if (!('runtime' in loaded)) throw new Error(`[BFF][Effect] Backend federation expose ${remoteRequest} must expose api and runtime.`);
|
|
130
|
+
return loaded;
|
|
131
|
+
}
|
|
132
|
+
export { BACKEND_FEDERATION_CONTRACT_VERSION, BACKEND_FEDERATION_EFFECT_EXPOSE, BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_NODE_ADAPTER_VERSION, createBackendFederationLoadEntryPlugin, createBackendFederationRuntime, loadBackendFederatedEffectApi };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createSafeFailureResponse } from "../safe-failure.mjs";
|
|
2
|
+
import { createEffectOperationContext } from "./operation-context.mjs";
|
|
3
|
+
function normalizeEffectBffPrefix(prefix) {
|
|
4
|
+
if (!prefix || '/' === prefix) return '';
|
|
5
|
+
return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
|
|
6
|
+
}
|
|
7
|
+
function removeEffectBffPrefixFromPath(pathname, prefix) {
|
|
8
|
+
const normalized = normalizeEffectBffPrefix(prefix);
|
|
9
|
+
if (!normalized || pathname !== normalized && !pathname.startsWith(`${normalized}/`)) return pathname;
|
|
10
|
+
const sliced = pathname.slice(normalized.length);
|
|
11
|
+
return sliced.startsWith('/') ? sliced : `/${sliced}`;
|
|
12
|
+
}
|
|
13
|
+
function matchesEffectBffPrefix(pathname, prefix) {
|
|
14
|
+
const normalized = normalizeEffectBffPrefix(prefix);
|
|
15
|
+
return !normalized || pathname === normalized || pathname.startsWith(`${normalized}/`);
|
|
16
|
+
}
|
|
17
|
+
function createEffectBffMountedRequest(req, prefix) {
|
|
18
|
+
const url = new URL(req.url);
|
|
19
|
+
const nextPath = removeEffectBffPrefixFromPath(url.pathname, prefix);
|
|
20
|
+
if (nextPath !== url.pathname) {
|
|
21
|
+
url.pathname = nextPath;
|
|
22
|
+
return new Request(url, req);
|
|
23
|
+
}
|
|
24
|
+
return req;
|
|
25
|
+
}
|
|
26
|
+
function createEffectBffDispatchContext(originalRequest, mountedRequest, options) {
|
|
27
|
+
const path = options.path ?? new URL(originalRequest.url).pathname;
|
|
28
|
+
const method = options.method ?? originalRequest.method;
|
|
29
|
+
const env = options.env ?? {};
|
|
30
|
+
return {
|
|
31
|
+
request: mountedRequest,
|
|
32
|
+
env,
|
|
33
|
+
path,
|
|
34
|
+
method,
|
|
35
|
+
operationContext: createEffectOperationContext({
|
|
36
|
+
request: mountedRequest,
|
|
37
|
+
env,
|
|
38
|
+
path,
|
|
39
|
+
method
|
|
40
|
+
})
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
async function dispatchEffectBffRequestWithContext(handler, request, options) {
|
|
44
|
+
const requestPath = new URL(request.url).pathname;
|
|
45
|
+
if (!matchesEffectBffPrefix(requestPath, options.prefix)) return new Response('', {
|
|
46
|
+
status: 404
|
|
47
|
+
});
|
|
48
|
+
const mountedRequest = createEffectBffMountedRequest(request, options.prefix);
|
|
49
|
+
const effectContext = createEffectBffDispatchContext(request, mountedRequest, options);
|
|
50
|
+
try {
|
|
51
|
+
const response = await options.runWithEffectContext(effectContext, ()=>handler(mountedRequest, effectContext));
|
|
52
|
+
if (!(response instanceof Response)) throw new Error('[BFF][Effect] Effect handler must return Response instance.');
|
|
53
|
+
return new Response(response.body, response);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (error instanceof Response) return new Response(error.body, error);
|
|
56
|
+
if (options.onError) {
|
|
57
|
+
const errorResponse = await options.onError(error, effectContext);
|
|
58
|
+
if (errorResponse instanceof Response) return errorResponse;
|
|
59
|
+
}
|
|
60
|
+
return createSafeFailureResponse(error);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export { createEffectBffDispatchContext, createEffectBffMountedRequest, dispatchEffectBffRequestWithContext, matchesEffectBffPrefix, normalizeEffectBffPrefix, removeEffectBffPrefixFromPath };
|