@bleedingdev/modern-js-plugin-bff-build-extensions 0.0.0 → 3.9.0-ultramodern.6

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 (38) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/client-artifacts.js +94 -0
  3. package/dist/cjs/compile.js +64 -0
  4. package/dist/cjs/cross-project.js +92 -0
  5. package/dist/cjs/generated-entries.js +96 -0
  6. package/dist/cjs/hono-client-codegen.js +107 -0
  7. package/dist/cjs/index.js +129 -0
  8. package/dist/cjs/server-global-vars.js +113 -0
  9. package/dist/esm/client-artifacts.mjs +53 -0
  10. package/dist/esm/compile.mjs +26 -0
  11. package/dist/esm/cross-project.mjs +44 -0
  12. package/dist/esm/generated-entries.mjs +58 -0
  13. package/dist/esm/hono-client-codegen.mjs +59 -0
  14. package/dist/esm/index.mjs +89 -0
  15. package/dist/esm/server-global-vars.mjs +72 -0
  16. package/dist/esm-node/client-artifacts.mjs +54 -0
  17. package/dist/esm-node/compile.mjs +27 -0
  18. package/dist/esm-node/cross-project.mjs +45 -0
  19. package/dist/esm-node/generated-entries.mjs +60 -0
  20. package/dist/esm-node/hono-client-codegen.mjs +61 -0
  21. package/dist/esm-node/index.mjs +91 -0
  22. package/dist/esm-node/server-global-vars.mjs +73 -0
  23. package/dist/types/client-artifacts.d.ts +10 -0
  24. package/dist/types/compile.d.ts +3 -0
  25. package/dist/types/cross-project.d.ts +11 -0
  26. package/dist/types/generated-entries.d.ts +4 -0
  27. package/dist/types/hono-client-codegen.d.ts +2 -0
  28. package/dist/types/index.d.ts +4 -0
  29. package/dist/types/server-global-vars.d.ts +6 -0
  30. package/package.json +104 -8
  31. package/src/client-artifacts.ts +87 -0
  32. package/src/compile.ts +39 -0
  33. package/src/cross-project.ts +72 -0
  34. package/src/generated-entries.ts +105 -0
  35. package/src/hono-client-codegen.ts +83 -0
  36. package/src/index.ts +128 -0
  37. package/src/server-global-vars.ts +145 -0
  38. package/README.md +0 -3
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ serializeServerGlobalVars: ()=>serializeServerGlobalVars,
32
+ transformServerGlobalVars: ()=>transformServerGlobalVars
33
+ });
34
+ const utils_namespaceObject = require("@modern-js/utils");
35
+ const core_namespaceObject = require("@swc/core");
36
+ const RELEASE_IDENTITY_GLOBAL_NAMES = [
37
+ 'ULTRAMODERN_BUILD_MARKER',
38
+ 'ULTRAMODERN_SOURCE_REVISION',
39
+ 'ULTRAMODERN_RELEASE_VERSION'
40
+ ];
41
+ const collectJavaScriptFiles = (directory)=>Promise.resolve().then(()=>utils_namespaceObject.fs.readdir(directory, {
42
+ withFileTypes: true
43
+ })).then((entries)=>Promise.all(entries.map((entry)=>{
44
+ const absolutePath = utils_namespaceObject.upath.join(directory, entry.name);
45
+ if (entry.isDirectory()) return collectJavaScriptFiles(absolutePath);
46
+ return /\.(?:c|m)?js$/u.test(entry.name) ? [
47
+ absolutePath
48
+ ] : [];
49
+ })).then((nested)=>nested.flat()));
50
+ const serializeServerGlobalVars = (options)=>{
51
+ const globalVars = (0, utils_namespaceObject.applyOptionsChain)({}, options, {
52
+ env: 'server',
53
+ target: 'node'
54
+ });
55
+ return Object.fromEntries(Object.entries(globalVars).map(([key, value])=>{
56
+ let serialized;
57
+ try {
58
+ serialized = JSON.stringify(value);
59
+ } catch (error) {
60
+ throw new Error(`source.globalVars["${key}"] cannot be serialized exactly for BFF compilation.`, {
61
+ cause: error
62
+ });
63
+ }
64
+ if (void 0 === serialized) throw new Error(`source.globalVars["${key}"] cannot be serialized exactly for BFF compilation.`);
65
+ return [
66
+ key,
67
+ serialized
68
+ ];
69
+ }));
70
+ };
71
+ const transformServerGlobalVars = (outputDirectories, globalVars)=>Promise.resolve().then(()=>{
72
+ if (0 === Object.keys(globalVars).length) return;
73
+ return Promise.all(outputDirectories.map((directory)=>utils_namespaceObject.fs.pathExists(directory).then((directoryExists)=>directoryExists ? directory : void 0))).then((existingDirectories)=>{
74
+ const filesPromise = Promise.all(existingDirectories.filter((directory)=>void 0 !== directory).map(collectJavaScriptFiles)).then((files)=>files.flat());
75
+ const releaseIdentityBanner = RELEASE_IDENTITY_GLOBAL_NAMES.every((name)=>Object.hasOwn(globalVars, name)) ? `${RELEASE_IDENTITY_GLOBAL_NAMES.map((name)=>`void ${globalVars[name]};`).join('')}\n` : '';
76
+ return filesPromise.then((files)=>Promise.all(files.map((filename)=>utils_namespaceObject.fs.readFile(filename, 'utf8').then((source)=>{
77
+ const sourceMapFilename = `${filename}.map`;
78
+ return utils_namespaceObject.fs.pathExists(sourceMapFilename).then((sourceMapExists)=>{
79
+ const inputSourceMapPromise = sourceMapExists ? utils_namespaceObject.fs.readFile(sourceMapFilename, 'utf8') : Promise.resolve(void 0);
80
+ return inputSourceMapPromise.then((inputSourceMap)=>(0, core_namespaceObject.transform)(`${releaseIdentityBanner}${source}`, {
81
+ filename,
82
+ inputSourceMap,
83
+ sourceMaps: sourceMapExists,
84
+ jsc: {
85
+ parser: {
86
+ syntax: "ecmascript"
87
+ },
88
+ preserveAllComments: true,
89
+ target: 'es2024',
90
+ transform: {
91
+ optimizer: {
92
+ globals: {
93
+ vars: globalVars
94
+ }
95
+ }
96
+ }
97
+ }
98
+ }).then((result)=>utils_namespaceObject.fs.writeFile(filename, result.code).then(()=>{
99
+ if (sourceMapExists && void 0 !== result.map && result.map.length > 0) return utils_namespaceObject.fs.writeFile(sourceMapFilename, result.map);
100
+ })));
101
+ });
102
+ }))));
103
+ }).then(()=>void 0);
104
+ });
105
+ exports.serializeServerGlobalVars = __webpack_exports__.serializeServerGlobalVars;
106
+ exports.transformServerGlobalVars = __webpack_exports__.transformServerGlobalVars;
107
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
108
+ "serializeServerGlobalVars",
109
+ "transformServerGlobalVars"
110
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
111
+ Object.defineProperty(exports, '__esModule', {
112
+ value: true
113
+ });
@@ -0,0 +1,53 @@
1
+ import { ApiRouter } from "@modern-js/bff-core";
2
+ import { buildOperationContractMap, deriveOperationVersion } from "@modern-js/server-runtime-extensions/bff-policy/node";
3
+ import { fs, upath } from "@modern-js/utils";
4
+ const BFF_REQUEST_RUNTIME = '@modern-js/runtime-extensions/request-policy';
5
+ function registerBffClientArtifacts(api, metadata) {
6
+ api.modifyBffClientArtifacts(async (context)=>{
7
+ const { generation } = context;
8
+ const config = api.getNormalizedConfig();
9
+ if ('effect' === api.getAppContext().bffRuntimeFramework) {
10
+ const { resolveEffectOperationContracts, resolveEffectEntryPaths } = await import("@modern-js/plugin-bff-extensions/effect-source-loader");
11
+ const { sourceEffectEntry, relativeEffectEntry } = resolveEffectEntryPaths({
12
+ appDir: generation.appDirectory,
13
+ apiDir: generation.apiDirectory,
14
+ effectEntry: config.bff?.effect?.entry
15
+ });
16
+ if (!sourceEffectEntry) throw new Error(`Cannot resolve Effect BFF entry in ${generation.apiDirectory}.`);
17
+ const operationContracts = await resolveEffectOperationContracts({
18
+ appDir: generation.appDirectory,
19
+ resourcePath: sourceEffectEntry,
20
+ prefix: generation.prefix,
21
+ requestId: generation.requestId
22
+ });
23
+ if (null === operationContracts) throw new Error(`Cannot resolve exported Effect HttpApi in ${sourceEffectEntry}.`);
24
+ metadata.set(generation, {
25
+ runtimeFramework: 'effect',
26
+ relativeEffectEntry,
27
+ operationContracts
28
+ });
29
+ } else {
30
+ const router = new ApiRouter({
31
+ appDir: generation.appDirectory,
32
+ apiDir: generation.apiDirectory,
33
+ lambdaDir: generation.lambdaDirectory,
34
+ prefix: generation.prefix,
35
+ httpMethodDecider: generation.httpMethodDecider,
36
+ isBuild: true
37
+ });
38
+ const packageJson = await fs.readJSON(upath.join(generation.appDirectory, 'package.json'));
39
+ const operationContracts = generation.existLambda ? buildOperationContractMap({
40
+ handlers: await router.getApiHandlers(),
41
+ requestId: generation.requestId,
42
+ operationVersion: deriveOperationVersion(packageJson.version)
43
+ }) : {};
44
+ metadata.set(generation, {
45
+ runtimeFramework: 'hono',
46
+ relativeEffectEntry: '',
47
+ operationContracts
48
+ });
49
+ }
50
+ return context;
51
+ });
52
+ }
53
+ export { BFF_REQUEST_RUNTIME, registerBffClientArtifacts };
@@ -0,0 +1,26 @@
1
+ import { serializeServerGlobalVars, transformServerGlobalVars } from "./server-global-vars.mjs";
2
+ function registerBffCompilation(api) {
3
+ const serialized = new WeakMap();
4
+ api.onBeforeBffCompile((context)=>{
5
+ serialized.set(context, serializeServerGlobalVars(api.getNormalizedConfig().source.globalVars));
6
+ });
7
+ api.onAfterBffCompile(async (context)=>{
8
+ const globals = serialized.get(context);
9
+ if (!globals) throw new Error('BFF compilation completed without its before hook.');
10
+ serialized.delete(context);
11
+ await transformServerGlobalVars([
12
+ ...context.outputDirectories
13
+ ], globals);
14
+ if ('effect' !== api.getAppContext().bffRuntimeFramework) return;
15
+ if (api.getNormalizedConfig().bff?.isCrossProjectServer === true) return;
16
+ const { bundleBuiltEffectEntryForNode } = await import("@modern-js/plugin-bff-extensions/effect-source-loader");
17
+ await bundleBuiltEffectEntryForNode({
18
+ appDir: context.appDirectory,
19
+ apiDir: context.apiDirectory,
20
+ distDir: context.distDirectory,
21
+ effectEntry: api.getNormalizedConfig().bff?.effect?.entry,
22
+ format: 'module' === context.moduleType ? 'esm' : 'cjs'
23
+ });
24
+ });
25
+ }
26
+ export { registerBffCompilation };
@@ -0,0 +1,44 @@
1
+ import "@modern-js/server-runtime-extensions/server-config";
2
+ import node_path from "node:path";
3
+ import { createCrossProjectApiPlugin } from "@modern-js/plugin-bff/cross-project";
4
+ function createCrossProjectBffPlugin(descriptor) {
5
+ return createCrossProjectApiPlugin({
6
+ ...descriptor.native,
7
+ modifyResolvedConfig: (resolvedConfig, { sdkDistDirectory, api })=>{
8
+ const config = api.getConfig();
9
+ const configuredRuntimeFramework = config?.bff?.runtimeFramework;
10
+ if (configuredRuntimeFramework && configuredRuntimeFramework !== descriptor.runtimeFramework) throw new Error(`[${descriptor.native.packageName}] Runtime framework mismatch for cross-project BFF. Detected "${configuredRuntimeFramework}", but producer SDK requires "${descriptor.runtimeFramework}".`);
11
+ const effectEntry = descriptor.relativeEffectEntry ? node_path.join(sdkDistDirectory, descriptor.relativeEffectEntry) : void 0;
12
+ api.updateAppContext({
13
+ ...effectEntry ? {
14
+ apiDirectory: node_path.dirname(effectEntry)
15
+ } : {},
16
+ bffRuntimeFramework: descriptor.runtimeFramework
17
+ });
18
+ resolvedConfig.bff ??= {};
19
+ resolvedConfig.bff.runtimeFramework = descriptor.runtimeFramework;
20
+ if (effectEntry) resolvedConfig.bff.effect = {
21
+ ...resolvedConfig.bff.effect,
22
+ entry: effectEntry
23
+ };
24
+ resolvedConfig.bff.requestId = resolvedConfig.bff.requestId || config?.bff?.requestId || descriptor.requestId || descriptor.native.packageName || 'default';
25
+ const policy = resolvedConfig.bff.crossProjectPolicy;
26
+ resolvedConfig.bff.crossProjectPolicy = {
27
+ ...policy,
28
+ enabled: policy?.enabled ?? true,
29
+ requireEnvelope: policy?.requireEnvelope ?? true,
30
+ requireOperationContext: policy?.requireOperationContext ?? true,
31
+ requireOperationContextDetails: policy?.requireOperationContextDetails ?? true,
32
+ requireOperationSchemaHash: policy?.requireOperationSchemaHash ?? true,
33
+ requireOperationVersion: policy?.requireOperationVersion ?? true,
34
+ allowUnknownOperations: policy?.allowUnknownOperations ?? false,
35
+ expectedOperationContracts: {
36
+ ...policy?.expectedOperationContracts,
37
+ ...descriptor.operationContracts
38
+ }
39
+ };
40
+ return resolvedConfig;
41
+ }
42
+ });
43
+ }
44
+ export { createCrossProjectBffPlugin };
@@ -0,0 +1,58 @@
1
+ import { pathToFileURL } from "node:url";
2
+ import { fs, upath } from "@modern-js/utils";
3
+ import { BFF_REQUEST_RUNTIME } from "./client-artifacts.mjs";
4
+ function registerBffGeneratedEntries(api, metadata) {
5
+ api.modifyBffGeneratedEntries(async (entries)=>{
6
+ const { generation } = entries;
7
+ const details = metadata.get(generation);
8
+ if (!details) throw new Error('BFF entries require completed operation contract collection.');
9
+ metadata.delete(generation);
10
+ const packageJson = await fs.readJSON(upath.join(generation.appDirectory, 'package.json'));
11
+ const runtimeSpecifier = api.getNormalizedConfig().bff?.runtimeCreateRequest || BFF_REQUEST_RUNTIME;
12
+ const dependencies = [
13
+ '@modern-js/plugin-bff-build-extensions',
14
+ '@modern-js/plugin-bff-extensions'
15
+ ];
16
+ const emitsClient = 'hono' === details.runtimeFramework && generation.apiFiles.length > 0;
17
+ if ('hono' === details.runtimeFramework && (runtimeSpecifier === BFF_REQUEST_RUNTIME || emitsClient && (generation.requestCreator || BFF_REQUEST_RUNTIME) === BFF_REQUEST_RUNTIME)) dependencies.push('@modern-js/runtime-extensions');
18
+ for (const name of dependencies){
19
+ const specifier = packageJson.dependencies?.[name] || packageJson.devDependencies?.[name] || fs.readJSONSync(require.resolve(`${name}/package.json`)).version;
20
+ entries.packageDependencies[name] = specifier;
21
+ }
22
+ const descriptor = {
23
+ native: {
24
+ packageName: packageJson.name,
25
+ prefix: generation.prefix,
26
+ relativeDistPath: upath.normalize(generation.relativeDistPath),
27
+ relativeApiPath: upath.relative(generation.appDirectory, generation.apiDirectory),
28
+ relativeLambdaPath: upath.relative(generation.appDirectory, generation.lambdaDirectory)
29
+ },
30
+ runtimeFramework: details.runtimeFramework,
31
+ relativeEffectEntry: details.relativeEffectEntry,
32
+ requestId: generation.requestId,
33
+ operationContracts: details.operationContracts
34
+ };
35
+ const isModule = 'module' === api.getAppContext().moduleType || 'module' === packageJson.type;
36
+ entries.plugin = {
37
+ code: isModule ? `import { createCrossProjectBffPlugin } from '@modern-js/plugin-bff-build-extensions/cross-project';\nexport const crossProjectApiPlugin = () => createCrossProjectBffPlugin(${JSON.stringify(descriptor)});\n` : `'use strict';\nconst { createCrossProjectBffPlugin } = require('@modern-js/plugin-bff-build-extensions/cross-project');\nexports.crossProjectApiPlugin = () => createCrossProjectBffPlugin(${JSON.stringify(descriptor)});\n`,
38
+ declaration: `import type { AppTools, CliPlugin } from '@modern-js/app-tools';
39
+ export declare const crossProjectApiPlugin: () => CliPlugin<AppTools>;
40
+ `
41
+ };
42
+ if ('effect' === details.runtimeFramework) {
43
+ entries.runtime = null;
44
+ return entries;
45
+ }
46
+ const runtime = JSON.stringify(runtimeSpecifier);
47
+ const esmRuntime = JSON.stringify(upath.isAbsolute(runtimeSpecifier) ? pathToFileURL(runtimeSpecifier).href : runtimeSpecifier);
48
+ entries.runtime = {
49
+ code: isModule ? `import { configure as _configure } from ${esmRuntime};\nimport { createProducerClient } from '@modern-js/plugin-bff-extensions/producer-runtime';\nexport const configure = createProducerClient(_configure, { requestId: ${JSON.stringify(generation.requestId)} });\nexport const initProducerClient = configure;\n` : `'use strict';\nconst { configure: _configure } = require(${runtime});\nconst { createProducerClient } = require('@modern-js/plugin-bff-extensions/producer-runtime');\nconst configure = createProducerClient(_configure, { requestId: ${JSON.stringify(generation.requestId)} });\nexports.configure = configure;\nexports.initProducerClient = configure;\n`,
50
+ declaration: `type Runtime = typeof import(${runtime});
51
+ export declare const initProducerClient: (options?: Parameters<Runtime['configure']>[0]) => ReturnType<Runtime['configure']>;
52
+ export declare const configure: typeof initProducerClient;
53
+ `
54
+ };
55
+ return entries;
56
+ });
57
+ }
58
+ export { registerBffGeneratedEntries };
@@ -0,0 +1,59 @@
1
+ import node_path from "node:path";
2
+ import { buildOperationContractMap, createOperationSchemaHash, deriveOperationVersion } from "@modern-js/server-runtime-extensions/bff-policy/node";
3
+ const REQUEST_RUNTIME = '@modern-js/runtime-extensions/request-policy';
4
+ const modifyClient = (draft, context)=>{
5
+ const { appDir, requestId } = context.options;
6
+ draft.requestCreator = context.options.requestCreator || REQUEST_RUNTIME;
7
+ let version;
8
+ try {
9
+ version = require(node_path.resolve(appDir, 'package.json')).version;
10
+ } catch {}
11
+ const operationVersion = deriveOperationVersion(version);
12
+ const normalizedRequestId = requestId || 'default';
13
+ const operationContracts = buildOperationContractMap({
14
+ handlers: [
15
+ ...context.handlerInfos
16
+ ],
17
+ requestId: normalizedRequestId,
18
+ operationVersion
19
+ });
20
+ const operationEntries = context.handlerInfos.map((handlerInfo)=>{
21
+ const httpMethod = handlerInfo.httpMethod.toUpperCase();
22
+ return {
23
+ name: handlerInfo.name,
24
+ httpMethod,
25
+ routePath: handlerInfo.routePath,
26
+ schemaHash: operationContracts[`${httpMethod}:${handlerInfo.routePath}`]?.schemaHash ?? ''
27
+ };
28
+ }).sort((a, b)=>`${a.routePath}:${a.httpMethod}:${a.name}`.localeCompare(`${b.routePath}:${b.httpMethod}:${b.name}`));
29
+ const schemaHash = createOperationSchemaHash(operationEntries, normalizedRequestId);
30
+ for (const { handlerInfo, optionProperties } of draft.handlers){
31
+ if ('upload' === handlerInfo.action && !requestId) continue;
32
+ const method = handlerInfo.httpMethod.toUpperCase();
33
+ const operationContext = {
34
+ operationId: handlerInfo.name,
35
+ routePath: handlerInfo.routePath,
36
+ method,
37
+ schemaHash: operationContracts[`${method}:${handlerInfo.routePath}`]?.schemaHash ?? '',
38
+ operationVersion
39
+ };
40
+ optionProperties.push(`operationContext: ${JSON.stringify(operationContext)}`);
41
+ }
42
+ if (requestId) {
43
+ draft.imports.push(`import * as requestRuntime from ${JSON.stringify(draft.requestCreator)};`, 'import { createProducerClient } from "@modern-js/plugin-bff-extensions/producer-runtime";');
44
+ draft.statements.push(`export const initProducerClient = (options = {}) => {
45
+ const configure = requestRuntime.configure;
46
+ if (typeof configure !== 'function') {
47
+ console.warn('[modernjs] Compatibility request creator path does not expose configure(); use default @modern-js/create-request or migrate the compatibility path.');
48
+ return undefined;
49
+ }
50
+ return createProducerClient(configure, { requestId: ${JSON.stringify(requestId)} })(options);
51
+ };`);
52
+ }
53
+ draft.statements.push(`export const operationVersion = ${String(operationVersion)};`, `export const operationSchemaHash = ${JSON.stringify(schemaHash)};`, `export const operationManifest = ${JSON.stringify({
54
+ operationVersion,
55
+ schemaHash,
56
+ operations: operationEntries
57
+ }, null, 2)};`);
58
+ };
59
+ export { modifyClient };
@@ -0,0 +1,89 @@
1
+ import "@modern-js/server-runtime-extensions/server-config";
2
+ import { bffPlugin } from "@modern-js/plugin-bff";
3
+ import { fs, upath } from "@modern-js/utils";
4
+ import { BFF_REQUEST_RUNTIME, registerBffClientArtifacts } from "./client-artifacts.mjs";
5
+ import { registerBffCompilation } from "./compile.mjs";
6
+ import { registerBffGeneratedEntries } from "./generated-entries.mjs";
7
+ const src_bffPlugin = ()=>({
8
+ name: '@modern-js/plugin-bff-build-extensions',
9
+ usePlugins: [
10
+ bffPlugin()
11
+ ],
12
+ pre: [
13
+ '@modern-js/plugin-bff'
14
+ ],
15
+ setup: (api)=>{
16
+ const hooks = api.getHooks();
17
+ for (const name of [
18
+ 'onBeforeBffCompile',
19
+ 'onAfterBffCompile',
20
+ 'modifyBffClientArtifacts',
21
+ 'modifyBffGeneratedEntries'
22
+ ])if ('function' != typeof hooks[name]?.tap) throw new Error(`Native BFF build hook ${name} is unavailable.`);
23
+ api.config(()=>({
24
+ bff: {
25
+ requestCreator: BFF_REQUEST_RUNTIME,
26
+ runtimeCreateRequest: BFF_REQUEST_RUNTIME,
27
+ clientCodegenPlugin: require.resolve('@modern-js/plugin-bff-build-extensions/hono-client-codegen')
28
+ }
29
+ }));
30
+ const runtimeFramework = api.getConfig()?.bff?.runtimeFramework;
31
+ if (void 0 !== runtimeFramework && 'hono' !== runtimeFramework && 'effect' !== runtimeFramework) throw new Error(`Unsupported Effect BFF runtime "${runtimeFramework}".`);
32
+ api.updateAppContext({
33
+ bffRuntimeFramework: runtimeFramework ?? 'effect'
34
+ });
35
+ api._internalServerPlugins(({ plugins })=>{
36
+ const nativePlugins = plugins.filter((plugin)=>'@modern-js/plugin-bff/server-plugin' === plugin.name);
37
+ if (1 !== nativePlugins.length) throw new Error('Expected exactly one native BFF server plugin.');
38
+ const native = nativePlugins[0];
39
+ const runtimeAdapters = native.options?.runtimeAdapters ?? {};
40
+ const effect = '@modern-js/plugin-bff-extensions/effect-adapter';
41
+ const honoRouteBinder = '@modern-js/plugin-bff-extensions/hono/node';
42
+ if (native.options?.honoRouteBinder !== void 0 && native.options.honoRouteBinder !== honoRouteBinder) throw new Error('The Hono BFF route binder is already configured.');
43
+ if (void 0 !== runtimeAdapters.effect && runtimeAdapters.effect !== effect) throw new Error('The Effect BFF runtime adapter is already configured.');
44
+ native.options = {
45
+ ...native.options,
46
+ honoRouteBinder,
47
+ runtimeAdapters: {
48
+ ...runtimeAdapters,
49
+ effect
50
+ }
51
+ };
52
+ return {
53
+ plugins
54
+ };
55
+ });
56
+ const metadata = new WeakMap();
57
+ registerBffCompilation(api);
58
+ registerBffClientArtifacts(api, metadata);
59
+ registerBffGeneratedEntries(api, metadata);
60
+ api.modifyBundlerChain(async (chain, { CHAIN_ID })=>{
61
+ if ('effect' !== api.getAppContext().bffRuntimeFramework) return;
62
+ const { appDirectory, apiDirectory } = api.getAppContext();
63
+ const bff = api.getNormalizedConfig().bff;
64
+ if (!fs.existsSync(apiDirectory) && bff?.effect?.entry === void 0) return;
65
+ const { resolveEffectEntryFile } = await import("@modern-js/plugin-bff-extensions/effect-source-loader");
66
+ const entry = resolveEffectEntryFile({
67
+ appDir: appDirectory,
68
+ apiDir: apiDirectory,
69
+ effectEntry: bff?.effect?.entry
70
+ });
71
+ if (!entry) throw new Error(`Cannot resolve Effect BFF entry in ${apiDirectory}.`);
72
+ const canonical = (file)=>upath.normalize(fs.existsSync(file) ? fs.realpathSync(file) : upath.resolve(file));
73
+ const entryPath = canonical(entry);
74
+ const isEntry = (resource)=>canonical(resource) === entryPath;
75
+ chain.module.rule(CHAIN_ID.RULE.JS).exclude.add(isEntry);
76
+ chain.module.rule('js-bff-api').exclude.add(isEntry);
77
+ chain.module.rule('js-bff-effect-entry').test(isEntry).use('effect-bff-loader').loader(require.resolve('@modern-js/plugin-bff-extensions/effect-source-loader/rspack-loader')).options({
78
+ appDir: appDirectory,
79
+ apiDir: apiDirectory,
80
+ effectEntry: entry,
81
+ prefix: Array.isArray(bff?.prefix) ? bff.prefix[0] : bff?.prefix || '/api',
82
+ requestId: bff?.requestId
83
+ });
84
+ });
85
+ }
86
+ });
87
+ const src = src_bffPlugin;
88
+ export default src;
89
+ export { src_bffPlugin as bffPlugin };
@@ -0,0 +1,72 @@
1
+ import { applyOptionsChain, fs, upath } from "@modern-js/utils";
2
+ import { transform } from "@swc/core";
3
+ const RELEASE_IDENTITY_GLOBAL_NAMES = [
4
+ 'ULTRAMODERN_BUILD_MARKER',
5
+ 'ULTRAMODERN_SOURCE_REVISION',
6
+ 'ULTRAMODERN_RELEASE_VERSION'
7
+ ];
8
+ const collectJavaScriptFiles = (directory)=>Promise.resolve().then(()=>fs.readdir(directory, {
9
+ withFileTypes: true
10
+ })).then((entries)=>Promise.all(entries.map((entry)=>{
11
+ const absolutePath = upath.join(directory, entry.name);
12
+ if (entry.isDirectory()) return collectJavaScriptFiles(absolutePath);
13
+ return /\.(?:c|m)?js$/u.test(entry.name) ? [
14
+ absolutePath
15
+ ] : [];
16
+ })).then((nested)=>nested.flat()));
17
+ const serializeServerGlobalVars = (options)=>{
18
+ const globalVars = applyOptionsChain({}, options, {
19
+ env: 'server',
20
+ target: 'node'
21
+ });
22
+ return Object.fromEntries(Object.entries(globalVars).map(([key, value])=>{
23
+ let serialized;
24
+ try {
25
+ serialized = JSON.stringify(value);
26
+ } catch (error) {
27
+ throw new Error(`source.globalVars["${key}"] cannot be serialized exactly for BFF compilation.`, {
28
+ cause: error
29
+ });
30
+ }
31
+ if (void 0 === serialized) throw new Error(`source.globalVars["${key}"] cannot be serialized exactly for BFF compilation.`);
32
+ return [
33
+ key,
34
+ serialized
35
+ ];
36
+ }));
37
+ };
38
+ const transformServerGlobalVars = (outputDirectories, globalVars)=>Promise.resolve().then(()=>{
39
+ if (0 === Object.keys(globalVars).length) return;
40
+ return Promise.all(outputDirectories.map((directory)=>fs.pathExists(directory).then((directoryExists)=>directoryExists ? directory : void 0))).then((existingDirectories)=>{
41
+ const filesPromise = Promise.all(existingDirectories.filter((directory)=>void 0 !== directory).map(collectJavaScriptFiles)).then((files)=>files.flat());
42
+ const releaseIdentityBanner = RELEASE_IDENTITY_GLOBAL_NAMES.every((name)=>Object.hasOwn(globalVars, name)) ? `${RELEASE_IDENTITY_GLOBAL_NAMES.map((name)=>`void ${globalVars[name]};`).join('')}\n` : '';
43
+ return filesPromise.then((files)=>Promise.all(files.map((filename)=>fs.readFile(filename, 'utf8').then((source)=>{
44
+ const sourceMapFilename = `${filename}.map`;
45
+ return fs.pathExists(sourceMapFilename).then((sourceMapExists)=>{
46
+ const inputSourceMapPromise = sourceMapExists ? fs.readFile(sourceMapFilename, 'utf8') : Promise.resolve(void 0);
47
+ return inputSourceMapPromise.then((inputSourceMap)=>transform(`${releaseIdentityBanner}${source}`, {
48
+ filename,
49
+ inputSourceMap,
50
+ sourceMaps: sourceMapExists,
51
+ jsc: {
52
+ parser: {
53
+ syntax: "ecmascript"
54
+ },
55
+ preserveAllComments: true,
56
+ target: 'es2024',
57
+ transform: {
58
+ optimizer: {
59
+ globals: {
60
+ vars: globalVars
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }).then((result)=>fs.writeFile(filename, result.code).then(()=>{
66
+ if (sourceMapExists && void 0 !== result.map && result.map.length > 0) return fs.writeFile(sourceMapFilename, result.map);
67
+ })));
68
+ });
69
+ }))));
70
+ }).then(()=>void 0);
71
+ });
72
+ export { serializeServerGlobalVars, transformServerGlobalVars };
@@ -0,0 +1,54 @@
1
+ import "node:module";
2
+ import { ApiRouter } from "@modern-js/bff-core";
3
+ import { buildOperationContractMap, deriveOperationVersion } from "@modern-js/server-runtime-extensions/bff-policy/node";
4
+ import { fs, upath } from "@modern-js/utils";
5
+ const BFF_REQUEST_RUNTIME = '@modern-js/runtime-extensions/request-policy';
6
+ function registerBffClientArtifacts(api, metadata) {
7
+ api.modifyBffClientArtifacts(async (context)=>{
8
+ const { generation } = context;
9
+ const config = api.getNormalizedConfig();
10
+ if ('effect' === api.getAppContext().bffRuntimeFramework) {
11
+ const { resolveEffectOperationContracts, resolveEffectEntryPaths } = await import("@modern-js/plugin-bff-extensions/effect-source-loader");
12
+ const { sourceEffectEntry, relativeEffectEntry } = resolveEffectEntryPaths({
13
+ appDir: generation.appDirectory,
14
+ apiDir: generation.apiDirectory,
15
+ effectEntry: config.bff?.effect?.entry
16
+ });
17
+ if (!sourceEffectEntry) throw new Error(`Cannot resolve Effect BFF entry in ${generation.apiDirectory}.`);
18
+ const operationContracts = await resolveEffectOperationContracts({
19
+ appDir: generation.appDirectory,
20
+ resourcePath: sourceEffectEntry,
21
+ prefix: generation.prefix,
22
+ requestId: generation.requestId
23
+ });
24
+ if (null === operationContracts) throw new Error(`Cannot resolve exported Effect HttpApi in ${sourceEffectEntry}.`);
25
+ metadata.set(generation, {
26
+ runtimeFramework: 'effect',
27
+ relativeEffectEntry,
28
+ operationContracts
29
+ });
30
+ } else {
31
+ const router = new ApiRouter({
32
+ appDir: generation.appDirectory,
33
+ apiDir: generation.apiDirectory,
34
+ lambdaDir: generation.lambdaDirectory,
35
+ prefix: generation.prefix,
36
+ httpMethodDecider: generation.httpMethodDecider,
37
+ isBuild: true
38
+ });
39
+ const packageJson = await fs.readJSON(upath.join(generation.appDirectory, 'package.json'));
40
+ const operationContracts = generation.existLambda ? buildOperationContractMap({
41
+ handlers: await router.getApiHandlers(),
42
+ requestId: generation.requestId,
43
+ operationVersion: deriveOperationVersion(packageJson.version)
44
+ }) : {};
45
+ metadata.set(generation, {
46
+ runtimeFramework: 'hono',
47
+ relativeEffectEntry: '',
48
+ operationContracts
49
+ });
50
+ }
51
+ return context;
52
+ });
53
+ }
54
+ export { BFF_REQUEST_RUNTIME, registerBffClientArtifacts };
@@ -0,0 +1,27 @@
1
+ import "node:module";
2
+ import { serializeServerGlobalVars, transformServerGlobalVars } from "./server-global-vars.mjs";
3
+ function registerBffCompilation(api) {
4
+ const serialized = new WeakMap();
5
+ api.onBeforeBffCompile((context)=>{
6
+ serialized.set(context, serializeServerGlobalVars(api.getNormalizedConfig().source.globalVars));
7
+ });
8
+ api.onAfterBffCompile(async (context)=>{
9
+ const globals = serialized.get(context);
10
+ if (!globals) throw new Error('BFF compilation completed without its before hook.');
11
+ serialized.delete(context);
12
+ await transformServerGlobalVars([
13
+ ...context.outputDirectories
14
+ ], globals);
15
+ if ('effect' !== api.getAppContext().bffRuntimeFramework) return;
16
+ if (api.getNormalizedConfig().bff?.isCrossProjectServer === true) return;
17
+ const { bundleBuiltEffectEntryForNode } = await import("@modern-js/plugin-bff-extensions/effect-source-loader");
18
+ await bundleBuiltEffectEntryForNode({
19
+ appDir: context.appDirectory,
20
+ apiDir: context.apiDirectory,
21
+ distDir: context.distDirectory,
22
+ effectEntry: api.getNormalizedConfig().bff?.effect?.entry,
23
+ format: 'module' === context.moduleType ? 'esm' : 'cjs'
24
+ });
25
+ });
26
+ }
27
+ export { registerBffCompilation };
@@ -0,0 +1,45 @@
1
+ import "node:module";
2
+ import "@modern-js/server-runtime-extensions/server-config";
3
+ import node_path from "node:path";
4
+ import { createCrossProjectApiPlugin } from "@modern-js/plugin-bff/cross-project";
5
+ function createCrossProjectBffPlugin(descriptor) {
6
+ return createCrossProjectApiPlugin({
7
+ ...descriptor.native,
8
+ modifyResolvedConfig: (resolvedConfig, { sdkDistDirectory, api })=>{
9
+ const config = api.getConfig();
10
+ const configuredRuntimeFramework = config?.bff?.runtimeFramework;
11
+ if (configuredRuntimeFramework && configuredRuntimeFramework !== descriptor.runtimeFramework) throw new Error(`[${descriptor.native.packageName}] Runtime framework mismatch for cross-project BFF. Detected "${configuredRuntimeFramework}", but producer SDK requires "${descriptor.runtimeFramework}".`);
12
+ const effectEntry = descriptor.relativeEffectEntry ? node_path.join(sdkDistDirectory, descriptor.relativeEffectEntry) : void 0;
13
+ api.updateAppContext({
14
+ ...effectEntry ? {
15
+ apiDirectory: node_path.dirname(effectEntry)
16
+ } : {},
17
+ bffRuntimeFramework: descriptor.runtimeFramework
18
+ });
19
+ resolvedConfig.bff ??= {};
20
+ resolvedConfig.bff.runtimeFramework = descriptor.runtimeFramework;
21
+ if (effectEntry) resolvedConfig.bff.effect = {
22
+ ...resolvedConfig.bff.effect,
23
+ entry: effectEntry
24
+ };
25
+ resolvedConfig.bff.requestId = resolvedConfig.bff.requestId || config?.bff?.requestId || descriptor.requestId || descriptor.native.packageName || 'default';
26
+ const policy = resolvedConfig.bff.crossProjectPolicy;
27
+ resolvedConfig.bff.crossProjectPolicy = {
28
+ ...policy,
29
+ enabled: policy?.enabled ?? true,
30
+ requireEnvelope: policy?.requireEnvelope ?? true,
31
+ requireOperationContext: policy?.requireOperationContext ?? true,
32
+ requireOperationContextDetails: policy?.requireOperationContextDetails ?? true,
33
+ requireOperationSchemaHash: policy?.requireOperationSchemaHash ?? true,
34
+ requireOperationVersion: policy?.requireOperationVersion ?? true,
35
+ allowUnknownOperations: policy?.allowUnknownOperations ?? false,
36
+ expectedOperationContracts: {
37
+ ...policy?.expectedOperationContracts,
38
+ ...descriptor.operationContracts
39
+ }
40
+ };
41
+ return resolvedConfig;
42
+ }
43
+ });
44
+ }
45
+ export { createCrossProjectBffPlugin };