@bleedingdev/modern-js-plugin-bff 3.2.0-ultramodern.9 → 3.2.0-ultramodern.91

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 (43) hide show
  1. package/dist/cjs/loader.js +23 -0
  2. package/dist/cjs/runtime/data-platform/index.js +39 -8
  3. package/dist/cjs/runtime/effect/adapter.js +15 -82
  4. package/dist/cjs/runtime/effect/context.js +10 -2
  5. package/dist/cjs/runtime/effect/edge.js +169 -0
  6. package/dist/cjs/runtime/effect/handler.js +598 -0
  7. package/dist/cjs/runtime/effect/index.js +16 -545
  8. package/dist/cjs/runtime/effect/module.js +115 -0
  9. package/dist/cjs/runtime/effect/operation-context.js +111 -0
  10. package/dist/cjs/runtime/effect-client/index.js +13 -1
  11. package/dist/cjs/utils/effectClientGenerator.js +17 -0
  12. package/dist/esm/loader.mjs +23 -0
  13. package/dist/esm/runtime/data-platform/index.mjs +31 -9
  14. package/dist/esm/runtime/effect/adapter.mjs +16 -83
  15. package/dist/esm/runtime/effect/context.mjs +3 -1
  16. package/dist/esm/runtime/effect/edge.mjs +90 -0
  17. package/dist/esm/runtime/effect/handler.mjs +437 -0
  18. package/dist/esm/runtime/effect/index.mjs +2 -438
  19. package/dist/esm/runtime/effect/module.mjs +81 -0
  20. package/dist/esm/runtime/effect/operation-context.mjs +77 -0
  21. package/dist/esm/runtime/effect-client/index.mjs +14 -2
  22. package/dist/esm/utils/effectClientGenerator.mjs +17 -0
  23. package/dist/esm-node/loader.mjs +23 -0
  24. package/dist/esm-node/runtime/data-platform/index.mjs +31 -9
  25. package/dist/esm-node/runtime/effect/adapter.mjs +16 -83
  26. package/dist/esm-node/runtime/effect/context.mjs +3 -1
  27. package/dist/esm-node/runtime/effect/edge.mjs +91 -0
  28. package/dist/esm-node/runtime/effect/handler.mjs +438 -0
  29. package/dist/esm-node/runtime/effect/index.mjs +2 -438
  30. package/dist/esm-node/runtime/effect/module.mjs +82 -0
  31. package/dist/esm-node/runtime/effect/operation-context.mjs +78 -0
  32. package/dist/esm-node/runtime/effect-client/index.mjs +14 -2
  33. package/dist/esm-node/utils/effectClientGenerator.mjs +17 -0
  34. package/dist/types/runtime/create-request/index.d.ts +1 -0
  35. package/dist/types/runtime/data-platform/index.d.ts +4 -0
  36. package/dist/types/runtime/effect/context.d.ts +3 -6
  37. package/dist/types/runtime/effect/edge.d.ts +25 -0
  38. package/dist/types/runtime/effect/handler.d.ts +170 -0
  39. package/dist/types/runtime/effect/index.d.ts +2 -171
  40. package/dist/types/runtime/effect/module.d.ts +28 -0
  41. package/dist/types/runtime/effect/operation-context.d.ts +10 -0
  42. package/dist/types/runtime/effect-client/index.d.ts +6 -1
  43. package/package.json +27 -18
