@bleedingdev/modern-js-plugin-bff 3.9.0-ultramodern.2 → 3.9.0-ultramodern.20

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 (81) hide show
  1. package/dist/cjs/cli/generator.js +118 -117
  2. package/dist/cjs/cli.js +12 -7
  3. package/dist/cjs/loader.js +9 -65
  4. package/dist/cjs/runtime/create-request/index.js +0 -6
  5. package/dist/cjs/runtime/hono/adapter.js +8 -12
  6. package/dist/cjs/server.js +41 -50
  7. package/dist/cjs/utils/client-generator/files.js +1 -1
  8. package/dist/cjs/utils/client-generator/generate.js +46 -45
  9. package/dist/cjs/utils/client-generator/package-json.js +2 -2
  10. package/dist/cjs/utils/client-generator/write-package.js +18 -1
  11. package/dist/cjs/utils/createHonoRoutes.js +1 -1
  12. package/dist/cjs/utils/crossProjectApiPlugin.js +26 -83
  13. package/dist/cjs/utils/pluginGenerator.js +26 -26
  14. package/dist/cjs/utils/runtimeGenerator.js +26 -75
  15. package/dist/esm/cli/generator.mjs +121 -120
  16. package/dist/esm/cli.mjs +12 -7
  17. package/dist/esm/loader.mjs +9 -55
  18. package/dist/esm/runtime/create-request/index.mjs +1 -1
  19. package/dist/esm/runtime/hono/adapter.mjs +8 -12
  20. package/dist/esm/server.mjs +42 -51
  21. package/dist/esm/utils/client-generator/files.mjs +1 -1
  22. package/dist/esm/utils/client-generator/generate.mjs +47 -46
  23. package/dist/esm/utils/client-generator/package-json.mjs +3 -3
  24. package/dist/esm/utils/client-generator/write-package.mjs +18 -1
  25. package/dist/esm/utils/createHonoRoutes.mjs +1 -1
  26. package/dist/esm/utils/crossProjectApiPlugin.mjs +24 -54
  27. package/dist/esm/utils/pluginGenerator.mjs +23 -25
  28. package/dist/esm/utils/runtimeGenerator.mjs +23 -74
  29. package/dist/esm-node/cli/generator.mjs +121 -120
  30. package/dist/esm-node/cli.mjs +12 -7
  31. package/dist/esm-node/loader.mjs +9 -55
  32. package/dist/esm-node/runtime/create-request/index.mjs +1 -1
  33. package/dist/esm-node/runtime/hono/adapter.mjs +8 -12
  34. package/dist/esm-node/server.mjs +42 -51
  35. package/dist/esm-node/utils/client-generator/files.mjs +1 -1
  36. package/dist/esm-node/utils/client-generator/generate.mjs +47 -46
  37. package/dist/esm-node/utils/client-generator/package-json.mjs +3 -3
  38. package/dist/esm-node/utils/client-generator/write-package.mjs +18 -1
  39. package/dist/esm-node/utils/createHonoRoutes.mjs +1 -1
  40. package/dist/esm-node/utils/crossProjectApiPlugin.mjs +24 -54
  41. package/dist/esm-node/utils/pluginGenerator.mjs +23 -28
  42. package/dist/esm-node/utils/runtimeGenerator.mjs +24 -76
  43. package/dist/types/cli/generator.d.ts +2 -2
  44. package/dist/types/loader.d.ts +1 -11
  45. package/dist/types/runtime/create-request/index.d.ts +1 -3
  46. package/dist/types/runtime/hono/adapter.d.ts +9 -2
  47. package/dist/types/server.d.ts +4 -1
  48. package/dist/types/utils/client-generator/generate.d.ts +8 -12
  49. package/dist/types/utils/client-generator/write-package.d.ts +1 -1
  50. package/dist/types/utils/crossProjectApiPlugin.d.ts +18 -12
  51. package/dist/types/utils/pluginGenerator.d.ts +6 -7
  52. package/dist/types/utils/runtimeGenerator.d.ts +6 -3
  53. package/package.json +31 -124
  54. package/dist/cjs/cli/serverGlobalVars.js +0 -113
  55. package/dist/cjs/runtime/data-platform/index.js +0 -62
  56. package/dist/cjs/runtime/effect/edge-dispatcher.js +0 -62
  57. package/dist/cjs/runtime/effect/edge.js +0 -69
  58. package/dist/cjs/runtime/effect/index.js +0 -305
  59. package/dist/cjs/runtime/effect-client/index.js +0 -62
  60. package/dist/cjs/runtime/effect-client/runtime.js +0 -62
  61. package/dist/esm/cli/serverGlobalVars.mjs +0 -72
  62. package/dist/esm/runtime/data-platform/index.mjs +0 -1
  63. package/dist/esm/runtime/effect/edge-dispatcher.mjs +0 -1
  64. package/dist/esm/runtime/effect/edge.mjs +0 -2
  65. package/dist/esm/runtime/effect/index.mjs +0 -16
  66. package/dist/esm/runtime/effect-client/index.mjs +0 -1
  67. package/dist/esm/runtime/effect-client/runtime.mjs +0 -1
  68. package/dist/esm-node/cli/serverGlobalVars.mjs +0 -73
  69. package/dist/esm-node/runtime/data-platform/index.mjs +0 -2
  70. package/dist/esm-node/runtime/effect/edge-dispatcher.mjs +0 -2
  71. package/dist/esm-node/runtime/effect/edge.mjs +0 -3
  72. package/dist/esm-node/runtime/effect/index.mjs +0 -17
  73. package/dist/esm-node/runtime/effect-client/index.mjs +0 -2
  74. package/dist/esm-node/runtime/effect-client/runtime.mjs +0 -2
  75. package/dist/types/cli/serverGlobalVars.d.ts +0 -6
  76. package/dist/types/runtime/data-platform/index.d.ts +0 -1
  77. package/dist/types/runtime/effect/edge-dispatcher.d.ts +0 -1
  78. package/dist/types/runtime/effect/edge.d.ts +0 -2
  79. package/dist/types/runtime/effect/index.d.ts +0 -15
  80. package/dist/types/runtime/effect-client/index.d.ts +0 -1
  81. package/dist/types/runtime/effect-client/runtime.d.ts +0 -1
