@bleedingdev/modern-js-plugin-bff 3.2.0-ultramodern.12 → 3.2.0-ultramodern.121

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 (80) hide show
  1. package/dist/cjs/cli.js +9 -5
  2. package/dist/cjs/constants.js +13 -9
  3. package/dist/cjs/index.js +9 -5
  4. package/dist/cjs/loader.js +32 -5
  5. package/dist/cjs/runtime/create-request/index.js +9 -5
  6. package/dist/cjs/runtime/data-platform/index.js +50 -26
  7. package/dist/cjs/runtime/effect/adapter.js +99 -93
  8. package/dist/cjs/runtime/effect/context.js +19 -7
  9. package/dist/cjs/runtime/effect/edge.js +169 -0
  10. package/dist/cjs/runtime/effect/endpoint-contracts.js +130 -0
  11. package/dist/cjs/runtime/effect/handler.js +642 -0
  12. package/dist/cjs/runtime/effect/index.js +30 -547
  13. package/dist/cjs/runtime/effect/module.js +151 -0
  14. package/dist/cjs/runtime/effect/operation-context.js +103 -0
  15. package/dist/cjs/runtime/effect-client/index.js +22 -6
  16. package/dist/cjs/runtime/effect-client/runtime.js +266 -0
  17. package/dist/cjs/runtime/hono/adapter.js +30 -14
  18. package/dist/cjs/runtime/hono/index.js +9 -5
  19. package/dist/cjs/runtime/hono/operators.js +9 -5
  20. package/dist/cjs/runtime/safe-failure.js +83 -0
  21. package/dist/cjs/server.js +9 -5
  22. package/dist/cjs/utils/clientGenerator.js +13 -9
  23. package/dist/cjs/utils/createHonoRoutes.js +9 -5
  24. package/dist/cjs/utils/crossProjectApiPlugin.js +9 -5
  25. package/dist/cjs/utils/crossProjectServerPolicy.js +104 -0
  26. package/dist/cjs/utils/effectClientGenerator.js +116 -488
  27. package/dist/cjs/utils/pluginGenerator.js +9 -5
  28. package/dist/cjs/utils/runtimeGenerator.js +9 -5
  29. package/dist/esm/loader.mjs +23 -0
  30. package/dist/esm/runtime/data-platform/index.mjs +33 -22
  31. package/dist/esm/runtime/effect/adapter.mjs +91 -89
  32. package/dist/esm/runtime/effect/context.mjs +3 -1
  33. package/dist/esm/runtime/effect/edge.mjs +83 -0
  34. package/dist/esm/runtime/effect/endpoint-contracts.mjs +68 -0
  35. package/dist/esm/runtime/effect/handler.mjs +470 -0
  36. package/dist/esm/runtime/effect/index.mjs +3 -437
  37. package/dist/esm/runtime/effect/module.mjs +113 -0
  38. package/dist/esm/runtime/effect/operation-context.mjs +65 -0
  39. package/dist/esm/runtime/effect-client/index.mjs +14 -2
  40. package/dist/esm/runtime/effect-client/runtime.mjs +228 -0
  41. package/dist/esm/runtime/hono/adapter.mjs +21 -9
  42. package/dist/esm/runtime/safe-failure.mjs +45 -0
  43. package/dist/esm/utils/clientGenerator.mjs +5 -5
  44. package/dist/esm/utils/crossProjectServerPolicy.mjs +50 -0
  45. package/dist/esm/utils/effectClientGenerator.mjs +105 -484
  46. package/dist/esm-node/loader.mjs +23 -0
  47. package/dist/esm-node/runtime/data-platform/index.mjs +33 -22
  48. package/dist/esm-node/runtime/effect/adapter.mjs +91 -89
  49. package/dist/esm-node/runtime/effect/context.mjs +3 -1
  50. package/dist/esm-node/runtime/effect/edge.mjs +84 -0
  51. package/dist/esm-node/runtime/effect/endpoint-contracts.mjs +69 -0
  52. package/dist/esm-node/runtime/effect/handler.mjs +471 -0
  53. package/dist/esm-node/runtime/effect/index.mjs +3 -437
  54. package/dist/esm-node/runtime/effect/module.mjs +114 -0
  55. package/dist/esm-node/runtime/effect/operation-context.mjs +66 -0
  56. package/dist/esm-node/runtime/effect-client/index.mjs +14 -2
  57. package/dist/esm-node/runtime/effect-client/runtime.mjs +229 -0
  58. package/dist/esm-node/runtime/hono/adapter.mjs +21 -9
  59. package/dist/esm-node/runtime/safe-failure.mjs +46 -0
  60. package/dist/esm-node/utils/clientGenerator.mjs +5 -5
  61. package/dist/esm-node/utils/crossProjectServerPolicy.mjs +52 -0
  62. package/dist/esm-node/utils/effectClientGenerator.mjs +105 -484
  63. package/dist/types/runtime/create-request/index.d.ts +1 -0
  64. package/dist/types/runtime/data-platform/index.d.ts +4 -0
  65. package/dist/types/runtime/effect/adapter.d.ts +25 -0
  66. package/dist/types/runtime/effect/context.d.ts +3 -6
  67. package/dist/types/runtime/effect/edge.d.ts +25 -0
  68. package/dist/types/runtime/effect/endpoint-contracts.d.ts +62 -0
  69. package/dist/types/runtime/effect/handler.d.ts +203 -0
  70. package/dist/types/runtime/effect/index.d.ts +2 -170
  71. package/dist/types/runtime/effect/module.d.ts +48 -0
  72. package/dist/types/runtime/effect/operation-context.d.ts +10 -0
  73. package/dist/types/runtime/effect-client/index.d.ts +6 -1
  74. package/dist/types/runtime/effect-client/runtime.d.ts +71 -0
  75. package/dist/types/runtime/hono/adapter.d.ts +3 -0
  76. package/dist/types/runtime/safe-failure.d.ts +1 -0
  77. package/dist/types/utils/createHonoRoutes.d.ts +3 -3
  78. package/dist/types/utils/crossProjectServerPolicy.d.ts +35 -0
  79. package/dist/types/utils/effectClientGenerator.d.ts +16 -2
  80. package/package.json +41 -20
