@bleedingdev/modern-js-plugin-bff 3.2.0-ultramodern.0

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 (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -0
  3. package/cli.js +1 -0
  4. package/dist/cjs/cli.js +294 -0
  5. package/dist/cjs/constants.js +48 -0
  6. package/dist/cjs/index.js +58 -0
  7. package/dist/cjs/loader.js +106 -0
  8. package/dist/cjs/runtime/create-request/index.js +48 -0
  9. package/dist/cjs/runtime/data-platform/index.js +693 -0
  10. package/dist/cjs/runtime/effect/adapter.js +311 -0
  11. package/dist/cjs/runtime/effect/context.js +48 -0
  12. package/dist/cjs/runtime/effect/index.js +608 -0
  13. package/dist/cjs/runtime/effect-client/index.js +178 -0
  14. package/dist/cjs/runtime/hono/adapter.js +168 -0
  15. package/dist/cjs/runtime/hono/index.js +65 -0
  16. package/dist/cjs/runtime/hono/operators.js +68 -0
  17. package/dist/cjs/server.js +179 -0
  18. package/dist/cjs/utils/clientGenerator.js +342 -0
  19. package/dist/cjs/utils/createHonoRoutes.js +138 -0
  20. package/dist/cjs/utils/crossProjectApiPlugin.js +118 -0
  21. package/dist/cjs/utils/effectClientGenerator.js +673 -0
  22. package/dist/cjs/utils/pluginGenerator.js +73 -0
  23. package/dist/cjs/utils/runtimeGenerator.js +133 -0
  24. package/dist/esm/cli.mjs +245 -0
  25. package/dist/esm/constants.mjs +11 -0
  26. package/dist/esm/index.mjs +1 -0
  27. package/dist/esm/loader.mjs +62 -0
  28. package/dist/esm/runtime/create-request/index.mjs +1 -0
  29. package/dist/esm/runtime/data-platform/index.mjs +599 -0
  30. package/dist/esm/runtime/effect/adapter.mjs +267 -0
  31. package/dist/esm/runtime/effect/context.mjs +11 -0
  32. package/dist/esm/runtime/effect/index.mjs +438 -0
  33. package/dist/esm/runtime/effect-client/index.mjs +90 -0
  34. package/dist/esm/runtime/hono/adapter.mjs +124 -0
  35. package/dist/esm/runtime/hono/index.mjs +2 -0
  36. package/dist/esm/runtime/hono/operators.mjs +31 -0
  37. package/dist/esm/server.mjs +135 -0
  38. package/dist/esm/utils/clientGenerator.mjs +293 -0
  39. package/dist/esm/utils/createHonoRoutes.mjs +92 -0
  40. package/dist/esm/utils/crossProjectApiPlugin.mjs +54 -0
  41. package/dist/esm/utils/effectClientGenerator.mjs +623 -0
  42. package/dist/esm/utils/pluginGenerator.mjs +29 -0
  43. package/dist/esm/utils/runtimeGenerator.mjs +89 -0
  44. package/dist/esm-node/cli.mjs +249 -0
  45. package/dist/esm-node/constants.mjs +12 -0
  46. package/dist/esm-node/index.mjs +2 -0
  47. package/dist/esm-node/loader.mjs +64 -0
  48. package/dist/esm-node/runtime/create-request/index.mjs +2 -0
  49. package/dist/esm-node/runtime/data-platform/index.mjs +600 -0
  50. package/dist/esm-node/runtime/effect/adapter.mjs +269 -0
  51. package/dist/esm-node/runtime/effect/context.mjs +12 -0
  52. package/dist/esm-node/runtime/effect/index.mjs +439 -0
  53. package/dist/esm-node/runtime/effect-client/index.mjs +91 -0
  54. package/dist/esm-node/runtime/hono/adapter.mjs +125 -0
  55. package/dist/esm-node/runtime/hono/index.mjs +3 -0
  56. package/dist/esm-node/runtime/hono/operators.mjs +32 -0
  57. package/dist/esm-node/server.mjs +136 -0
  58. package/dist/esm-node/utils/clientGenerator.mjs +294 -0
  59. package/dist/esm-node/utils/createHonoRoutes.mjs +93 -0
  60. package/dist/esm-node/utils/crossProjectApiPlugin.mjs +55 -0
  61. package/dist/esm-node/utils/effectClientGenerator.mjs +625 -0
  62. package/dist/esm-node/utils/pluginGenerator.mjs +33 -0
  63. package/dist/esm-node/utils/runtimeGenerator.mjs +91 -0
  64. package/dist/types/cli.d.ts +3 -0
  65. package/dist/types/constants.d.ts +2 -0
  66. package/dist/types/index.d.ts +1 -0
  67. package/dist/types/loader.d.ts +27 -0
  68. package/dist/types/runtime/create-request/index.d.ts +2 -0
  69. package/dist/types/runtime/data-platform/index.d.ts +187 -0
  70. package/dist/types/runtime/effect/adapter.d.ts +22 -0
  71. package/dist/types/runtime/effect/context.d.ts +8 -0
  72. package/dist/types/runtime/effect/index.d.ts +171 -0
  73. package/dist/types/runtime/effect-client/index.d.ts +47 -0
  74. package/dist/types/runtime/hono/adapter.d.ts +19 -0
  75. package/dist/types/runtime/hono/index.d.ts +2 -0
  76. package/dist/types/runtime/hono/operators.d.ts +10 -0
  77. package/dist/types/server.d.ts +3 -0
  78. package/dist/types/utils/clientGenerator.d.ts +37 -0
  79. package/dist/types/utils/createHonoRoutes.d.ts +10 -0
  80. package/dist/types/utils/crossProjectApiPlugin.d.ts +9 -0
  81. package/dist/types/utils/effectClientGenerator.d.ts +27 -0
  82. package/dist/types/utils/pluginGenerator.d.ts +9 -0
  83. package/dist/types/utils/runtimeGenerator.d.ts +7 -0
  84. package/docs/data-platform-architecture.md +61 -0
  85. package/package.json +172 -0
  86. package/rslib.config.mts +4 -0
  87. package/rstest.config.mts +10 -0
  88. package/server.js +1 -0
@@ -0,0 +1,623 @@
1
+ import { DEFAULT_OPERATION_VERSION, createOperationEntries, createOperationSchemaHash } from "@modern-js/bff-core";
2
+ import { compatibleRequire, findExists, fs, logger } from "@modern-js/utils";
3
+ import path from "path";
4
+ const JS_OR_TS_EXTS = [
5
+ '.js',
6
+ '.jsx',
7
+ '.ts',
8
+ '.tsx',
9
+ '.mjs',
10
+ '.mts',
11
+ '.cjs',
12
+ '.cts'
13
+ ];
14
+ const DEFAULT_REQUEST_CREATOR = '@modern-js/plugin-bff/client';
15
+ const DEFAULT_DATA_PLATFORM_IMPORT = '@modern-js/plugin-bff/data-platform';
16
+ let httpApiRuntimePromise;
17
+ function isRecord(value) {
18
+ return 'object' == typeof value && null !== value;
19
+ }
20
+ function ensureLeadingSlash(pathname) {
21
+ return pathname.startsWith('/') ? pathname : `/${pathname}`;
22
+ }
23
+ function normalizePrefix(prefix) {
24
+ if ('/' === prefix) return '';
25
+ return ensureLeadingSlash(prefix || '/api');
26
+ }
27
+ function isAbsoluteUrl(value) {
28
+ try {
29
+ new URL(value);
30
+ return true;
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+ function resolveBatchEndpoint(prefix, endpoint) {
36
+ const value = endpoint || '/_data/batch';
37
+ if (isAbsoluteUrl(value)) return value;
38
+ const normalizedPrefix = normalizePrefix(prefix);
39
+ const normalizedEndpoint = ensureLeadingSlash(value);
40
+ if (!normalizedPrefix) return normalizedEndpoint;
41
+ if (normalizedEndpoint === normalizedPrefix || normalizedEndpoint.startsWith(`${normalizedPrefix}/`)) return normalizedEndpoint;
42
+ return `${normalizedPrefix}${'/' === normalizedEndpoint ? '' : normalizedEndpoint}`;
43
+ }
44
+ function getRoutePath(prefix, endpointPath) {
45
+ const normalizedPrefix = normalizePrefix(prefix);
46
+ const normalizedEndpointPath = ensureLeadingSlash(endpointPath);
47
+ const finalEndpointPath = '/' === normalizedEndpointPath ? '' : endpointPath;
48
+ if (!normalizedPrefix && !finalEndpointPath) return '/';
49
+ return `${normalizedPrefix}${finalEndpointPath || ''}`;
50
+ }
51
+ function toSafeIdentifier(name) {
52
+ const sanitized = name.replace(/[^a-zA-Z0-9_$]/g, '_');
53
+ if (!sanitized) return '_';
54
+ if (/^[0-9]/.test(sanitized)) return `_${sanitized}`;
55
+ return sanitized;
56
+ }
57
+ function getPackageName(appDir) {
58
+ try {
59
+ const packageJsonPath = path.resolve(appDir, './package.json');
60
+ const packageJson = fs.readJSONSync(packageJsonPath);
61
+ return packageJson.name;
62
+ } catch {
63
+ return;
64
+ }
65
+ }
66
+ async function getHttpApiRuntime() {
67
+ if (!httpApiRuntimePromise) httpApiRuntimePromise = (async ()=>{
68
+ let mod;
69
+ try {
70
+ mod = await compatibleRequire('effect/unstable/httpapi', false);
71
+ } catch (error) {
72
+ const message = error instanceof Error ? error.message : String(error);
73
+ if (!message.includes("Cannot find module 'effect/unstable/httpapi'")) throw error;
74
+ const effectPackageJson = require.resolve('effect/package.json');
75
+ const effectHttpApiRuntimePath = path.join(path.dirname(effectPackageJson), 'dist', 'unstable', 'httpapi', 'index.js');
76
+ mod = await compatibleRequire(effectHttpApiRuntimePath, false);
77
+ }
78
+ if (isRecord(mod) && isRecord(mod.HttpApi)) {
79
+ const maybeHttpApi = mod.HttpApi;
80
+ if ('function' == typeof maybeHttpApi.isHttpApi && 'function' == typeof maybeHttpApi.reflect) return maybeHttpApi;
81
+ }
82
+ throw new Error('[BFF][Effect] Unable to resolve HttpApi runtime from effect/unstable/httpapi.');
83
+ })();
84
+ return httpApiRuntimePromise;
85
+ }
86
+ function resolveApiId(api) {
87
+ const fallback = 'EffectHttpApi';
88
+ const maybeApi = api;
89
+ if ('identifier' in maybeApi && 'string' == typeof maybeApi.identifier && maybeApi.identifier) return maybeApi.identifier;
90
+ return fallback;
91
+ }
92
+ function collectEffectEndpoints(httpApiRuntime, api, prefix) {
93
+ const endpoints = [];
94
+ const apiId = resolveApiId(api);
95
+ httpApiRuntime.reflect(api, {
96
+ onGroup: ()=>{},
97
+ onEndpoint: ({ group, endpoint })=>{
98
+ endpoints.push({
99
+ apiId,
100
+ groupName: String(group.identifier),
101
+ endpointName: String(endpoint.name),
102
+ method: String(endpoint.method).toUpperCase(),
103
+ routePath: getRoutePath(prefix, String(endpoint.path))
104
+ });
105
+ }
106
+ });
107
+ return endpoints.sort((a, b)=>{
108
+ if (a.groupName === b.groupName) return a.endpointName.localeCompare(b.endpointName);
109
+ return a.groupName.localeCompare(b.groupName);
110
+ });
111
+ }
112
+ async function loadEffectApi(resourcePath) {
113
+ const httpApiRuntime = await getHttpApiRuntime();
114
+ const mod = await compatibleRequire(resourcePath, false);
115
+ if (isRecord(mod) && httpApiRuntime.isHttpApi(mod.api)) return mod.api;
116
+ if (isRecord(mod) && isRecord(mod.default) && httpApiRuntime.isHttpApi(mod.default.api)) return mod.default.api;
117
+ if (isRecord(mod) && 'function' == typeof mod.default && 0 === mod.default.length) {
118
+ const output = await mod.default();
119
+ if (isRecord(output) && httpApiRuntime.isHttpApi(output.api)) return output.api;
120
+ }
121
+ return null;
122
+ }
123
+ function renderEffectClientCode(endpoints, options) {
124
+ const senderDeclarations = [];
125
+ const operationDeclarations = [];
126
+ const callerDeclarations = [];
127
+ const groupedCallers = {};
128
+ const groupedOperations = {};
129
+ const requestCreator = options.requestCreator || DEFAULT_REQUEST_CREATOR;
130
+ const dataPlatformImport = DEFAULT_DATA_PLATFORM_IMPORT;
131
+ const httpMethodDecider = options.httpMethodDecider || 'functionName';
132
+ const portCode = 'server' === options.target ? `process.env.PORT || ${String(options.port)}` : String(options.port);
133
+ const packageName = getPackageName(options.appDir);
134
+ const dataPlatformAppNamespace = packageName || 'unknown-app';
135
+ const requestId = 'bundle' === options.target ? packageName || process.env.npm_package_name : void 0;
136
+ const normalizedRequestId = requestId || 'default';
137
+ const operationVersion = 'number' == typeof DEFAULT_OPERATION_VERSION ? DEFAULT_OPERATION_VERSION : 1;
138
+ const schemaHash = createOperationSchemaHash(createOperationEntries(endpoints.map((endpoint)=>({
139
+ name: endpoint.endpointName,
140
+ httpMethod: endpoint.method,
141
+ routePath: endpoint.routePath
142
+ }))), normalizedRequestId);
143
+ const batchConfig = options.dataPlatformBatch;
144
+ const batchEndpoint = resolveBatchEndpoint(options.prefix, batchConfig?.endpoint);
145
+ const batchConfigCode = JSON.stringify({
146
+ enabled: batchConfig?.enabled ?? true,
147
+ endpoint: batchEndpoint,
148
+ flushIntervalMs: batchConfig?.flushIntervalMs ?? 8,
149
+ maxBatchSize: batchConfig?.maxBatchSize ?? 16,
150
+ maxBatchBytes: batchConfig?.maxBatchBytes ?? 65536,
151
+ requestTimeoutMs: batchConfig?.requestTimeoutMs ?? 10000,
152
+ allowedMethods: batchConfig?.allowedMethods && batchConfig.allowedMethods.length > 0 ? batchConfig.allowedMethods : [
153
+ 'GET'
154
+ ]
155
+ });
156
+ endpoints.forEach((endpoint, index)=>{
157
+ const senderVar = `__sender_${toSafeIdentifier(endpoint.groupName)}_${toSafeIdentifier(endpoint.endpointName)}_${index}`;
158
+ const callVar = `__call_${toSafeIdentifier(endpoint.groupName)}_${toSafeIdentifier(endpoint.endpointName)}_${index}`;
159
+ const operationVar = `__operation_${toSafeIdentifier(endpoint.groupName)}_${toSafeIdentifier(endpoint.endpointName)}_${index}`;
160
+ const operationId = `${endpoint.method}:${endpoint.routePath}`;
161
+ const operationContextCode = JSON.stringify({
162
+ operationId,
163
+ routePath: endpoint.routePath,
164
+ method: endpoint.method,
165
+ schemaHash,
166
+ operationVersion
167
+ });
168
+ const createRequestOptions = `{
169
+ path: ${JSON.stringify(endpoint.routePath)},
170
+ method: ${JSON.stringify(endpoint.method)},
171
+ port: ${portCode},
172
+ operationContext: ${operationContextCode},
173
+ httpMethodDecider: ${JSON.stringify(httpMethodDecider)}${requestId ? `, requestId: ${JSON.stringify(requestId)}` : ''}
174
+ }`.replace(/\n\s*/g, '');
175
+ senderDeclarations.push(`const ${senderVar} = createRequest(${createRequestOptions});`);
176
+ operationDeclarations.push(`const ${operationVar} = ${JSON.stringify({
177
+ appNamespace: dataPlatformAppNamespace,
178
+ apiId: endpoint.apiId,
179
+ group: endpoint.groupName,
180
+ endpoint: endpoint.endpointName,
181
+ operationId,
182
+ routePath: endpoint.routePath,
183
+ method: endpoint.method,
184
+ operationVersion,
185
+ schemaHash,
186
+ version: operationVersion
187
+ })};`);
188
+ callerDeclarations.push(`const ${callVar} = (request = {}) => ${senderVar}(__prepareEffectRequest(${JSON.stringify(endpoint.method)}, ${JSON.stringify(endpoint.routePath)}, ${operationVar}, request));`);
189
+ groupedCallers[endpoint.groupName] ??= [];
190
+ groupedCallers[endpoint.groupName].push({
191
+ endpointName: endpoint.endpointName,
192
+ callVar
193
+ });
194
+ groupedOperations[endpoint.groupName] ??= [];
195
+ groupedOperations[endpoint.groupName].push({
196
+ endpointName: endpoint.endpointName,
197
+ operationVar
198
+ });
199
+ });
200
+ const groupObjectEntries = Object.entries(groupedCallers).map(([groupName, groupCallers])=>{
201
+ const endpointEntries = groupCallers.map((caller)=>`${JSON.stringify(caller.endpointName)}: ${caller.callVar}`).join(', ');
202
+ return `${JSON.stringify(groupName)}: { ${endpointEntries} }`;
203
+ });
204
+ const clientObject = groupObjectEntries.length ? `{
205
+ ${groupObjectEntries.join(',\n ')}
206
+ }` : '{}';
207
+ const operationManifestEntries = Object.entries(groupedOperations).map(([groupName, groupOperations])=>{
208
+ const endpointEntries = groupOperations.map((operation)=>`${JSON.stringify(operation.endpointName)}: ${operation.operationVar}`).join(', ');
209
+ return `${JSON.stringify(groupName)}: { ${endpointEntries} }`;
210
+ });
211
+ const operationManifestObject = operationManifestEntries.length ? `{
212
+ ${operationManifestEntries.join(',\n ')}
213
+ }` : '{}';
214
+ return `import * as __requestRuntime from ${JSON.stringify(requestCreator)};
215
+ import {
216
+ createDataBatchTransport,
217
+ DEFAULT_DATA_BATCH_HEADER,
218
+ DEFAULT_DATA_ENVELOPE_HEADER,
219
+ createRequestEnvelope,
220
+ encodeRequestEnvelopeHeader,
221
+ } from ${JSON.stringify(dataPlatformImport)};
222
+
223
+ const createRequest = __requestRuntime.createRequest;
224
+ const __configureRequest =
225
+ typeof __requestRuntime.configure === 'function'
226
+ ? __requestRuntime.configure
227
+ : undefined;
228
+ const __createRequestContextHeaders =
229
+ typeof __requestRuntime.createRequestContextHeaders === 'function'
230
+ ? __requestRuntime.createRequestContextHeaders
231
+ : undefined;
232
+
233
+ const __METHODS_WITHOUT_BODY = new Set(['GET', 'DELETE', 'HEAD', 'OPTIONS']);
234
+ const __DATA_REQUEST_MODES = new Set(['cache-first', 'stale-while-revalidate', 'network-only']);
235
+ const __DATA_MUTATION_MODES = new Set(['optimistic', 'pessimistic', 'fire-and-forget']);
236
+ const __DEFAULT_APP_NAMESPACE = ${JSON.stringify(dataPlatformAppNamespace)};
237
+ const __DEFAULT_ORIGIN = 'http://localhost:${String(options.port)}';
238
+ const __DEFAULT_BATCH_CONFIG = ${batchConfigCode};
239
+ const __REQUEST_ID = ${requestId ? JSON.stringify(requestId) : 'undefined'};
240
+ const __RUNTIME_FETCH =
241
+ typeof fetch === 'function' ? fetch.bind(globalThis) : undefined;
242
+
243
+ if (__REQUEST_ID && __configureRequest) {
244
+ const __configurePayload = {
245
+ requestId: __REQUEST_ID,
246
+ requireEnvelope: true,
247
+ identityBinding: {
248
+ enabled: true,
249
+ strict: true,
250
+ },
251
+ operationContract: {
252
+ enabled: true,
253
+ strict: true,
254
+ requireSchemaHash: true,
255
+ requireOperationVersion: true,
256
+ },
257
+ setDomain: () => {
258
+ if (
259
+ typeof window !== 'undefined' &&
260
+ window.location &&
261
+ typeof window.location.origin === 'string' &&
262
+ window.location.origin
263
+ ) {
264
+ return window.location.origin;
265
+ }
266
+
267
+ if (
268
+ typeof globalThis !== 'undefined' &&
269
+ globalThis.location &&
270
+ typeof globalThis.location.origin === 'string' &&
271
+ globalThis.location.origin
272
+ ) {
273
+ return globalThis.location.origin;
274
+ }
275
+
276
+ return __DEFAULT_ORIGIN;
277
+ },
278
+ };
279
+
280
+ if (__DEFAULT_BATCH_CONFIG.enabled !== false && __RUNTIME_FETCH) {
281
+ __configurePayload.request = createDataBatchTransport({
282
+ fetch: __RUNTIME_FETCH,
283
+ endpoint: __DEFAULT_BATCH_CONFIG.endpoint,
284
+ flushIntervalMs: __DEFAULT_BATCH_CONFIG.flushIntervalMs,
285
+ maxBatchSize: __DEFAULT_BATCH_CONFIG.maxBatchSize,
286
+ maxBatchBytes: __DEFAULT_BATCH_CONFIG.maxBatchBytes,
287
+ requestTimeoutMs: __DEFAULT_BATCH_CONFIG.requestTimeoutMs,
288
+ allowedMethods: __DEFAULT_BATCH_CONFIG.allowedMethods,
289
+ });
290
+ }
291
+
292
+ __configureRequest(__configurePayload);
293
+ }
294
+
295
+ const __isRecord = value => typeof value === 'object' && value !== null;
296
+ const __stringOrUndefined = value =>
297
+ typeof value === 'string' && value.length > 0 ? value : undefined;
298
+ const __isDataRequestMode = value =>
299
+ typeof value === 'string' && __DATA_REQUEST_MODES.has(value);
300
+ const __isDataMutationMode = value =>
301
+ typeof value === 'string' && __DATA_MUTATION_MODES.has(value);
302
+ const __normalizeOrigin = value => {
303
+ if (typeof value !== 'string' || value.length === 0) {
304
+ return undefined;
305
+ }
306
+ try {
307
+ return new URL(value).origin;
308
+ } catch {
309
+ return undefined;
310
+ }
311
+ };
312
+
313
+ const __normalizeRequest = (method, request = {}) => {
314
+ if (!__isRecord(request)) {
315
+ return {};
316
+ }
317
+
318
+ const payload = { ...request };
319
+
320
+ if (__isRecord(request.path) && !__isRecord(payload.params)) {
321
+ payload.params = request.path;
322
+ }
323
+
324
+ if (__isRecord(request.urlParams) && !__isRecord(payload.query)) {
325
+ payload.query = request.urlParams;
326
+ }
327
+
328
+ if (__isRecord(request.headers) && !__isRecord(payload.headers)) {
329
+ payload.headers = request.headers;
330
+ }
331
+
332
+ if ('payload' in request && request.payload !== undefined) {
333
+ if (request.payload instanceof FormData && !('formData' in payload)) {
334
+ payload.formData = request.payload;
335
+ } else if (__METHODS_WITHOUT_BODY.has(method)) {
336
+ if (__isRecord(request.payload)) {
337
+ payload.query = __isRecord(payload.query)
338
+ ? { ...payload.query, ...request.payload }
339
+ : request.payload;
340
+ } else if (!('body' in payload)) {
341
+ payload.body = request.payload;
342
+ }
343
+ } else if (__isRecord(request.payload) && !('data' in payload)) {
344
+ payload.data = request.payload;
345
+ } else if (!('body' in payload)) {
346
+ payload.body = request.payload;
347
+ }
348
+ }
349
+
350
+ return payload;
351
+ };
352
+
353
+ const __resolveOrigin = () => {
354
+ if (
355
+ typeof window !== 'undefined' &&
356
+ window.location &&
357
+ typeof window.location.origin === 'string' &&
358
+ window.location.origin
359
+ ) {
360
+ return window.location.origin;
361
+ }
362
+
363
+ if (
364
+ typeof globalThis !== 'undefined' &&
365
+ globalThis.location &&
366
+ typeof globalThis.location.origin === 'string' &&
367
+ globalThis.location.origin
368
+ ) {
369
+ return globalThis.location.origin;
370
+ }
371
+
372
+ return __DEFAULT_ORIGIN;
373
+ };
374
+
375
+ const __resolveTargetOrigin = dataPlatform => {
376
+ const explicitTargetOrigin =
377
+ __stringOrUndefined(dataPlatform.targetOrigin) ||
378
+ __stringOrUndefined(dataPlatform.endpointOrigin);
379
+ if (explicitTargetOrigin) {
380
+ return explicitTargetOrigin;
381
+ }
382
+ return __DEFAULT_ORIGIN;
383
+ };
384
+
385
+ const __shouldAttachEnvelopeHeader = dataPlatform => {
386
+ if (dataPlatform.allowCrossOriginEnvelope === true) {
387
+ return true;
388
+ }
389
+ const currentOrigin = __normalizeOrigin(__resolveOrigin());
390
+ const targetOrigin = __normalizeOrigin(__resolveTargetOrigin(dataPlatform));
391
+ if (!currentOrigin || !targetOrigin) {
392
+ return true;
393
+ }
394
+ return currentOrigin === targetOrigin;
395
+ };
396
+
397
+ const __toEnvelopeInput = normalizedRequest => {
398
+ if (!__isRecord(normalizedRequest)) {
399
+ return {};
400
+ }
401
+
402
+ const payload = {};
403
+ if (__isRecord(normalizedRequest.params)) {
404
+ payload.path = normalizedRequest.params;
405
+ }
406
+ if (__isRecord(normalizedRequest.query)) {
407
+ payload.query = normalizedRequest.query;
408
+ }
409
+ if ('data' in normalizedRequest && normalizedRequest.data !== undefined) {
410
+ payload.data = normalizedRequest.data;
411
+ }
412
+ if ('body' in normalizedRequest && normalizedRequest.body !== undefined) {
413
+ payload.body = normalizedRequest.body;
414
+ }
415
+ if (
416
+ typeof FormData !== 'undefined' &&
417
+ normalizedRequest.formData instanceof FormData
418
+ ) {
419
+ payload.formData = Array.from(normalizedRequest.formData.entries()).map(
420
+ ([key, value]) => [key, String(value)],
421
+ );
422
+ }
423
+ if (
424
+ typeof URLSearchParams !== 'undefined' &&
425
+ normalizedRequest.formUrlencoded instanceof URLSearchParams
426
+ ) {
427
+ payload.formUrlencoded = normalizedRequest.formUrlencoded.toString();
428
+ }
429
+ return payload;
430
+ };
431
+
432
+ const createEffectRequestContext = requestContext => {
433
+ if (!__isRecord(requestContext)) {
434
+ return {};
435
+ }
436
+
437
+ const headers = __createRequestContextHeaders
438
+ ? __createRequestContextHeaders(requestContext)
439
+ : {};
440
+
441
+ return {
442
+ ...requestContext,
443
+ headers,
444
+ };
445
+ };
446
+
447
+ const __applyRequestContext = (normalizedRequest, request = {}) => {
448
+ if (!__isRecord(request) || !__isRecord(request.requestContext)) {
449
+ return normalizedRequest;
450
+ }
451
+
452
+ const requestContext = createEffectRequestContext(request.requestContext);
453
+ const requestHeaders = __isRecord(requestContext.headers)
454
+ ? requestContext.headers
455
+ : {};
456
+
457
+ if (Object.keys(requestHeaders).length === 0) {
458
+ return normalizedRequest;
459
+ }
460
+
461
+ return {
462
+ ...normalizedRequest,
463
+ headers: {
464
+ ...requestHeaders,
465
+ ...(__isRecord(normalizedRequest.headers) ? normalizedRequest.headers : {}),
466
+ },
467
+ };
468
+ };
469
+
470
+ const __prepareEffectRequest = (method, routePath, operation, request = {}) => {
471
+ const normalizedRequest = __applyRequestContext(
472
+ __normalizeRequest(method, request),
473
+ request,
474
+ );
475
+ const dataPlatform = __isRecord(request) && __isRecord(request.dataPlatform)
476
+ ? request.dataPlatform
477
+ : {};
478
+ const strictEnvelope =
479
+ dataPlatform.requireEnvelope === true || dataPlatform.strict === true;
480
+
481
+ if (!strictEnvelope && !__shouldAttachEnvelopeHeader(dataPlatform)) {
482
+ return normalizedRequest;
483
+ }
484
+
485
+ try {
486
+ const namespace =
487
+ __stringOrUndefined(dataPlatform.appNamespace) || __DEFAULT_APP_NAMESPACE;
488
+ const origin = __stringOrUndefined(dataPlatform.origin) || __resolveOrigin();
489
+ const envelope = createRequestEnvelope({
490
+ operation: {
491
+ ...operation,
492
+ appNamespace: namespace,
493
+ },
494
+ scope: {
495
+ appNamespace: namespace,
496
+ origin,
497
+ tenantId: __stringOrUndefined(dataPlatform.tenantId),
498
+ userId: __stringOrUndefined(dataPlatform.userId),
499
+ sessionId: __stringOrUndefined(dataPlatform.sessionId),
500
+ },
501
+ requestInput: {
502
+ method,
503
+ routePath,
504
+ payload: __toEnvelopeInput(normalizedRequest),
505
+ },
506
+ requestMode: __isDataRequestMode(dataPlatform.requestMode)
507
+ ? dataPlatform.requestMode
508
+ : undefined,
509
+ mutationMode: __isDataMutationMode(dataPlatform.mutationMode)
510
+ ? dataPlatform.mutationMode
511
+ : undefined,
512
+ selectionPlan: __isRecord(dataPlatform.selectionPlan)
513
+ ? dataPlatform.selectionPlan
514
+ : undefined,
515
+ traceContext: __isRecord(dataPlatform.traceContext)
516
+ ? dataPlatform.traceContext
517
+ : undefined,
518
+ requireTraceContext: dataPlatform.requireTraceContext === true,
519
+ });
520
+
521
+ const headerName =
522
+ __stringOrUndefined(dataPlatform.envelopeHeader) ||
523
+ DEFAULT_DATA_ENVELOPE_HEADER;
524
+ const headers = __isRecord(normalizedRequest.headers)
525
+ ? { ...normalizedRequest.headers }
526
+ : {};
527
+
528
+ if (dataPlatform.batch === false) {
529
+ headers[DEFAULT_DATA_BATCH_HEADER] = 'off';
530
+ }
531
+
532
+ headers[headerName] = encodeRequestEnvelopeHeader(envelope);
533
+
534
+ return {
535
+ ...normalizedRequest,
536
+ headers,
537
+ };
538
+ } catch (error) {
539
+ if (strictEnvelope) {
540
+ throw error;
541
+ }
542
+ return normalizedRequest;
543
+ }
544
+ };
545
+
546
+ ${senderDeclarations.join('\n')}
547
+ ${operationDeclarations.join('\n')}
548
+ ${callerDeclarations.join('\n')}
549
+
550
+ const client = ${clientObject};
551
+ const operationManifest = ${operationManifestObject};
552
+ const effectBffModule = {
553
+ client,
554
+ operationManifest,
555
+ createEffectRequestContext,
556
+ };
557
+
558
+ export { client, createEffectRequestContext, operationManifest };
559
+ export default effectBffModule;
560
+ `;
561
+ }
562
+ function renderEffectClientDeclaration() {
563
+ return `export type EffectClientOperation = (
564
+ request?: unknown,
565
+ ) => Promise<unknown>;
566
+ export type EffectClientGroup = Record<string, EffectClientOperation>;
567
+ export type EffectClient = Record<string, EffectClientGroup>;
568
+ export type EffectOperationDescriptor = {
569
+ appNamespace: string;
570
+ apiId: string;
571
+ group: string;
572
+ endpoint: string;
573
+ operationId: string;
574
+ routePath: string;
575
+ method: string;
576
+ operationVersion: number;
577
+ schemaHash: string;
578
+ version: number;
579
+ };
580
+ export type EffectOperationManifest = Record<
581
+ string,
582
+ Record<string, EffectOperationDescriptor>
583
+ >;
584
+ export type EffectRequestContext = {
585
+ headers?: Record<string, string>;
586
+ locale?: string;
587
+ traceparent?: string;
588
+ traceId?: string;
589
+ spanId?: string;
590
+ };
591
+
592
+ export declare const client: EffectClient;
593
+ export declare const createEffectRequestContext: (
594
+ requestContext: Record<string, unknown>,
595
+ ) => EffectRequestContext;
596
+ export declare const operationManifest: EffectOperationManifest;
597
+ declare const effectBffModule: {
598
+ client: EffectClient;
599
+ createEffectRequestContext: typeof createEffectRequestContext;
600
+ operationManifest: EffectOperationManifest;
601
+ };
602
+
603
+ export default effectBffModule;
604
+ `;
605
+ }
606
+ async function generateEffectClientCode(options) {
607
+ const api = await loadEffectApi(options.resourcePath);
608
+ if (!api) {
609
+ logger.warn(`[BFF][Effect] Failed to generate client for ${options.resourcePath}: unable to resolve exported HttpApi.`);
610
+ return null;
611
+ }
612
+ const httpApiRuntime = await getHttpApiRuntime();
613
+ const endpoints = collectEffectEndpoints(httpApiRuntime, api, options.prefix);
614
+ return renderEffectClientCode(endpoints, options);
615
+ }
616
+ function resolveEffectEntryFile(options) {
617
+ const { appDir, apiDir, effectEntry } = options;
618
+ const defaultEntry = path.resolve(apiDir, 'effect', 'index');
619
+ const entryWithoutExt = effectEntry ? path.isAbsolute(effectEntry) ? effectEntry : path.resolve(appDir, effectEntry) : defaultEntry;
620
+ if (path.extname(entryWithoutExt)) return fs.existsSync(entryWithoutExt) ? entryWithoutExt : void 0;
621
+ return findExists(JS_OR_TS_EXTS.map((ext)=>`${entryWithoutExt}${ext}`));
622
+ }
623
+ export { generateEffectClientCode, renderEffectClientDeclaration, resolveEffectEntryFile };
@@ -0,0 +1,29 @@
1
+ import { fs, logger, normalizeToPosixPath } from "@modern-js/utils";
2
+ import path from "path";
3
+ import { API_DIR, DIST_DIR, LAMBDA_DIR, PACKAGE_NAME, PREFIX, RUNTIME_FRAMEWORK } from "./crossProjectApiPlugin.mjs";
4
+ function replaceContent(source, packageName, prefix, relativeDistPath, relativeApiPath, relativeLambdaPath, runtimeFramework) {
5
+ const updatedSource = source.replace(new RegExp(PACKAGE_NAME, 'g'), packageName).replace(new RegExp(PREFIX, 'g'), prefix).replace(new RegExp(DIST_DIR, 'g'), normalizeToPosixPath(relativeDistPath)).replace(new RegExp(API_DIR, 'g'), normalizeToPosixPath(relativeApiPath)).replace(new RegExp(LAMBDA_DIR, 'g'), normalizeToPosixPath(relativeLambdaPath)).replace(new RegExp(RUNTIME_FRAMEWORK, 'g'), runtimeFramework);
6
+ return updatedSource;
7
+ }
8
+ async function pluginGenerator({ prefix, appDirectory, relativeDistPath, relativeApiPath, relativeLambdaPath, runtimeFramework }) {
9
+ try {
10
+ const packageContent = await fs.readFile(path.resolve(appDirectory, './package.json'), 'utf8');
11
+ const packageJson = JSON.parse(packageContent);
12
+ const pluginDir = path.resolve(appDirectory, `./${relativeDistPath}`, 'plugin');
13
+ const pluginPath = path.join(pluginDir, 'index.js');
14
+ const pluginTemplate = await fs.readFile(path.resolve(__dirname, 'crossProjectApiPlugin.js'), 'utf8');
15
+ const updatedPlugin = replaceContent(pluginTemplate, packageJson.name, prefix, relativeDistPath, relativeApiPath, relativeLambdaPath, runtimeFramework);
16
+ await fs.ensureFile(pluginPath);
17
+ await fs.writeFile(pluginPath, updatedPlugin);
18
+ const typeContent = `import type { AppTools, CliPlugin } from '@modern-js/app-tools';
19
+ export declare const crossProjectApiPlugin: () => CliPlugin<AppTools>`;
20
+ const pluginTypePath = path.join(pluginDir, 'index.d.ts');
21
+ await fs.ensureFile(pluginTypePath);
22
+ await fs.writeFile(pluginTypePath, typeContent);
23
+ logger.info('Api plugin generate succeed');
24
+ } catch (error) {
25
+ logger.error('Api plugin generate failed:', error);
26
+ }
27
+ }
28
+ const utils_pluginGenerator = pluginGenerator;
29
+ export default utils_pluginGenerator;