@@ -1,19 +1,18 @@
1
- import { generateClient } from "@modern-js/bff-core";
1
+ import { ClientCodegenError, generateClient } from "@modern-js/bff-core";
2
2
  import { fs, logger } from "@modern-js/utils";
3
3
  import path from "path";
4
4
  import { CLIENT_DIR, createFileDetails, readDirectoryFiles, writeTargetFile } from "./files.mjs";
5
5
  import { getPackageName } from "./package-json.mjs";
6
6
  import { DEFAULT_EXPORT_RE, buildClientTypeFacade, createMissingClientDeclarationError, isMissingClientDeclarationError } from "./type-facade.mjs";
7
7
  import { setPackage, writeClientModuleBoundary } from "./write-package.mjs";
8
- async function clientGenerator(draftOptions) {
8
+ async function clientGenerator(draftOptions, integration) {
9
9
  const generatedClientDir = path.resolve(draftOptions.appDir, draftOptions.relativeDistPath, CLIENT_DIR);
10
10
  await fs.remove(generatedClientDir);
11
- const requestId = getPackageName(draftOptions.appDir) || process.env.npm_package_name;
11
+ const requestId = draftOptions.requestId || getPackageName(draftOptions.appDir) || process.env.npm_package_name;
12
12
  const lambdaSourceList = draftOptions.existLambda ? await readDirectoryFiles(draftOptions.appDir, draftOptions.lambdaDir, draftOptions.relativeDistPath, draftOptions.apiFiles) : [];
13
13
  const generatedSourceList = [
14
14
  ...lambdaSourceList
15
15
  ];
16
- let generatedEffectClient = null;
17
16
  const getClitentCode = async (resourcePath, source)=>{
18
17
  const warning = `The file ${resourcePath} is not allowed to be imported in src directory, only API definition files are allowed.`;
19
18
  if (!draftOptions.existLambda) return void logger.warn(warning);
@@ -28,6 +27,7 @@ async function clientGenerator(draftOptions) {
28
27
  target: 'bundle',
29
28
  httpMethodDecider: draftOptions.httpMethodDecider,
30
29
  requestCreator: draftOptions.requestCreator,
30
+ clientCodegenPlugin: draftOptions.clientCodegenPlugin,
31
31
  requestId
32
32
  };
33
33
  const { lambdaDir } = draftOptions;
@@ -36,9 +36,9 @@ async function clientGenerator(draftOptions) {
36
36
  return result;
37
37
  };
38
38
  const writeClientTypeFacade = async (source, clientCode)=>{
39
- if (!await fs.pathExists(path.resolve(source.relativeTargetDistDir))) throw createMissingClientDeclarationError(source.resourcePath, source.relativeTargetDistDir);
40
- const clientTypesFile = source.targetDir.replace(/\.js$/, '.d.ts');
41
- await writeTargetFile(path.resolve(clientTypesFile), buildClientTypeFacade(clientTypesFile, source.relativeTargetDistDir, DEFAULT_EXPORT_RE.test(clientCode), true));
39
+ if (!await fs.pathExists(path.resolve(draftOptions.appDir, source.relativeTargetDistDir))) throw createMissingClientDeclarationError(source.resourcePath, path.resolve(draftOptions.appDir, source.relativeTargetDistDir));
40
+ const clientTypesFile = source.absTargetDir.replace(/\.js$/, '.d.ts');
41
+ await writeTargetFile(path.resolve(clientTypesFile), buildClientTypeFacade(clientTypesFile, path.resolve(draftOptions.appDir, source.relativeTargetDistDir), DEFAULT_EXPORT_RE.test(clientCode), true));
42
42
  };
43
43
  try {
44
44
  for (const source of lambdaSourceList){
@@ -48,50 +48,51 @@ async function clientGenerator(draftOptions) {
48
48
  await writeClientTypeFacade(source, code.value);
49
49
  }
50
50
  }
51
- if ('effect' === draftOptions.bffRuntimeFramework) {
52
- const { generateEffectClient, resolveEffectEntryFile } = await import("@modern-js/plugin-bff-extensions/client-generator");
53
- const effectEntryFile = resolveEffectEntryFile({
54
- appDir: draftOptions.appDir,
55
- apiDir: draftOptions.apiDir,
56
- effectEntry: draftOptions.effectEntry
57
- });
58
- if (effectEntryFile) {
59
- const effectSource = await fs.readFile(effectEntryFile, 'utf8');
60
- const effectFileDetails = createFileDetails({
61
- appDirectory: draftOptions.appDir,
62
- baseDirectory: draftOptions.apiDir,
63
- resourcePath: effectEntryFile,
64
- source: effectSource,
65
- relativeDistPath: draftOptions.relativeDistPath
66
- });
67
- generatedEffectClient = await generateEffectClient({
68
- appDir: draftOptions.appDir,
69
- apiDir: draftOptions.apiDir,
70
- resourcePath: effectEntryFile,
71
- prefix: Array.isArray(draftOptions.prefix) ? draftOptions.prefix[0] : draftOptions.prefix,
72
- port: Number(draftOptions.port),
73
- target: 'bundle',
74
- requestId: draftOptions.requestId,
75
- requestCreator: draftOptions.requestCreator,
76
- httpMethodDecider: draftOptions.httpMethodDecider,
77
- dataPlatformBatch: draftOptions.effectDataPlatformBatch
78
- });
79
- if (generatedEffectClient) {
80
- const targetTypeFile = effectFileDetails.targetDir.replace(/\.js$/, '.d.ts');
81
- await writeTargetFile(effectFileDetails.absTargetDir, generatedEffectClient.code);
82
- await writeTargetFile(path.resolve(targetTypeFile), generatedEffectClient.declaration);
83
- generatedSourceList.push(effectFileDetails);
84
- }
85
- }
86
- }
87
51
  logger.info("Client bundle generate succeed");
88
52
  } catch (error) {
89
- if (isMissingClientDeclarationError(error)) throw error;
53
+ if (isMissingClientDeclarationError(error) || error instanceof ClientCodegenError) throw error;
90
54
  logger.error(`Client bundle generate failed: ${error}`);
91
55
  }
56
+ let packageDependencies;
57
+ if (integration) {
58
+ const artifacts = await integration.modifyArtifacts({
59
+ generation: integration.generation,
60
+ additionalArtifacts: []
61
+ });
62
+ if (artifacts.generation !== integration.generation) throw new Error('BFF artifacts must preserve generation identity.');
63
+ const sourcePaths = new Set(generatedSourceList.map((file)=>path.resolve(file.resourcePath)));
64
+ const exportKeys = new Set(generatedSourceList.map((file)=>file.exportKey));
65
+ const outputPaths = new Set(generatedSourceList.map((file)=>path.resolve(file.absTargetDir)));
66
+ const additionalFiles = artifacts.additionalArtifacts.map((artifact)=>{
67
+ const relative = artifact.sourcePath;
68
+ const resourcePath = path.resolve(draftOptions.apiDir, relative);
69
+ if (!relative || path.isAbsolute(relative) || relative.includes('\\') || path.relative(draftOptions.apiDir, resourcePath).split(path.sep).includes('..') || path.relative(draftOptions.apiDir, resourcePath).split(path.sep).join('/') !== relative || !/\.[cm]?[jt]sx?$/.test(relative)) throw new Error(`Invalid BFF client artifact source path: ${relative}`);
70
+ const file = createFileDetails({
71
+ appDirectory: draftOptions.appDir,
72
+ baseDirectory: draftOptions.apiDir,
73
+ resourcePath,
74
+ source: '',
75
+ relativeDistPath: draftOptions.relativeDistPath
76
+ });
77
+ if (sourcePaths.has(resourcePath) || exportKeys.has(file.exportKey) || outputPaths.has(path.resolve(file.absTargetDir))) throw new Error(`BFF client artifact collision: ${relative}`);
78
+ sourcePaths.add(resourcePath);
79
+ exportKeys.add(file.exportKey);
80
+ outputPaths.add(path.resolve(file.absTargetDir));
81
+ return {
82
+ file,
83
+ artifact
84
+ };
85
+ });
86
+ for (const { file, artifact } of additionalFiles){
87
+ await writeTargetFile(file.absTargetDir, artifact.code);
88
+ await writeTargetFile(file.absTargetDir.replace(/\.js$/, '.d.ts'), artifact.declaration);
89
+ generatedSourceList.push(file);
90
+ }
91
+ packageDependencies = await integration.beforePublish() || void 0;
92
+ }
92
93
  if (generatedSourceList.length > 0) await writeClientModuleBoundary(draftOptions.appDir, draftOptions.relativeDistPath);
93
- await setPackage(generatedSourceList, draftOptions.appDir, draftOptions.relativeDistPath);
94
- return generatedEffectClient;
94
+ await setPackage(generatedSourceList, draftOptions.appDir, draftOptions.relativeDistPath, packageDependencies);
95
+ return null;
95
96
  }
96
97
  const generate = clientGenerator;
97
98
  export default generate;
@@ -1,6 +1,6 @@
1
1
  import { fs } from "@modern-js/utils";
2
2
  import path from "path";
3
- import { EXPORT_PREFIX, GENERATED_RUNTIME_DIRS, TYPE_PREFIX, toPosixPath } from "./files.mjs";
3
+ import { EXPORT_PREFIX, GENERATED_RUNTIME_DIRS, RUNTIME_DIR, TYPE_PREFIX, toPosixPath } from "./files.mjs";
4
4
  function getPackageName(appDirectory) {
5
5
  try {
6
6
  const packageJsonPath = path.resolve(appDirectory, './package.json');
@@ -46,7 +46,7 @@ function mergePackageJson(packageJson, files, typesVersion, exports, relativeDis
46
46
  }).map(([key])=>key);
47
47
  if (typeConflicts.length > 0) throw new Error(`[plugin-bff] package.json typesVersions conflict on keys: ${typeConflicts.sort().join(', ')}. Rename these keys or move them outside "${TYPE_PREFIX}" namespace.`);
48
48
  Object.keys(starTypes).forEach((key)=>{
49
- if (generatedTypeKeys.has(key) || key.startsWith(TYPE_PREFIX)) delete starTypes[key];
49
+ if (generatedTypeKeys.has(key) || key.startsWith(TYPE_PREFIX) || key === RUNTIME_DIR && isManagedTypeEntry(starTypes[key])) delete starTypes[key];
50
50
  });
51
51
  typesVersions['*'] = {
52
52
  ...starTypes,
@@ -63,7 +63,7 @@ function mergePackageJson(packageJson, files, typesVersion, exports, relativeDis
63
63
  }).map(([key])=>key);
64
64
  if (exportConflicts.length > 0) throw new Error(`[plugin-bff] package.json exports conflict on keys: ${exportConflicts.sort().join(', ')}. Rename these exports or move them outside "${EXPORT_PREFIX}" namespace.`);
65
65
  Object.keys(packageExports).forEach((key)=>{
66
- if (generatedExportKeys.has(key) || key.startsWith(EXPORT_PREFIX)) delete packageExports[key];
66
+ if (generatedExportKeys.has(key) || key.startsWith(EXPORT_PREFIX) || key === `./${RUNTIME_DIR}` && isManagedExportEntry(packageExports[key])) delete packageExports[key];
67
67
  });
68
68
  Object.assign(packageExports, exports);
69
69
  }
@@ -9,10 +9,19 @@ async function writeClientModuleBoundary(appDirectory, relativeDistPath) {
9
9
  type: 'module'
10
10
  }, null, 2)}\n`);
11
11
  }
12
- async function setPackage(files, appDirectory, relativeDistPath) {
12
+ async function setPackage(files, appDirectory, relativeDistPath, packageDependencies = {}) {
13
13
  const packagePath = path.resolve(appDirectory, './package.json');
14
14
  const packageContent = await fs.readFile(packagePath, 'utf8');
15
15
  const packageJson = JSON.parse(packageContent);
16
+ for (const [name, specifier] of Object.entries(packageDependencies)){
17
+ if (!name || 'string' != typeof specifier || !specifier.trim()) throw new Error(`Invalid BFF SDK dependency: ${name}`);
18
+ const existing = packageJson.dependencies?.[name];
19
+ if (void 0 !== existing && existing !== specifier) throw new Error(`package.json dependency conflict for ${name}: ${existing} versus ${specifier}`);
20
+ }
21
+ if (Object.keys(packageDependencies).length > 0) packageJson.dependencies = {
22
+ ...packageJson.dependencies,
23
+ ...packageDependencies
24
+ };
16
25
  const sortedFiles = [
17
26
  ...files
18
27
  ].sort((a, b)=>a.exportKey.localeCompare(b.exportKey));
@@ -69,6 +78,14 @@ async function setPackage(files, appDirectory, relativeDistPath) {
69
78
  types: toPosixPath(`./${relativeDistPath}/${RUNTIME_DIR}/index.d.ts`)
70
79
  }
71
80
  });
81
+ if (0 === files.length) {
82
+ Reflect.deleteProperty(typesVersions['*'], `${API_DIR}/*`);
83
+ Reflect.deleteProperty(exports, `./${API_DIR}/*`);
84
+ }
85
+ if (!fs.existsSync(path.resolve(appDirectory, relativeDistPath, RUNTIME_DIR, 'index.js'))) {
86
+ Reflect.deleteProperty(typesVersions['*'], RUNTIME_DIR);
87
+ Reflect.deleteProperty(exports, `./${RUNTIME_DIR}`);
88
+ }
72
89
  mergePackageJson(packageJson, addFiles, typesVersions, exports, relativeDistPath);
73
90
  await fs.promises.writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
74
91
  }
@@ -47,7 +47,7 @@ const createHonoHandler = (handler)=>async (c)=>{
47
47
  }
48
48
  throw error;
49
49
  }
50
- {
50
+ else {
51
51
  const routePath = c.req.routePath;
52
52
  const paramNames = routePath.match(/:\w+/g)?.map((s)=>s.slice(1)) || [];
53
53
  const params = Object.fromEntries(paramNames.map((name)=>[
@@ -1,68 +1,38 @@
1
1
  import path from "path";
2
- const PACKAGE_NAME = '{packageName}';
3
- const REQUEST_ID = '{requestId}';
4
- const PREFIX = '{prefix}';
5
- const API_DIR = '{apiDirectory}';
6
- const LAMBDA_DIR = '{lambdaDirectory}';
7
- const DIST_DIR = '{distDirectory}';
8
- const RUNTIME_FRAMEWORK = '{runtimeFramework}';
9
- const EFFECT_ENTRY = '{effectEntry}';
10
- const OPERATION_CONTRACTS_JSON = '{operationContracts}';
11
- const NODE_MODULES = 'node_modules';
12
- const crossProjectApiPlugin = ()=>({
2
+ const createCrossProjectApiPlugin = (options)=>({
13
3
  name: '@modern-js/plugin-independent-bff',
14
4
  post: [
15
5
  '@modern-js/plugin-bff'
16
6
  ],
17
7
  setup: (api)=>{
18
- api.modifyResolvedConfig((resolvedConfig)=>{
19
- const { appDirectory: originAppDirectory } = api.getAppContext();
20
- const sdkPath = path.join(originAppDirectory, NODE_MODULES, PACKAGE_NAME);
21
- const sdkDistPath = path.join(sdkPath, DIST_DIR);
22
- const effectEntry = EFFECT_ENTRY ? path.join(sdkDistPath, EFFECT_ENTRY) : void 0;
23
- const apiDirectory = effectEntry ? path.dirname(effectEntry) : path.join(sdkDistPath, API_DIR);
24
- const lambdaDirectory = path.resolve(sdkDistPath, LAMBDA_DIR);
8
+ api.modifyResolvedConfig(async (resolvedConfig)=>{
9
+ const { appDirectory } = api.getAppContext();
10
+ const sdkDirectory = path.join(appDirectory, 'node_modules', options.packageName);
11
+ const sdkDistDirectory = path.join(sdkDirectory, options.relativeDistPath);
12
+ const apiDirectory = path.join(sdkDistDirectory, options.relativeApiPath);
13
+ const lambdaDirectory = path.resolve(sdkDistDirectory, options.relativeLambdaPath);
14
+ const configuredPrefix = api.getConfig()?.bff?.prefix;
15
+ if (configuredPrefix) {
16
+ const isSamePrefix = Array.isArray(configuredPrefix) ? 1 === configuredPrefix.length && configuredPrefix[0] === options.prefix : configuredPrefix === options.prefix;
17
+ if (!isSamePrefix) throw new Error(`[${options.packageName}] Invalid bff.prefix for cross-project BFF. Detected "${configuredPrefix}", expected "${options.prefix}". Remove bff.prefix from the consumer app, or set it exactly to "${options.prefix}".`);
18
+ }
25
19
  api.updateAppContext({
26
20
  apiDirectory,
27
- lambdaDirectory,
28
- bffRuntimeFramework: RUNTIME_FRAMEWORK
21
+ lambdaDirectory
29
22
  });
30
- const config = api.getConfig();
31
- const configuredPrefix = config?.bff?.prefix;
32
- if (configuredPrefix) {
33
- const isSamePrefix = Array.isArray(configuredPrefix) ? 1 === configuredPrefix.length && configuredPrefix[0] === PREFIX : configuredPrefix === PREFIX;
34
- if (!isSamePrefix) throw new Error(`[${PACKAGE_NAME}] Invalid bff.prefix for cross-project BFF. Detected "${configuredPrefix}", expected "${PREFIX}". Remove bff.prefix from the consumer app, or set it exactly to "${PREFIX}".`);
35
- }
36
- const configuredRuntimeFramework = config?.bff?.runtimeFramework;
37
- if (configuredRuntimeFramework && configuredRuntimeFramework !== RUNTIME_FRAMEWORK) throw new Error(`[${PACKAGE_NAME}] Runtime framework mismatch for cross-project BFF. Detected "${configuredRuntimeFramework}", but producer SDK requires "${RUNTIME_FRAMEWORK}".`);
38
23
  resolvedConfig.bff ??= {};
39
- resolvedConfig.bff.prefix = PREFIX;
40
- resolvedConfig.bff.runtimeFramework = RUNTIME_FRAMEWORK;
41
- if (EFFECT_ENTRY) resolvedConfig.bff.effect = {
42
- ...resolvedConfig.bff.effect,
43
- entry: effectEntry
44
- };
24
+ resolvedConfig.bff.prefix = options.prefix;
45
25
  resolvedConfig.bff.isCrossProjectServer = true;
46
- resolvedConfig.bff.requestId = resolvedConfig.bff.requestId || config?.bff?.requestId || REQUEST_ID || PACKAGE_NAME || 'default';
47
- const generatedOperationContracts = "{operationContracts}" === OPERATION_CONTRACTS_JSON ? {} : JSON.parse(OPERATION_CONTRACTS_JSON);
48
- resolvedConfig.bff.crossProjectPolicy = {
49
- ...resolvedConfig.bff.crossProjectPolicy || {},
50
- enabled: resolvedConfig.bff.crossProjectPolicy?.enabled ?? true,
51
- requireEnvelope: resolvedConfig.bff.crossProjectPolicy?.requireEnvelope ?? true,
52
- requireOperationContext: resolvedConfig.bff.crossProjectPolicy?.requireOperationContext ?? true,
53
- requireOperationContextDetails: resolvedConfig.bff.crossProjectPolicy?.requireOperationContextDetails ?? true,
54
- requireOperationSchemaHash: resolvedConfig.bff.crossProjectPolicy?.requireOperationSchemaHash ?? true,
55
- requireOperationVersion: resolvedConfig.bff.crossProjectPolicy?.requireOperationVersion ?? true,
56
- allowUnknownOperations: resolvedConfig.bff.crossProjectPolicy?.allowUnknownOperations ?? false,
57
- expectedOperationContracts: {
58
- ...resolvedConfig.bff.crossProjectPolicy?.expectedOperationContracts || {},
59
- ...generatedOperationContracts
60
- }
61
- };
62
- return resolvedConfig;
26
+ return options.modifyResolvedConfig ? options.modifyResolvedConfig(resolvedConfig, {
27
+ sdkDirectory,
28
+ sdkDistDirectory,
29
+ apiDirectory,
30
+ lambdaDirectory,
31
+ api
32
+ }) : resolvedConfig;
63
33
  });
64
34
  }
65
35
  });
66
- const utils_crossProjectApiPlugin = crossProjectApiPlugin;
67
- export default utils_crossProjectApiPlugin;
68
- export { API_DIR, DIST_DIR, EFFECT_ENTRY, LAMBDA_DIR, OPERATION_CONTRACTS_JSON, PACKAGE_NAME, PREFIX, REQUEST_ID, RUNTIME_FRAMEWORK, crossProjectApiPlugin };
36
+ const crossProjectApiPlugin = createCrossProjectApiPlugin;
37
+ export default crossProjectApiPlugin;
38
+ export { createCrossProjectApiPlugin };
@@ -1,29 +1,27 @@
1
1
  import { fs, logger, normalizeToPosixPath } from "@modern-js/utils";
2
2
  import path from "path";
3
- import { API_DIR, DIST_DIR, EFFECT_ENTRY, LAMBDA_DIR, OPERATION_CONTRACTS_JSON, PACKAGE_NAME, PREFIX, REQUEST_ID, RUNTIME_FRAMEWORK } from "./crossProjectApiPlugin.mjs";
4
- function replaceContent(source, packageName, requestId, prefix, relativeDistPath, relativeApiPath, relativeLambdaPath, runtimeFramework, relativeEffectEntry, operationContracts) {
5
- const updatedSource = source.replace(new RegExp(PACKAGE_NAME, 'g'), packageName).replace(new RegExp(REQUEST_ID, 'g'), requestId).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).replace(new RegExp(EFFECT_ENTRY, 'g'), normalizeToPosixPath(relativeEffectEntry)).replace(`'${OPERATION_CONTRACTS_JSON}'`, ()=>JSON.stringify(JSON.stringify(operationContracts)));
6
- return updatedSource;
3
+ async function renderBffPlugin(options) {
4
+ const packageJson = await fs.readJSON(path.resolve(options.appDirectory, 'package.json'));
5
+ const descriptor = {
6
+ packageName: packageJson.name,
7
+ prefix: options.prefix,
8
+ relativeDistPath: normalizeToPosixPath(options.relativeDistPath),
9
+ relativeApiPath: normalizeToPosixPath(options.relativeApiPath),
10
+ relativeLambdaPath: normalizeToPosixPath(options.relativeLambdaPath)
11
+ };
12
+ return {
13
+ code: 'module' === packageJson.type ? `import { createCrossProjectApiPlugin } from '@modern-js/plugin-bff/cross-project';\nexport const crossProjectApiPlugin = () => createCrossProjectApiPlugin(${JSON.stringify(descriptor)});\n` : `'use strict';\nconst { createCrossProjectApiPlugin } = require('@modern-js/plugin-bff/cross-project');\nexports.crossProjectApiPlugin = () => createCrossProjectApiPlugin(${JSON.stringify(descriptor)});\n`,
14
+ declaration: `import type { AppTools, CliPlugin } from '@modern-js/app-tools';
15
+ export declare const crossProjectApiPlugin: () => CliPlugin<AppTools>;
16
+ `
17
+ };
7
18
  }
8
- async function pluginGenerator({ prefix, appDirectory, requestId, relativeDistPath, relativeApiPath, relativeLambdaPath, runtimeFramework, relativeEffectEntry, operationContracts }) {
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, requestId, prefix, relativeDistPath, relativeApiPath, relativeLambdaPath, runtimeFramework, relativeEffectEntry, operationContracts);
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
- }
19
+ async function pluginGenerator(options, rendered) {
20
+ const module = rendered ?? await renderBffPlugin(options);
21
+ const directory = path.resolve(options.appDirectory, options.relativeDistPath, 'plugin');
22
+ await fs.outputFile(path.join(directory, 'index.js'), module.code);
23
+ await fs.outputFile(path.join(directory, 'index.d.ts'), module.declaration);
24
+ logger.info('Api plugin generate succeed');
27
25
  }
28
- const utils_pluginGenerator = pluginGenerator;
29
- export default utils_pluginGenerator;
26
+ export default pluginGenerator;
27
+ export { renderBffPlugin };
@@ -1,77 +1,26 @@
1
- import { renderProducerRuntimeDefaults } from "@modern-js/plugin-bff-extensions/cross-project-generation";
1
+ import { pathToFileURL } from "node:url";
2
2
  import { fs } from "@modern-js/utils";
3
3
  import path from "path";
4
- const getPackageName = (appDirectory)=>{
5
- try {
6
- const packageJsonPath = path.resolve(appDirectory, './package.json');
7
- const packageJson = require(packageJsonPath);
8
- return packageJson.name;
9
- } catch (error) {
10
- return;
11
- }
12
- };
13
- async function runtimeGenerator({ runtime, appDirectory, relativeDistPath, packageName }) {
14
- const pluginDir = path.resolve(appDirectory, `./${relativeDistPath}`, 'runtime');
15
- const requestId = packageName || getPackageName(appDirectory) || process.env.npm_package_name || 'default';
16
- const runtimeImportPath = JSON.stringify(runtime);
17
- const requestIdValue = JSON.stringify(requestId);
18
- const source = `'use strict'; const { configure: _configure } = require(${runtimeImportPath});
19
- const defaultSecureOptions = ${renderProducerRuntimeDefaults(requestIdValue)};
20
- const initProducerClient = (options) => {
21
- return _configure({
22
- ...defaultSecureOptions,
23
- ...options,
24
- identityBinding: {
25
- ...defaultSecureOptions.identityBinding,
26
- ...(options && options.identityBinding ? options.identityBinding : {}),
27
- },
28
- operationContract: {
29
- ...defaultSecureOptions.operationContract,
30
- ...(options && options.operationContract ? options.operationContract : {}),
31
- },
32
- });
33
- }
34
- const configure = initProducerClient;
35
- Object.defineProperty(exports, '__esModule', { value: true });
36
- exports.initProducerClient = initProducerClient;
37
- exports.configure = configure;
38
- `;
39
- const pluginPath = path.join(pluginDir, 'index.js');
40
- await fs.ensureFile(pluginPath);
41
- await fs.writeFile(pluginPath, source);
42
- const tsSource = `type ProducerRuntimeModule = typeof import(${runtimeImportPath});
43
- type ProducerClientOptions = ProducerRuntimeModule extends {
44
- configure: (options: infer TOptions) => unknown;
45
- }
46
- ? TOptions
47
- : {
48
- request?: typeof fetch;
49
- interceptor?: (request: typeof fetch) => typeof fetch;
50
- allowedHeaders?: string[];
51
- requireEnvelope?: boolean;
52
- allowCrossOriginEnvelope?: boolean;
53
- identityBinding?: {
54
- enabled?: boolean;
55
- strict?: boolean;
56
- protectedHeaders?: string[];
57
- };
58
- operationContract?: {
59
- enabled?: boolean;
60
- strict?: boolean;
61
- requireSchemaHash?: boolean;
62
- requireOperationVersion?: boolean;
63
- };
64
- setDomain?: (ops?: {
65
- target: 'server' | 'browser';
66
- requestId?: string;
67
- }) => string;
68
- requestId?: string;
69
- };
70
- export declare const initProducerClient: (options?: ProducerClientOptions) => ReturnType<ProducerRuntimeModule['configure']>;
71
- export declare const configure: typeof initProducerClient;`;
72
- const pluginTypePath = path.join(pluginDir, 'index.d.ts');
73
- await fs.ensureFile(pluginTypePath);
74
- await fs.writeFile(pluginTypePath, tsSource);
4
+ function renderBffRuntime(options) {
5
+ const packagePath = path.resolve(options.appDirectory, 'package.json');
6
+ const packageJson = fs.existsSync(packagePath) ? fs.readJSONSync(packagePath) : {};
7
+ const requestId = options.packageName || packageJson.name || process.env.npm_package_name || 'default';
8
+ const runtime = JSON.stringify(options.runtime);
9
+ const esmRuntime = JSON.stringify(path.isAbsolute(options.runtime) ? pathToFileURL(options.runtime).href : options.runtime);
10
+ return {
11
+ code: 'module' === packageJson.type ? `import { configure as _configure } from ${esmRuntime};\nexport const initProducerClient = options => _configure({ requestId: ${JSON.stringify(requestId)}, ...options });\nexport const configure = initProducerClient;\n` : `'use strict';\nconst { configure: _configure } = require(${runtime});\nconst initProducerClient = options => _configure({ requestId: ${JSON.stringify(requestId)}, ...options });\nexports.initProducerClient = initProducerClient;\nexports.configure = initProducerClient;\n`,
12
+ declaration: `type Runtime = typeof import(${runtime});
13
+ export declare const initProducerClient: (options?: Parameters<Runtime['configure']>[0]) => ReturnType<Runtime['configure']>;
14
+ export declare const configure: typeof initProducerClient;
15
+ `
16
+ };
75
17
  }
76
- const utils_runtimeGenerator = runtimeGenerator;
77
- export default utils_runtimeGenerator;
18
+ async function runtimeGenerator(options, rendered) {
19
+ const directory = path.resolve(options.appDirectory, options.relativeDistPath, 'runtime');
20
+ if (null === rendered) return void await fs.remove(directory);
21
+ const module = rendered ?? renderBffRuntime(options);
22
+ await fs.outputFile(path.join(directory, 'index.js'), module.code);
23
+ await fs.outputFile(path.join(directory, 'index.d.ts'), module.declaration);
24
+ }
25
+ export default runtimeGenerator;
26
+ export { renderBffRuntime };