@modern-js/plugin-bff 2.69.5 → 3.0.0-alpha.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 (76) hide show
  1. package/dist/cjs/cli.js +256 -272
  2. package/dist/cjs/constants.js +43 -34
  3. package/dist/cjs/index.js +55 -19
  4. package/dist/cjs/loader.js +69 -65
  5. package/dist/cjs/runtime/create-request/index.js +39 -29
  6. package/dist/cjs/runtime/hono/adapter.js +128 -126
  7. package/dist/cjs/runtime/hono/index.js +78 -30
  8. package/dist/cjs/runtime/hono/operators.js +64 -67
  9. package/dist/cjs/server.js +159 -165
  10. package/dist/cjs/utils/clientGenerator.js +204 -206
  11. package/dist/cjs/utils/createHonoRoutes.js +128 -144
  12. package/dist/cjs/utils/crossProjectApiPlugin.js +91 -81
  13. package/dist/cjs/utils/pluginGenerator.js +66 -54
  14. package/dist/cjs/utils/runtimeGenerator.js +67 -45
  15. package/dist/esm/cli.mjs +214 -0
  16. package/dist/esm/constants.mjs +11 -0
  17. package/dist/esm/loader.mjs +39 -0
  18. package/dist/esm/runtime/create-request/{index.js → index.mjs} +1 -5
  19. package/dist/esm/runtime/hono/adapter.mjs +95 -0
  20. package/dist/{esm-node/runtime/hono/index.js → esm/runtime/hono/index.mjs} +2 -4
  21. package/dist/esm/runtime/hono/operators.mjs +31 -0
  22. package/dist/esm/server.mjs +122 -0
  23. package/dist/esm/utils/clientGenerator.mjs +175 -0
  24. package/dist/esm/utils/createHonoRoutes.mjs +91 -0
  25. package/dist/esm/utils/crossProjectApiPlugin.mjs +34 -0
  26. package/dist/esm/utils/pluginGenerator.mjs +29 -0
  27. package/dist/esm/utils/runtimeGenerator.mjs +43 -0
  28. package/dist/esm-node/cli.mjs +214 -0
  29. package/dist/esm-node/constants.mjs +11 -0
  30. package/dist/esm-node/index.mjs +1 -0
  31. package/dist/esm-node/loader.mjs +39 -0
  32. package/dist/esm-node/runtime/create-request/{index.js → index.mjs} +1 -5
  33. package/dist/esm-node/runtime/hono/adapter.mjs +95 -0
  34. package/dist/{esm/runtime/hono/index.js → esm-node/runtime/hono/index.mjs} +3 -5
  35. package/dist/esm-node/runtime/hono/operators.mjs +31 -0
  36. package/dist/esm-node/server.mjs +122 -0
  37. package/dist/esm-node/utils/clientGenerator.mjs +175 -0
  38. package/dist/esm-node/utils/createHonoRoutes.mjs +91 -0
  39. package/dist/esm-node/utils/crossProjectApiPlugin.mjs +34 -0
  40. package/dist/esm-node/utils/pluginGenerator.mjs +29 -0
  41. package/dist/esm-node/utils/runtimeGenerator.mjs +43 -0
  42. package/dist/types/loader.d.ts +2 -2
  43. package/dist/types/runtime/hono/adapter.d.ts +3 -3
  44. package/dist/types/server.d.ts +2 -2
  45. package/dist/types/utils/runtimeGenerator.d.ts +2 -1
  46. package/package.json +53 -31
  47. package/rslib.config.mts +4 -0
  48. package/dist/cjs/helper.js +0 -48
  49. package/dist/esm/cli.js +0 -425
  50. package/dist/esm/constants.js +0 -14
  51. package/dist/esm/helper.js +0 -13
  52. package/dist/esm/index.js +0 -1
  53. package/dist/esm/loader.js +0 -75
  54. package/dist/esm/runtime/hono/adapter.js +0 -243
  55. package/dist/esm/runtime/hono/operators.js +0 -79
  56. package/dist/esm/server.js +0 -258
  57. package/dist/esm/utils/clientGenerator.js +0 -517
  58. package/dist/esm/utils/createHonoRoutes.js +0 -319
  59. package/dist/esm/utils/crossProjectApiPlugin.js +0 -49
  60. package/dist/esm/utils/pluginGenerator.js +0 -94
  61. package/dist/esm/utils/runtimeGenerator.js +0 -55
  62. package/dist/esm-node/cli.js +0 -246
  63. package/dist/esm-node/constants.js +0 -14
  64. package/dist/esm-node/helper.js +0 -14
  65. package/dist/esm-node/loader.js +0 -49
  66. package/dist/esm-node/runtime/hono/adapter.js +0 -103
  67. package/dist/esm-node/runtime/hono/operators.js +0 -46
  68. package/dist/esm-node/server.js +0 -142
  69. package/dist/esm-node/utils/clientGenerator.js +0 -192
  70. package/dist/esm-node/utils/createHonoRoutes.js +0 -120
  71. package/dist/esm-node/utils/crossProjectApiPlugin.js +0 -47
  72. package/dist/esm-node/utils/pluginGenerator.js +0 -31
  73. package/dist/esm-node/utils/runtimeGenerator.js +0 -35
  74. package/dist/types/helper.d.ts +0 -2
  75. package/types.d.ts +0 -3
  76. /package/dist/{esm-node/index.js → esm/index.mjs} +0 -0