@@ -1,438 +1,2 @@
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
- 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 };
1
+ export * from "./handler.mjs";
2
+ export { createEffectOperationContext, useEffectContext, useOperationContext } from "./context.mjs";
@@ -0,0 +1,81 @@
1
+ import { HttpApi } from "effect/unstable/httpapi";
2
+ import { createHttpApiHandler } from "./handler.mjs";
3
+ function isRecord(value) {
4
+ return 'object' == typeof value && null !== value;
5
+ }
6
+ function includesRuntimeExports(value) {
7
+ return 'api' in value || 'layer' in value || 'createHandler' in value || 'handler' in value;
8
+ }
9
+ function isRequestHandler(value) {
10
+ return 'function' == typeof value;
11
+ }
12
+ function isEffectApiDefinition(module) {
13
+ return HttpApi.isHttpApi(module.api) && void 0 !== module.layer;
14
+ }
15
+ async function resolveEffectBffModuleHandler(mod, options = {}) {
16
+ let normalizedModule = mod;
17
+ const mergeRuntimeExports = (value)=>{
18
+ if (!isRecord(value) || !includesRuntimeExports(value)) return;
19
+ normalizedModule = {
20
+ ...normalizedModule,
21
+ ...value
22
+ };
23
+ };
24
+ if (isRequestHandler(normalizedModule.handler)) return {
25
+ handler: normalizedModule.handler
26
+ };
27
+ const entry = normalizedModule.default;
28
+ if (isRequestHandler(entry)) return {
29
+ handler: entry
30
+ };
31
+ if ('function' == typeof entry && 0 === entry.length) {
32
+ const out = await entry();
33
+ if (isRequestHandler(out)) return {
34
+ handler: out
35
+ };
36
+ mergeRuntimeExports(out);
37
+ }
38
+ if (isRecord(entry)) normalizedModule = {
39
+ ...normalizedModule,
40
+ ...entry
41
+ };
42
+ if (isRecord(entry) && 'handler' in entry) {
43
+ const maybeHandler = entry.handler;
44
+ if (isRequestHandler(maybeHandler)) normalizedModule = {
45
+ ...normalizedModule,
46
+ handler: maybeHandler
47
+ };
48
+ }
49
+ if (isRequestHandler(normalizedModule.handler)) return {
50
+ handler: normalizedModule.handler
51
+ };
52
+ if ('function' == typeof normalizedModule.createHandler) {
53
+ const webHandler = normalizedModule.createHandler({
54
+ openapi: options.openapi,
55
+ dataPlatform: options.dataPlatform
56
+ });
57
+ return {
58
+ handler: async (request, context)=>webHandler.handler(request, context),
59
+ dispose: async ()=>{
60
+ await webHandler.dispose();
61
+ }
62
+ };
63
+ }
64
+ if (isEffectApiDefinition(normalizedModule)) {
65
+ options.onWarning?.('[BFF][Effect] Detected { api, layer } export without createHandler. Prefer `defineEffectBff(...)` from @modern-js/plugin-bff/server to avoid module instance mismatch.');
66
+ const webHandler = createHttpApiHandler({
67
+ api: normalizedModule.api,
68
+ layer: normalizedModule.layer,
69
+ openapi: options.openapi,
70
+ dataPlatform: options.dataPlatform
71
+ });
72
+ return {
73
+ handler: async (request, context)=>webHandler.handler(request, context),
74
+ dispose: async ()=>{
75
+ await webHandler.dispose();
76
+ }
77
+ };
78
+ }
79
+ return null;
80
+ }
81
+ export { resolveEffectBffModuleHandler };
@@ -0,0 +1,77 @@
1
+ import { BFF_LOCALE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER, BFF_TRACEPARENT_HEADER } from "@modern-js/create-request";
2
+ const TRACEPARENT_REGEX = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/i;
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 parseTraceparent = (traceparent)=>{
12
+ if (!traceparent) return;
13
+ const match = traceparent.trim().match(TRACEPARENT_REGEX);
14
+ if (!match) return;
15
+ const [, traceId, spanId] = match;
16
+ if (!traceId || !spanId) return;
17
+ return {
18
+ traceId: traceId.toLowerCase(),
19
+ spanId: spanId.toLowerCase()
20
+ };
21
+ };
22
+ const readOperationContextDetails = (request)=>{
23
+ const rawDetails = readHeader(request.headers, BFF_OPERATION_CONTEXT_DETAIL_HEADER);
24
+ if (!rawDetails) return {};
25
+ try {
26
+ const parsed = JSON.parse(rawDetails);
27
+ if (!parsed || 'object' != typeof parsed || Array.isArray(parsed)) return {};
28
+ const details = parsed;
29
+ const safeDetails = {};
30
+ copyStringField(safeDetails, details, 'requestId');
31
+ copyStringField(safeDetails, details, 'operationId');
32
+ copyStringField(safeDetails, details, 'schemaHash');
33
+ copyStringField(safeDetails, details, 'traceparent');
34
+ copyStringField(safeDetails, details, 'traceId');
35
+ copyStringField(safeDetails, details, 'spanId');
36
+ if ('number' == typeof details.operationVersion) safeDetails.operationVersion = details.operationVersion;
37
+ return safeDetails;
38
+ } catch {
39
+ return {};
40
+ }
41
+ };
42
+ const createEffectOperationContext = ({ request, path, method })=>{
43
+ const details = readOperationContextDetails(request);
44
+ const servicePath = new URL(request.url).pathname;
45
+ const traceparent = readHeader(request.headers, BFF_TRACEPARENT_HEADER) || details.traceparent;
46
+ const parsedTraceparent = details.traceId && details.spanId ? {
47
+ traceId: details.traceId,
48
+ spanId: details.spanId
49
+ } : parseTraceparent(traceparent);
50
+ const locale = readHeader(request.headers, BFF_LOCALE_HEADER);
51
+ const headerOperationId = readHeader(request.headers, BFF_OPERATION_CONTEXT_HEADER);
52
+ return {
53
+ ...details,
54
+ ...headerOperationId || details.operationId ? {
55
+ operationId: headerOperationId || details.operationId
56
+ } : {},
57
+ routePath: servicePath,
58
+ method: (method || request.method || 'GET').toUpperCase(),
59
+ source: 'effect-adapter',
60
+ ...path && path !== servicePath ? {
61
+ attributes: {
62
+ mountedPath: path
63
+ }
64
+ } : {},
65
+ ...locale ? {
66
+ locale
67
+ } : {},
68
+ ...traceparent ? {
69
+ traceparent
70
+ } : {},
71
+ ...parsedTraceparent ? {
72
+ traceId: parsedTraceparent.traceId,
73
+ spanId: parsedTraceparent.spanId
74
+ } : {}
75
+ };
76
+ };
77
+ 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 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) {
@@ -581,9 +581,26 @@ export type EffectOperationManifest = Record<
581
581
  string,
582
582
  Record<string, EffectOperationDescriptor>
583
583
  >;
584
+ export type EffectOperationContext = {
585
+ requestId?: string;
586
+ operationId?: string;
587
+ routePath?: string;
588
+ method?: string;
589
+ schemaHash?: string;
590
+ operationVersion?: number;
591
+ locale?: string;
592
+ traceparent?: string;
593
+ traceId?: string;
594
+ spanId?: string;
595
+ source?: string;
596
+ scope?: Record<string, unknown>;
597
+ sessionClaims?: Record<string, unknown>;
598
+ attributes?: Record<string, unknown>;
599
+ };
584
600
  export type EffectRequestContext = {
585
601
  headers?: Record<string, string>;
586
602
  locale?: string;
603
+ operationContext?: EffectOperationContext;
587
604
  traceparent?: string;
588
605
  traceId?: string;
589
606
  spanId?: string;