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