@@ -1,438 +1,4 @@
1
- import * as __rspack_external_effect_Layer_16f7a8fc from "effect/Layer";
2
- import { HttpRouter, HttpServerResponse, HttpTraceContext } from "effect/unstable/http";
3
- import { HttpApiBuilder, OpenApi } from "effect/unstable/httpapi";
4
- import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
5
- import { DEFAULT_DATA_BATCH_ENDPOINT, DEFAULT_DATA_BATCH_HEADER, DEFAULT_DATA_ENVELOPE_HEADER, decodeRequestEnvelopeHeader, validateRequestEnvelope, validateSelectionPlan } from "../data-platform/index.mjs";
6
1
  import * as __rspack_external__effect_opentelemetry_8bbbb5af from "@effect/opentelemetry";
7
- import * as __rspack_external_effect_Config_29be8a92 from "effect/Config";
8
- import * as __rspack_external_effect_Effect_194ac36c from "effect/Effect";
9
- import * as __rspack_external_effect_Option_4d691636 from "effect/Option";
10
- import * as __rspack_external_effect_Schema_f8472650 from "effect/Schema";
11
- export * from "effect/unstable/http";
12
- export * from "effect/unstable/httpapi";
13
- export * from "effect/unstable/rpc";
14
- function normalizeOpenApiPath(pathname) {
15
- if (!pathname.startsWith('/')) return `/${pathname}`;
16
- return pathname;
17
- }
18
- function getOpenApiOptions(openapi) {
19
- if (!openapi || 'object' != typeof openapi) return;
20
- if (!openapi.path) return;
21
- return {
22
- path: normalizeOpenApiPath(openapi.path)
23
- };
24
- }
25
- function normalizeRpcPath(pathname) {
26
- if (!pathname || '/' === pathname) return '/rpc';
27
- if (!pathname.startsWith('/')) return `/${pathname}`;
28
- return pathname;
29
- }
30
- function normalizeBatchPath(pathname) {
31
- if (!pathname || '/' === pathname) return DEFAULT_DATA_BATCH_ENDPOINT;
32
- if (!pathname.startsWith('/')) return `/${pathname}`;
33
- return pathname;
34
- }
35
- function isPlainObject(value) {
36
- return 'object' == typeof value && null !== value && !Array.isArray(value);
37
- }
38
- function toTextLength(value) {
39
- if ("u" > typeof TextEncoder) return new TextEncoder().encode(value).length;
40
- if ("u" > typeof Buffer) return Buffer.byteLength(value);
41
- return value.length;
42
- }
43
- function toHeaderRecord(headers) {
44
- const record = {};
45
- headers.forEach((value, key)=>{
46
- record[key] = value;
47
- });
48
- return record;
49
- }
50
- function normalizeItemMethod(method) {
51
- return (method || 'GET').toUpperCase();
52
- }
53
- function normalizeBatchAllowedMethods(allowedMethods) {
54
- const source = Array.isArray(allowedMethods) && allowedMethods.length > 0 ? allowedMethods : [
55
- 'GET'
56
- ];
57
- return new Set(source.map((method)=>method.toUpperCase()));
58
- }
59
- function isBatchRequestPayload(value) {
60
- return isPlainObject(value) && 1 === value.protocolVersion && 'string' == typeof value.batchId && 'number' == typeof value.sentAt && Array.isArray(value.items);
61
- }
62
- function createBatchValidationResponse(message, status = 400) {
63
- return new Response(JSON.stringify({
64
- message
65
- }), {
66
- status,
67
- headers: {
68
- 'content-type': 'application/json; charset=utf-8'
69
- }
70
- });
71
- }
72
- function toBatchItemError(id, status, message) {
73
- return {
74
- id,
75
- status,
76
- headers: {
77
- 'content-type': 'application/json; charset=utf-8'
78
- },
79
- body: JSON.stringify({
80
- message
81
- })
82
- };
83
- }
84
- function promiseWithTimeout(effect, timeoutMs) {
85
- if (timeoutMs <= 0) return effect;
86
- return new Promise((resolve, reject)=>{
87
- const timer = setTimeout(()=>{
88
- reject(new Error(`Batch item timeout after ${String(timeoutMs)}ms`));
89
- }, timeoutMs);
90
- effect.then((value)=>{
91
- clearTimeout(timer);
92
- resolve(value);
93
- }, (error)=>{
94
- clearTimeout(timer);
95
- reject(error);
96
- });
97
- });
98
- }
99
- async function mapWithConcurrency(items, concurrency, mapper) {
100
- if (0 === items.length) return [];
101
- const normalizedConcurrency = Math.max(1, concurrency);
102
- const output = new Array(items.length);
103
- let index = 0;
104
- const workers = Array.from({
105
- length: Math.min(normalizedConcurrency, items.length)
106
- }, async ()=>{
107
- while(true){
108
- const currentIndex = index;
109
- index += 1;
110
- if (currentIndex >= items.length) return;
111
- output[currentIndex] = await mapper(items[currentIndex], currentIndex);
112
- }
113
- });
114
- await Promise.all(workers);
115
- return output;
116
- }
117
- function getRequestPathname(request) {
118
- try {
119
- return new URL(request.url).pathname;
120
- } catch {
121
- return new URL(request.url, 'http://localhost').pathname;
122
- }
123
- }
124
- function normalizeMountPrefix(prefix) {
125
- if (!prefix || '/' === prefix) return '';
126
- return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
127
- }
128
- function getMountedPrefixFromContext(request, context) {
129
- if (!isPlainObject(context) || 'string' != typeof context.path) return '';
130
- const contextPath = normalizeMountPrefix(context.path);
131
- const requestPath = normalizeMountPrefix(getRequestPathname(request));
132
- if (!contextPath || !requestPath || contextPath === requestPath || !contextPath.endsWith(requestPath)) return '';
133
- return normalizeMountPrefix(contextPath.slice(0, contextPath.length - requestPath.length));
134
- }
135
- function removeMountedPrefixFromBatchPath(pathWithQuery, prefix) {
136
- const normalizedPrefix = normalizeMountPrefix(prefix);
137
- if (!normalizedPrefix) return pathWithQuery;
138
- const [pathname, ...queryParts] = pathWithQuery.split('?');
139
- if (!pathname) return pathWithQuery;
140
- let nextPathname = pathname;
141
- if (pathname === normalizedPrefix) nextPathname = '/';
142
- else if (pathname.startsWith(`${normalizedPrefix}/`)) {
143
- const sliced = pathname.slice(normalizedPrefix.length);
144
- nextPathname = sliced.startsWith('/') ? sliced : `/${sliced}`;
145
- }
146
- if (0 === queryParts.length) return nextPathname;
147
- return `${nextPathname}?${queryParts.join('?')}`;
148
- }
149
- function getRequestOrigin(request) {
150
- try {
151
- return new URL(request.url).origin;
152
- } catch {
153
- return new URL(request.url, 'http://localhost').origin;
154
- }
155
- }
156
- function getExpectedEnvelopeOrigin(request) {
157
- const origin = request.headers.get('origin');
158
- if (origin && 'null' !== origin) return origin;
159
- return getRequestOrigin(request);
160
- }
161
- function isRpcRequest(request, rpcPath) {
162
- const pathname = getRequestPathname(request);
163
- return pathname === rpcPath || pathname.startsWith(`${rpcPath}/`);
164
- }
165
- function getRpcSerializationLayer(serialization) {
166
- switch(serialization){
167
- case 'ndjson':
168
- return RpcSerialization.layerNdjson;
169
- case 'jsonRpc':
170
- return RpcSerialization.layerJsonRpc();
171
- case 'ndJsonRpc':
172
- return RpcSerialization.layerNdJsonRpc();
173
- case 'msgPack':
174
- return RpcSerialization.layerMsgPack;
175
- default:
176
- return RpcSerialization.layerJsonRpc();
177
- }
178
- }
179
- function createRpcApiHandler(options) {
180
- const rpcPath = normalizeRpcPath(options.path);
181
- const rpcLayer = __rspack_external_effect_Layer_16f7a8fc.provide(RpcServer.layerHttp({
182
- group: options.group,
183
- path: rpcPath,
184
- protocol: 'http',
185
- disableTracing: options.disableTracing,
186
- spanPrefix: options.spanPrefix,
187
- spanAttributes: options.spanAttributes
188
- }), __rspack_external_effect_Layer_16f7a8fc.mergeAll(options.layer, getRpcSerializationLayer(options.serialization)));
189
- return HttpRouter.toWebHandler(rpcLayer);
190
- }
191
- function createOpenApiLayer(api, openapi) {
192
- const openApiOptions = getOpenApiOptions(openapi);
193
- if (!openApiOptions) return null;
194
- return HttpRouter.add('GET', openApiOptions.path, HttpServerResponse.jsonUnsafe(OpenApi.fromApi(api)));
195
- }
196
- function createInvalidEnvelopeResponse(message, errors) {
197
- return new Response(JSON.stringify({
198
- message,
199
- ...errors && errors.length > 0 ? {
200
- errors
201
- } : {}
202
- }), {
203
- status: 400,
204
- headers: {
205
- 'content-type': 'application/json; charset=utf-8'
206
- }
207
- });
208
- }
209
- function validateDataPlatformRequestEnvelope(request, options) {
210
- const isEnabled = options?.enabled ?? true;
211
- if (!isEnabled) return null;
212
- const envelopeHeader = options?.envelopeHeader || DEFAULT_DATA_ENVELOPE_HEADER;
213
- const encodedEnvelope = request.headers.get(envelopeHeader);
214
- if (!encodedEnvelope) {
215
- if (options?.requireEnvelope) return createInvalidEnvelopeResponse(`Missing required data envelope header: ${envelopeHeader}`);
216
- return null;
217
- }
218
- const envelope = decodeRequestEnvelopeHeader(encodedEnvelope);
219
- if (!envelope) return createInvalidEnvelopeResponse(`Invalid data envelope header format: ${envelopeHeader}`);
220
- const validation = validateRequestEnvelope(envelope, {
221
- expectedProtocolVersion: 1,
222
- expectedNamespace: options?.expectedNamespace,
223
- expectedOrigin: options?.validateOrigin === false ? void 0 : getExpectedEnvelopeOrigin(request),
224
- requireTraceContext: options?.requireTraceContext
225
- });
226
- if (!validation.ok) return createInvalidEnvelopeResponse('Invalid data envelope', validation.errors);
227
- if (envelope.selectionPlan) {
228
- const selectionValidation = validateSelectionPlan(envelope.selectionPlan, {
229
- maxDepth: options?.selection?.maxDepth,
230
- maxFields: options?.selection?.maxFields,
231
- allowedLeafPaths: options?.selection?.allowedLeafPaths
232
- });
233
- if (!selectionValidation.ok) return createInvalidEnvelopeResponse('Invalid data envelope selection plan', selectionValidation.errors);
234
- }
235
- return null;
236
- }
237
- function mergeDataPlatformOptions(base, override) {
238
- if (!base && !override) return;
239
- const baseSelection = base?.selection;
240
- const overrideSelection = override?.selection;
241
- const baseBatch = base?.batch;
242
- const overrideBatch = override?.batch;
243
- return {
244
- ...base,
245
- ...override,
246
- selection: baseSelection || overrideSelection ? {
247
- ...baseSelection,
248
- ...overrideSelection
249
- } : void 0,
250
- batch: baseBatch || overrideBatch ? {
251
- ...baseBatch,
252
- ...overrideBatch
253
- } : void 0
254
- };
255
- }
256
- function defineEffectBff(definition) {
257
- const createHandler = (options)=>{
258
- const rpcDefinition = definition.rpc;
259
- let mergedRpcOptions = rpcDefinition;
260
- if (rpcDefinition && options?.rpc) mergedRpcOptions = {
261
- ...rpcDefinition,
262
- ...options.rpc
263
- };
264
- return createHttpApiHandler({
265
- api: definition.api,
266
- layer: definition.layer,
267
- openapi: options?.openapi,
268
- rpc: mergedRpcOptions,
269
- dataPlatform: mergeDataPlatformOptions(definition.dataPlatform, options?.dataPlatform)
270
- });
271
- };
272
- const client = void 0;
273
- return {
274
- ...definition,
275
- createHandler,
276
- client
277
- };
278
- }
279
- function defineEffectRpcBff(definition) {
280
- const createHandler = (options)=>createRpcApiHandler({
281
- ...definition,
282
- ...options
283
- });
284
- return {
285
- ...definition,
286
- createHandler
287
- };
288
- }
289
- function createHttpApiHandler(options) {
290
- const apiLayer = options.layer;
291
- const openApiLayer = createOpenApiLayer(options.api, options.openapi);
292
- const mergedLayer = openApiLayer ? __rspack_external_effect_Layer_16f7a8fc.mergeAll(apiLayer, openApiLayer) : apiLayer;
293
- const httpApiHandler = HttpRouter.toWebHandler(mergedLayer);
294
- const dataPlatformBatchOptions = options.dataPlatform?.batch;
295
- const batchEnabled = dataPlatformBatchOptions?.enabled !== false;
296
- const batchPath = normalizeBatchPath(dataPlatformBatchOptions?.endpoint);
297
- const batchMaxSize = Math.max(1, dataPlatformBatchOptions?.maxBatchSize ?? 16);
298
- const batchMaxBytes = Math.max(1024, dataPlatformBatchOptions?.maxBatchBytes ?? 65536);
299
- const batchConcurrency = Math.max(1, dataPlatformBatchOptions?.maxConcurrency ?? 4);
300
- const batchItemTimeoutMs = Math.max(0, dataPlatformBatchOptions?.requestTimeoutMs ?? 10000);
301
- const batchAllowedMethods = normalizeBatchAllowedMethods(dataPlatformBatchOptions?.allowedMethods);
302
- const envelopeHeader = options.dataPlatform?.envelopeHeader || DEFAULT_DATA_ENVELOPE_HEADER;
303
- const normalizedEnvelopeHeader = envelopeHeader.toLowerCase();
304
- const withDataPlatformValidation = async (request, context)=>{
305
- const validationError = validateDataPlatformRequestEnvelope(request, options.dataPlatform);
306
- if (validationError) return validationError;
307
- return httpApiHandler.handler(request, context);
308
- };
309
- const handleBatchRequest = async (request, context)=>{
310
- const mountedPrefix = getMountedPrefixFromContext(request, context);
311
- const method = normalizeItemMethod(request.method);
312
- if ('POST' !== method) return createBatchValidationResponse('Batch endpoint only supports POST requests', 405);
313
- const contentType = request.headers.get('content-type') || '';
314
- if (!contentType.includes('application/json')) return createBatchValidationResponse('Batch endpoint requires application/json content-type', 415);
315
- const payloadText = await request.text();
316
- if (toTextLength(payloadText) > batchMaxBytes) return createBatchValidationResponse(`Batch payload exceeds max size (${String(batchMaxBytes)} bytes)`, 413);
317
- let payload;
318
- try {
319
- payload = JSON.parse(payloadText);
320
- } catch {
321
- return createBatchValidationResponse('Invalid batch payload JSON');
322
- }
323
- if (!isBatchRequestPayload(payload)) return createBatchValidationResponse('Invalid batch payload shape');
324
- if (0 === payload.items.length) return createBatchValidationResponse('Batch payload items cannot be empty');
325
- if (payload.items.length > batchMaxSize) return createBatchValidationResponse(`Batch item count exceeds max size (${String(batchMaxSize)})`, 413);
326
- const responseItems = await mapWithConcurrency(payload.items, batchConcurrency, async (rawItem, index)=>{
327
- const fallbackId = `item_${String(index)}`;
328
- const itemId = isPlainObject(rawItem) && 'string' == typeof rawItem.id ? rawItem.id : fallbackId;
329
- if (!isPlainObject(rawItem)) return toBatchItemError(itemId, 400, 'Invalid batch item; expected object');
330
- if ('string' != typeof rawItem.path || 0 === rawItem.path.length) return toBatchItemError(itemId, 400, 'Invalid batch item path');
331
- if (!rawItem.path.startsWith('/')) return toBatchItemError(itemId, 400, 'Batch item path must start with "/"');
332
- const normalizedItemPath = removeMountedPrefixFromBatchPath(rawItem.path, mountedPrefix);
333
- const itemPathname = normalizedItemPath.split('?')[0] || normalizedItemPath;
334
- if (itemPathname === batchPath || itemPathname.startsWith(`${batchPath}/`)) return toBatchItemError(itemId, 400, 'Batch item path cannot target batch endpoint');
335
- const itemMethod = normalizeItemMethod('string' == typeof rawItem.method ? rawItem.method : void 0);
336
- if (!batchAllowedMethods.has(itemMethod)) return toBatchItemError(itemId, 405, `Batch item method ${itemMethod} is not allowed`);
337
- if (void 0 !== rawItem.body && null !== rawItem.body && 'string' != typeof rawItem.body) return toBatchItemError(itemId, 400, 'Batch item body must be a string when provided');
338
- if (('GET' === itemMethod || 'HEAD' === itemMethod) && 'string' == typeof rawItem.body) return toBatchItemError(itemId, 400, `${itemMethod} batch item cannot include body`);
339
- const normalizedHeaders = {};
340
- if (void 0 !== rawItem.headers) {
341
- if (!isPlainObject(rawItem.headers)) return toBatchItemError(itemId, 400, 'Batch item headers must be an object');
342
- for (const [key, value] of Object.entries(rawItem.headers)){
343
- if ('string' != typeof value) return toBatchItemError(itemId, 400, `Invalid header "${key}" for batch item`);
344
- normalizedHeaders[key.toLowerCase()] = value;
345
- }
346
- }
347
- if (!normalizedHeaders.traceparent) {
348
- const encodedEnvelope = normalizedHeaders[normalizedEnvelopeHeader];
349
- if ('string' == typeof encodedEnvelope) {
350
- const envelope = decodeRequestEnvelopeHeader(encodedEnvelope);
351
- if (envelope?.traceparent) normalizedHeaders.traceparent = envelope.traceparent;
352
- }
353
- }
354
- if (!normalizedHeaders.traceparent) {
355
- const requestTraceparent = request.headers.get('traceparent');
356
- if (requestTraceparent) normalizedHeaders.traceparent = requestTraceparent;
357
- }
358
- const targetUrl = new URL(normalizedItemPath, request.url);
359
- const requestHeaders = new Headers(normalizedHeaders);
360
- const body = 'GET' === itemMethod || 'HEAD' === itemMethod ? void 0 : rawItem.body;
361
- if (void 0 === body) requestHeaders.delete('content-type');
362
- const itemRequest = new Request(targetUrl.toString(), {
363
- method: itemMethod,
364
- headers: requestHeaders,
365
- body
366
- });
367
- try {
368
- const itemResponse = await promiseWithTimeout(withDataPlatformValidation(itemRequest, context), batchItemTimeoutMs);
369
- if (!(itemResponse instanceof Response)) return toBatchItemError(itemId, 500, 'Invalid response returned by batch item handler');
370
- const bodyText = await itemResponse.text();
371
- const responseItem = {
372
- id: itemId,
373
- status: itemResponse.status,
374
- headers: toHeaderRecord(itemResponse.headers),
375
- ...bodyText ? {
376
- body: bodyText
377
- } : {}
378
- };
379
- return responseItem;
380
- } catch (error) {
381
- if (error instanceof Response) {
382
- const bodyText = await error.text();
383
- return {
384
- id: itemId,
385
- status: error.status,
386
- headers: toHeaderRecord(error.headers),
387
- ...bodyText ? {
388
- body: bodyText
389
- } : {}
390
- };
391
- }
392
- const message = error instanceof Error ? error.message : String(error);
393
- return toBatchItemError(itemId, 500, message);
394
- }
395
- });
396
- const responsePayload = {
397
- protocolVersion: 1,
398
- batchId: payload.batchId,
399
- receivedAt: Date.now(),
400
- items: responseItems
401
- };
402
- return new Response(JSON.stringify(responsePayload), {
403
- status: 200,
404
- headers: {
405
- 'content-type': 'application/json; charset=utf-8',
406
- [DEFAULT_DATA_BATCH_HEADER]: '1',
407
- 'x-modernjs-data-batch-id': payload.batchId
408
- }
409
- });
410
- };
411
- const handleHttpApiRequest = async (request, context)=>{
412
- const pathname = getRequestPathname(request);
413
- if (batchEnabled && pathname === batchPath) return handleBatchRequest(request, context);
414
- return withDataPlatformValidation(request, context);
415
- };
416
- if (!options.rpc) return {
417
- handler: handleHttpApiRequest,
418
- dispose: async ()=>{
419
- await httpApiHandler.dispose();
420
- }
421
- };
422
- const rpcPath = normalizeRpcPath(options.rpc.path);
423
- const rpcHandler = createRpcApiHandler(options.rpc);
424
- return {
425
- handler: async (request, context)=>{
426
- if (isRpcRequest(request, rpcPath)) return rpcHandler.handler(request, context);
427
- return handleHttpApiRequest(request);
428
- },
429
- dispose: async ()=>{
430
- await Promise.all([
431
- httpApiHandler.dispose(),
432
- rpcHandler.dispose()
433
- ]);
434
- }
435
- };
436
- }
437
- export { useEffectContext } from "./context.mjs";
438
- export { HttpApiBuilder, HttpTraceContext, __rspack_external__effect_opentelemetry_8bbbb5af as OpenTelemetry, __rspack_external_effect_Config_29be8a92 as Config, __rspack_external_effect_Effect_194ac36c as Effect, __rspack_external_effect_Layer_16f7a8fc as Layer, __rspack_external_effect_Option_4d691636 as Option, __rspack_external_effect_Schema_f8472650 as Schema, createHttpApiHandler, defineEffectBff, defineEffectRpcBff };
2
+ export * from "./handler.mjs";
3
+ export { createEffectOperationContext, useEffectContext, useOperationContext } from "./context.mjs";
4
+ export { __rspack_external__effect_opentelemetry_8bbbb5af as OpenTelemetry };
@@ -0,0 +1,113 @@
1
+ import { HttpApi } from "effect/unstable/httpapi";
2
+ import { createHttpApiHandler, isValidatorAwareHandlerFactory } from "./handler.mjs";
3
+ 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
+ function isRequestHandler(value) {
11
+ return 'function' == typeof value;
12
+ }
13
+ function isEffectApiDefinition(module) {
14
+ return HttpApi.isHttpApi(module.api) && void 0 !== module.layer;
15
+ }
16
+ function isEffectServiceContext(context) {
17
+ return 'object' == typeof context && null !== context && 'mapUnsafe' in context;
18
+ }
19
+ const emptyEffectServiceContext = __rspack_external_effect_Context_f1289ca3.empty();
20
+ function callEffectBffRequestHandler(handler, request, context) {
21
+ return void 0 === context ? handler(request) : handler(request, context);
22
+ }
23
+ function createLoadedHandler(webHandler, appliesRequestValidator) {
24
+ return {
25
+ handler: (request, context)=>callEffectBffRequestHandler(webHandler.handler, request, context),
26
+ dispose: webHandler.dispose,
27
+ ...appliesRequestValidator ? {
28
+ appliesRequestValidator: true
29
+ } : {}
30
+ };
31
+ }
32
+ function createLoadedHttpApiHandler(webHandler) {
33
+ return {
34
+ handler: (request, context)=>{
35
+ const effectContext = isEffectServiceContext(context) ? context : emptyEffectServiceContext;
36
+ return webHandler.handler(request, effectContext);
37
+ },
38
+ dispose: webHandler.dispose,
39
+ appliesRequestValidator: true
40
+ };
41
+ }
42
+ function resolveNormalizedEffectBffModuleHandler(normalizedModule, options = {}) {
43
+ if (isRequestHandler(normalizedModule.handler)) return {
44
+ handler: normalizedModule.handler
45
+ };
46
+ const entry = normalizedModule.default;
47
+ if (isRequestHandler(entry)) return {
48
+ handler: entry
49
+ };
50
+ if (isRecord(entry)) normalizedModule = {
51
+ ...normalizedModule,
52
+ ...entry
53
+ };
54
+ if (isRecord(entry) && 'handler' in entry) {
55
+ const maybeHandler = entry.handler;
56
+ if (isRequestHandler(maybeHandler)) normalizedModule = {
57
+ ...normalizedModule,
58
+ handler: maybeHandler
59
+ };
60
+ }
61
+ if (isRequestHandler(normalizedModule.handler)) return {
62
+ handler: normalizedModule.handler
63
+ };
64
+ if ('function' == typeof normalizedModule.createHandler) {
65
+ const factory = normalizedModule.createHandler;
66
+ const validatorAware = isValidatorAwareHandlerFactory(factory);
67
+ if (!validatorAware && void 0 !== options.validateRequest) options.onWarning?.('[BFF][Effect] Custom createHandler export detected: it cannot be verified to apply validateRequest (cross-project policy), so the policy is enforced by the adapter middleware on the outer request. Batched calls will be denied at the batch POST (it carries no per-operation contract); export defineEffectBff(...) to get per-batch-item enforcement.');
68
+ const webHandler = factory({
69
+ openapi: options.openapi,
70
+ dataPlatform: options.dataPlatform,
71
+ validateRequest: options.validateRequest
72
+ });
73
+ return createLoadedHandler(webHandler, validatorAware);
74
+ }
75
+ if (isEffectApiDefinition(normalizedModule)) {
76
+ options.onWarning?.('[BFF][Effect] Detected { api, layer } export without createHandler. Prefer `defineEffectBff(...)` from @modern-js/plugin-bff/server to avoid module instance mismatch.');
77
+ const webHandler = createHttpApiHandler({
78
+ api: normalizedModule.api,
79
+ layer: normalizedModule.layer,
80
+ openapi: options.openapi,
81
+ dataPlatform: options.dataPlatform,
82
+ validateRequest: options.validateRequest
83
+ });
84
+ return createLoadedHttpApiHandler(webHandler);
85
+ }
86
+ return null;
87
+ }
88
+ function resolveEffectBffModuleHandler(mod, options = {}) {
89
+ let normalizedModule = mod;
90
+ const mergeRuntimeExports = (value)=>{
91
+ if (!isRecord(value) || !includesRuntimeExports(value)) return;
92
+ normalizedModule = {
93
+ ...normalizedModule,
94
+ ...value
95
+ };
96
+ };
97
+ if (isRequestHandler(normalizedModule.handler)) return Promise.resolve({
98
+ handler: normalizedModule.handler
99
+ });
100
+ const entry = normalizedModule.default;
101
+ if (isRequestHandler(entry)) return Promise.resolve({
102
+ handler: entry
103
+ });
104
+ if ('function' == typeof entry && 0 === entry.length) return Promise.resolve(entry()).then((out)=>{
105
+ if (isRequestHandler(out)) return {
106
+ handler: out
107
+ };
108
+ mergeRuntimeExports(out);
109
+ return resolveNormalizedEffectBffModuleHandler(normalizedModule, options);
110
+ });
111
+ return Promise.resolve(resolveNormalizedEffectBffModuleHandler(normalizedModule, options));
112
+ }
113
+ export { resolveEffectBffModuleHandler };
@@ -0,0 +1,65 @@
1
+ import { BFF_LOCALE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER, BFF_TRACEPARENT_HEADER, parseTraceparent } from "@modern-js/create-request";
2
+ const readHeader = (headers, header)=>{
3
+ const value = headers.get(header);
4
+ return value && value.length > 0 ? value : void 0;
5
+ };
6
+ const copyStringField = (target, details, key)=>{
7
+ const value = details[key];
8
+ if ('string' == typeof value && value.length > 0) target[key] = value;
9
+ };
10
+ const readOperationContextDetails = (request)=>{
11
+ const rawDetails = readHeader(request.headers, BFF_OPERATION_CONTEXT_DETAIL_HEADER);
12
+ if (!rawDetails) return {};
13
+ try {
14
+ const parsed = JSON.parse(rawDetails);
15
+ if (!parsed || 'object' != typeof parsed || Array.isArray(parsed)) return {};
16
+ const details = parsed;
17
+ const safeDetails = {};
18
+ copyStringField(safeDetails, details, 'requestId');
19
+ copyStringField(safeDetails, details, 'operationId');
20
+ copyStringField(safeDetails, details, 'schemaHash');
21
+ copyStringField(safeDetails, details, 'traceparent');
22
+ copyStringField(safeDetails, details, 'traceId');
23
+ copyStringField(safeDetails, details, 'spanId');
24
+ if ('number' == typeof details.operationVersion) safeDetails.operationVersion = details.operationVersion;
25
+ return safeDetails;
26
+ } catch {
27
+ return {};
28
+ }
29
+ };
30
+ const createEffectOperationContext = ({ request, path, method })=>{
31
+ const details = readOperationContextDetails(request);
32
+ const servicePath = new URL(request.url).pathname;
33
+ const traceparent = readHeader(request.headers, BFF_TRACEPARENT_HEADER) || details.traceparent;
34
+ const parsedTraceparent = details.traceId && details.spanId ? {
35
+ traceId: details.traceId,
36
+ spanId: details.spanId
37
+ } : parseTraceparent(traceparent);
38
+ const locale = readHeader(request.headers, BFF_LOCALE_HEADER);
39
+ const headerOperationId = readHeader(request.headers, BFF_OPERATION_CONTEXT_HEADER);
40
+ return {
41
+ ...details,
42
+ ...headerOperationId || details.operationId ? {
43
+ operationId: headerOperationId || details.operationId
44
+ } : {},
45
+ routePath: servicePath,
46
+ method: (method || request.method || 'GET').toUpperCase(),
47
+ source: 'effect-adapter',
48
+ ...path && path !== servicePath ? {
49
+ attributes: {
50
+ mountedPath: path
51
+ }
52
+ } : {},
53
+ ...locale ? {
54
+ locale
55
+ } : {},
56
+ ...traceparent ? {
57
+ traceparent
58
+ } : {},
59
+ ...parsedTraceparent ? {
60
+ traceId: parsedTraceparent.traceId,
61
+ spanId: parsedTraceparent.spanId
62
+ } : {}
63
+ };
64
+ };
65
+ export { createEffectOperationContext };
@@ -1,6 +1,7 @@
1
+ import { createRequestContextHeaders } from "@modern-js/create-request";
1
2
  import * as __rspack_external_effect_Effect_194ac36c from "effect/Effect";
