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