@@ -1,192 +0,0 @@
1
- import path from "path";
2
- import { generateClient } from "@modern-js/bff-core";
3
- import { fs, logger } from "@modern-js/utils";
4
- const API_DIR = "api";
5
- const PLUGIN_DIR = "plugin";
6
- const RUNTIME_DIR = "runtime";
7
- const CLIENT_DIR = "client";
8
- const EXPORT_PREFIX = `./${API_DIR}/`;
9
- const TYPE_PREFIX = `${API_DIR}/`;
10
- const toPosixPath = (p) => p.replace(/\\/g, "/");
11
- const posixJoin = (...args) => toPosixPath(path.join(...args));
12
- async function readDirectoryFiles(appDirectory, directory, relativeDistPath) {
13
- const filesList = [];
14
- async function readFiles(currentPath) {
15
- const entries = await fs.readdir(currentPath, {
16
- withFileTypes: true
17
- });
18
- for (const entry of entries) {
19
- if (entry.name === "_app.ts")
20
- continue;
21
- const resourcePath = path.join(currentPath, entry.name);
22
- if (entry.isDirectory()) {
23
- await readFiles(resourcePath);
24
- } else {
25
- const source = await fs.readFile(resourcePath, "utf8");
26
- const relativePath = path.relative(directory, resourcePath);
27
- const parsedPath = path.parse(relativePath);
28
- const targetDir = posixJoin(`./${relativeDistPath}/${CLIENT_DIR}`, parsedPath.dir, `${parsedPath.name}.js`);
29
- const name = parsedPath.name;
30
- const absTargetDir = path.resolve(targetDir);
31
- const relativePathFromAppDirectory = path.relative(appDirectory, currentPath);
32
- const typesFilePath = posixJoin(`./${relativeDistPath}`, relativePathFromAppDirectory, `${name}.d.ts`);
33
- const relativeTargetDistDir = `./${typesFilePath}`;
34
- const exportKey = toPosixPath(path.join(parsedPath.dir, name));
35
- filesList.push({
36
- resourcePath,
37
- source,
38
- targetDir,
39
- name,
40
- absTargetDir,
41
- relativeTargetDistDir,
42
- exportKey
43
- });
44
- }
45
- }
46
- }
47
- await readFiles(directory);
48
- return filesList;
49
- }
50
- function mergePackageJson(packageJson, files, typesVersion, exports) {
51
- var _packageJson, _packageJson1;
52
- packageJson.files = [
53
- .../* @__PURE__ */ new Set([
54
- ...packageJson.files || [],
55
- ...files
56
- ])
57
- ];
58
- var _typesVersions;
59
- (_typesVersions = (_packageJson = packageJson).typesVersions) !== null && _typesVersions !== void 0 ? _typesVersions : _packageJson.typesVersions = {};
60
- const starTypes = packageJson.typesVersions["*"] || {};
61
- Object.keys(starTypes).forEach((k) => k.startsWith(TYPE_PREFIX) && delete starTypes[k]);
62
- packageJson.typesVersions["*"] = {
63
- ...starTypes,
64
- ...typesVersion["*"] || {}
65
- };
66
- var _exports;
67
- (_exports = (_packageJson1 = packageJson).exports) !== null && _exports !== void 0 ? _exports : _packageJson1.exports = {};
68
- Object.keys(packageJson.exports).forEach((k) => k.startsWith(EXPORT_PREFIX) && delete packageJson.exports[k]);
69
- Object.assign(packageJson.exports, exports);
70
- }
71
- async function writeTargetFile(absTargetDir, content) {
72
- await fs.mkdir(path.dirname(absTargetDir), {
73
- recursive: true
74
- });
75
- await fs.writeFile(absTargetDir, content);
76
- }
77
- async function setPackage(files, appDirectory, relativeDistPath) {
78
- try {
79
- const packagePath = path.resolve(appDirectory, "./package.json");
80
- const packageContent = await fs.readFile(packagePath, "utf8");
81
- const packageJson = JSON.parse(packageContent);
82
- const addFiles = [
83
- posixJoin(relativeDistPath, CLIENT_DIR, "**", "*"),
84
- posixJoin(relativeDistPath, RUNTIME_DIR, "**", "*"),
85
- posixJoin(relativeDistPath, PLUGIN_DIR, "**", "*")
86
- ];
87
- const typesVersions = {
88
- "*": files.reduce((acc, file) => {
89
- const typeFilePath = toPosixPath(`./${file.targetDir}`).replace("js", "d.ts");
90
- return {
91
- ...acc,
92
- [toPosixPath(`${TYPE_PREFIX}${file.exportKey}`)]: [
93
- typeFilePath
94
- ]
95
- };
96
- }, {
97
- [`${API_DIR}/*`]: [
98
- toPosixPath(`./${relativeDistPath}/${CLIENT_DIR}/*.d.ts`)
99
- ],
100
- [RUNTIME_DIR]: [
101
- toPosixPath(`./${relativeDistPath}/${RUNTIME_DIR}/index.d.ts`)
102
- ],
103
- [PLUGIN_DIR]: [
104
- toPosixPath(`./${relativeDistPath}/${PLUGIN_DIR}/index.d.ts`)
105
- ]
106
- })
107
- };
108
- const exports = files.reduce((acc, file) => {
109
- const exportKey = `${EXPORT_PREFIX}${file.exportKey}`;
110
- const jsFilePath = toPosixPath(`./${file.targetDir}`);
111
- return {
112
- ...acc,
113
- [toPosixPath(exportKey)]: {
114
- import: jsFilePath,
115
- types: toPosixPath(jsFilePath.replace(/\.js$/, ".d.ts"))
116
- }
117
- };
118
- }, {
119
- [toPosixPath(`./${API_DIR}/*`)]: {
120
- import: toPosixPath(`./${relativeDistPath}/${CLIENT_DIR}/*.js`),
121
- types: toPosixPath(`./${relativeDistPath}/${CLIENT_DIR}/*.d.ts`)
122
- },
123
- [toPosixPath(`./${PLUGIN_DIR}`)]: {
124
- import: toPosixPath(`./${relativeDistPath}/${PLUGIN_DIR}/index.js`),
125
- require: toPosixPath(`./${relativeDistPath}/${PLUGIN_DIR}/index.js`),
126
- types: toPosixPath(`./${relativeDistPath}/${PLUGIN_DIR}/index.d.ts`)
127
- },
128
- [toPosixPath(`./${RUNTIME_DIR}`)]: {
129
- import: toPosixPath(`./${relativeDistPath}/${RUNTIME_DIR}/index.js`),
130
- require: toPosixPath(`./${relativeDistPath}/${RUNTIME_DIR}/index.js`),
131
- types: toPosixPath(`./${relativeDistPath}/${RUNTIME_DIR}/index.d.ts`)
132
- }
133
- });
134
- mergePackageJson(packageJson, addFiles, typesVersions, exports);
135
- await fs.promises.writeFile(packagePath, JSON.stringify(packageJson, null, 2));
136
- } catch (error) {
137
- logger.error(`package.json update failed: ${error}`);
138
- }
139
- }
140
- async function copyFiles(from, to) {
141
- if (await fs.pathExists(from)) {
142
- await fs.copy(toPosixPath(from), toPosixPath(to));
143
- }
144
- }
145
- async function clientGenerator(draftOptions) {
146
- const sourceList = await readDirectoryFiles(draftOptions.appDir, draftOptions.lambdaDir, draftOptions.relativeDistPath);
147
- const getClitentCode = async (resourcePath, source) => {
148
- const warning = `The file ${resourcePath} is not allowd to be imported in src directory, only API definition files are allowed.`;
149
- if (!draftOptions.existLambda) {
150
- logger.warn(warning);
151
- return;
152
- }
153
- const options = {
154
- prefix: Array.isArray(draftOptions.prefix) ? draftOptions.prefix[0] : draftOptions.prefix,
155
- appDir: draftOptions.appDir,
156
- apiDir: draftOptions.apiDir,
157
- lambdaDir: draftOptions.lambdaDir,
158
- port: Number(draftOptions.port),
159
- source,
160
- resourcePath,
161
- target: "bundle",
162
- httpMethodDecider: draftOptions.httpMethodDecider,
163
- requestCreator: draftOptions.requestCreator
164
- };
165
- const { lambdaDir } = draftOptions;
166
- if (!resourcePath.startsWith(lambdaDir)) {
167
- logger.warn(warning);
168
- return;
169
- }
170
- const result = await generateClient(options);
171
- return result;
172
- };
173
- try {
174
- for (const source of sourceList) {
175
- const code = await getClitentCode(source.resourcePath, source.source);
176
- if (code === null || code === void 0 ? void 0 : code.value) {
177
- await writeTargetFile(source.absTargetDir, code.value);
178
- await copyFiles(source.relativeTargetDistDir, source.targetDir.replace(`js`, "d.ts"));
179
- }
180
- }
181
- logger.info(`Client bundle generate succeed`);
182
- } catch (error) {
183
- logger.error(`Client bundle generate failed: ${error}`);
184
- }
185
- setPackage(sourceList, draftOptions.appDir, draftOptions.relativeDistPath);
186
- }
187
- var clientGenerator_default = clientGenerator;
188
- export {
189
- copyFiles,
190
- clientGenerator_default as default,
191
- readDirectoryFiles
192
- };
@@ -1,120 +0,0 @@
1
- import { HttpMetadata, ResponseMetaType, ValidationError, isWithMetaHandler } from "@modern-js/bff-core";
2
- import { parse } from "@modern-js/create-request/qs";
3
- import typeIs from "type-is";
4
- const createHonoRoutes = (handlerInfos = []) => {
5
- return handlerInfos.map(({ routePath, handler, httpMethod }) => {
6
- const routeMiddlwares = Reflect.getMetadata("middleware", handler) || [];
7
- const honoHandler = createHonoHandler(handler);
8
- return {
9
- method: httpMethod.toLowerCase(),
10
- path: routePath,
11
- handler: routeMiddlwares.length > 0 ? [
12
- ...routeMiddlwares,
13
- honoHandler
14
- ] : honoHandler
15
- };
16
- });
17
- };
18
- const handleResponseMeta = (c, handler) => {
19
- const responseMeta = Reflect.getMetadata(HttpMetadata.Response, handler);
20
- if (Array.isArray(responseMeta)) {
21
- for (const meta of responseMeta) {
22
- switch (meta.type) {
23
- case ResponseMetaType.Headers:
24
- for (const [key, value] of Object.entries(meta.value)) {
25
- c.header(key, value);
26
- }
27
- break;
28
- case ResponseMetaType.Redirect:
29
- return c.redirect(meta.value);
30
- case ResponseMetaType.StatusCode:
31
- c.status(meta.value);
32
- break;
33
- default:
34
- break;
35
- }
36
- }
37
- }
38
- return null;
39
- };
40
- const createHonoHandler = (handler) => {
41
- return async (c) => {
42
- const input = await getHonoInput(c);
43
- if (isWithMetaHandler(handler)) {
44
- try {
45
- const response = handleResponseMeta(c, handler);
46
- if (response) {
47
- return response;
48
- }
49
- if (c.finalized)
50
- return;
51
- const result = await handler(input);
52
- if (result instanceof Response) {
53
- return result;
54
- }
55
- return result && typeof result === "object" ? c.json(result) : c.body(result);
56
- } catch (error) {
57
- if (error instanceof ValidationError) {
58
- c.status(error.status);
59
- return c.json({
60
- message: error.message
61
- });
62
- }
63
- throw error;
64
- }
65
- } else {
66
- var _routePath_match;
67
- const routePath = c.req.routePath;
68
- const paramNames = ((_routePath_match = routePath.match(/:\w+/g)) === null || _routePath_match === void 0 ? void 0 : _routePath_match.map((s) => s.slice(1))) || [];
69
- const params = Object.fromEntries(paramNames.map((name) => [
70
- name,
71
- input.params[name]
72
- ]));
73
- const args = Object.values(params).concat(input);
74
- const body = await handler(...args);
75
- if (c.finalized) {
76
- return await Promise.resolve();
77
- }
78
- if (typeof body !== "undefined") {
79
- if (body instanceof Response) {
80
- return body;
81
- }
82
- return c.json(body);
83
- }
84
- }
85
- };
86
- };
87
- const getHonoInput = async (c) => {
88
- const draft = {
89
- params: c.req.param(),
90
- query: parse(c.req.query()),
91
- headers: c.req.header(),
92
- cookies: c.req.header("cookie")
93
- };
94
- try {
95
- const contentType = c.req.header("content-type") || "";
96
- if (typeIs.is(contentType, [
97
- "application/json"
98
- ])) {
99
- draft.data = await c.req.json();
100
- } else if (typeIs.is(contentType, [
101
- "multipart/form-data"
102
- ])) {
103
- draft.formData = await c.req.parseBody();
104
- } else if (typeIs.is(contentType, [
105
- "application/x-www-form-urlencoded"
106
- ])) {
107
- draft.formUrlencoded = await c.req.parseBody();
108
- } else {
109
- draft.body = await c.req.json();
110
- }
111
- } catch (error) {
112
- draft.body = null;
113
- }
114
- return draft;
115
- };
116
- var createHonoRoutes_default = createHonoRoutes;
117
- export {
118
- createHonoHandler,
119
- createHonoRoutes_default as default
120
- };
@@ -1,47 +0,0 @@
1
- import path from "path";
2
- const PACKAGE_NAME = "{packageName}";
3
- const PREFIX = "{prefix}";
4
- const API_DIR = "{apiDirectory}";
5
- const LAMBDA_DIR = "{lambdaDirectory}";
6
- const DIST_DIR = "{distDirectory}";
7
- const NODE_MODULES = "node_modules";
8
- const crossProjectApiPlugin = () => ({
9
- name: "@modern-js/plugin-independent-bff",
10
- post: [
11
- "@modern-js/plugin-bff"
12
- ],
13
- setup: (api) => {
14
- return {
15
- config() {
16
- const { appDirectory: originAppDirectory } = api.useAppContext();
17
- const sdkPath = path.join(originAppDirectory, NODE_MODULES, PACKAGE_NAME);
18
- const sdkDistPath = path.join(sdkPath, DIST_DIR);
19
- const apiDirectory = path.join(sdkDistPath, API_DIR);
20
- const lambdaDirectory = path.resolve(sdkDistPath, LAMBDA_DIR);
21
- const appContext = api.useAppContext();
22
- api.setAppContext({
23
- ...appContext,
24
- apiDirectory,
25
- lambdaDirectory
26
- });
27
- const config = api.useConfigContext();
28
- config.bff = {
29
- ...config.bff,
30
- prefix: PREFIX,
31
- isCrossProjectServer: true
32
- };
33
- return {};
34
- }
35
- };
36
- }
37
- });
38
- var crossProjectApiPlugin_default = crossProjectApiPlugin;
39
- export {
40
- API_DIR,
41
- DIST_DIR,
42
- LAMBDA_DIR,
43
- PACKAGE_NAME,
44
- PREFIX,
45
- crossProjectApiPlugin,
46
- crossProjectApiPlugin_default as default
47
- };
@@ -1,31 +0,0 @@
1
- import path from "path";
2
- import { fs, logger } from "@modern-js/utils";
3
- import { API_DIR, DIST_DIR, LAMBDA_DIR, PACKAGE_NAME, PREFIX } from "./crossProjectApiPlugin";
4
- function replaceContent(source, packageName, prefix, relativeDistPath, relativeApiPath, relativeLambdaPath) {
5
- const updatedSource = source.replace(new RegExp(PACKAGE_NAME, "g"), packageName).replace(new RegExp(PREFIX, "g"), prefix).replace(new RegExp(DIST_DIR, "g"), relativeDistPath).replace(new RegExp(API_DIR, "g"), relativeApiPath).replace(new RegExp(LAMBDA_DIR, "g"), relativeLambdaPath);
6
- return updatedSource;
7
- }
8
- async function pluginGenerator({ prefix, appDirectory, relativeDistPath, relativeApiPath, relativeLambdaPath }) {
9
- try {
10
- const packageContent = await fs.readFile(path.resolve(appDirectory, "./package.json"), "utf8");
11
- const packageJson = JSON.parse(packageContent);
12
- const pluginDir = path.resolve(appDirectory, `./${relativeDistPath}`, "plugin");
13
- const pluginPath = path.join(pluginDir, "index.js");
14
- const pluginTemplate = await fs.readFile(path.resolve(__dirname, "crossProjectApiPlugin.js"), "utf8");
15
- const updatedPlugin = replaceContent(pluginTemplate, packageJson.name, prefix, relativeDistPath, relativeApiPath, relativeLambdaPath);
16
- await fs.ensureFile(pluginPath);
17
- await fs.writeFile(pluginPath, updatedPlugin);
18
- const typeContent = `import type { AppTools, CliPlugin } from '@modern-js/app-tools';
19
- export declare const crossProjectApiPlugin: () => CliPlugin<AppTools>`;
20
- const pluginTypePath = path.join(pluginDir, "index.d.ts");
21
- await fs.ensureFile(pluginTypePath);
22
- await fs.writeFile(pluginTypePath, typeContent);
23
- logger.info("Api plugin generate succeed");
24
- } catch (error) {
25
- logger.error("Api plugin generate failed:", error);
26
- }
27
- }
28
- var pluginGenerator_default = pluginGenerator;
29
- export {
30
- pluginGenerator_default as default
31
- };
@@ -1,35 +0,0 @@
1
- import path from "path";
2
- import { fs } from "@modern-js/utils";
3
- async function runtimeGenerator({ runtime, appDirectory, relativeDistPath }) {
4
- const pluginDir = path.resolve(appDirectory, `./${relativeDistPath}`, "runtime");
5
- const source = `import { configure as _configure } from '${runtime}'
6
- const configure = (options) => {
7
- return _configure({
8
- ...options,
9
- requestId: '${process.env.npm_package_name}',
10
- });
11
- }
12
- export { configure }
13
- `;
14
- const pluginPath = path.join(pluginDir, "index.js");
15
- await fs.ensureFile(pluginPath);
16
- await fs.writeFile(pluginPath, source);
17
- const tsSource = `type IOptions<F = typeof fetch> = {
18
- request?: F;
19
- interceptor?: (request: F) => F;
20
- allowedHeaders?: string[];
21
- setDomain?: (ops?: {
22
- target: 'node' | 'browser';
23
- requestId: string;
24
- }) => string;
25
- requestId?: string;
26
- };
27
- export declare const configure: (options: IOptions) => void;`;
28
- const pluginTypePath = path.join(pluginDir, "index.d.ts");
29
- await fs.ensureFile(pluginTypePath);
30
- await fs.writeFile(pluginTypePath, tsSource);
31
- }
32
- var runtimeGenerator_default = runtimeGenerator;
33
- export {
34
- runtimeGenerator_default as default
35
- };
@@ -1,2 +0,0 @@
1
- declare const registerModernRuntimePath: (internalDirectory: string) => () => void;
2
- export { registerModernRuntimePath };
package/types.d.ts DELETED
@@ -1,3 +0,0 @@
1
- declare module '@modern-js/runtime/bff' {
2
- export * from '@modern-js/create-request';
3
- }
File without changes