2
3
  import * as __rspack_external_effect_Layer_16f7a8fc from "effect/Layer";
3
- import { FetchHttpClient } from "effect/unstable/http";
4
+ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
4
5
  import { HttpApi, HttpApiClient, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/unstable/httpapi";
5
6
  import { Rpc, RpcClient, RpcGroup, RpcSchema, RpcSerialization } from "effect/unstable/rpc";
6
7
  import * as __rspack_external_effect_Schema_f8472650 from "effect/Schema";
@@ -47,8 +48,19 @@ function getRpcSerializationLayer(serialization) {
47
48
  }
48
49
  }
49
50
  function makeEffectHttpApiClient(api, options) {
51
+ const requestContextHeaders = createRequestContextHeaders(options?.requestContext);
52
+ const transformClient = (client)=>{
53
+ const contextClient = 0 === Object.keys(requestContextHeaders).length ? client : client.pipe(HttpClient.mapRequest((request)=>{
54
+ let nextRequest = request;
55
+ for (const [header, value] of Object.entries(requestContextHeaders))if (void 0 === nextRequest.headers[header.toLowerCase()]) nextRequest = HttpClientRequest.setHeader(nextRequest, header, value);
56
+ return nextRequest;
57
+ }));
58
+ return 'function' == typeof options?.transformClient ? options.transformClient(contextClient) : contextClient;
59
+ };
50
60
  return HttpApiClient.make(api, {
51
- baseUrl: options?.baseUrl
61
+ baseUrl: options?.baseUrl,
62
+ transformClient,
63
+ transformResponse: options?.transformResponse
52
64
  }).pipe(__rspack_external_effect_Effect_194ac36c.provide(FetchHttpClient.layer));
53
65
  }
54
66
  function makeEffectRpcClient(group, options) {