@modern-js/bff-generator 2.4.16 → 2.4.18

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.
package/dist/index.js CHANGED
@@ -85065,7 +85065,6 @@ var require_downloadPackage = __commonJSMin((exports) => {
85065
85065
  if (response.status !== 200) {
85066
85066
  throw new Error(`download tar package get bad status code: ${response.status}`);
85067
85067
  }
85068
- const contentLength = Number(response.headers["content-length"]);
85069
85068
  const randomId = Math.floor(Math.random() * 1e4);
85070
85069
  const tempTgzFilePath = `${_os.default.tmpdir()}/temp-${randomId}.tgz`;
85071
85070
  const dest = _utils.fs.createWriteStream(tempTgzFilePath);
@@ -85078,9 +85077,6 @@ var require_downloadPackage = __commonJSMin((exports) => {
85078
85077
  resolve();
85079
85078
  });
85080
85079
  });
85081
- if ((await _utils.fs.stat(tempTgzFilePath)).size !== contentLength) {
85082
- throw new Error("download tar package get bad content length");
85083
- }
85084
85080
  await new Promise((resolve, reject) => {
85085
85081
  _utils.fs.createReadStream(tempTgzFilePath).pipe(_tar.default.x({
85086
85082
  strip: 1,
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "2.4.16",
14
+ "version": "2.4.18",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./src/index.ts",
17
17
  "main": "./dist/index.js",
@@ -21,17 +21,17 @@
21
21
  ],
22
22
  "devDependencies": {
23
23
  "@babel/runtime": "^7.18.0",
24
- "@modern-js/codesmith": "1.6.3",
25
- "@modern-js/codesmith-api-app": "1.6.3",
26
- "@modern-js/codesmith-api-json": "1.6.3",
24
+ "@modern-js/codesmith": "1.6.4",
25
+ "@modern-js/codesmith-api-app": "1.6.4",
26
+ "@modern-js/codesmith-api-json": "1.6.4",
27
27
  "@types/jest": "^27",
28
28
  "@types/node": "^14",
29
29
  "jest": "^27",
30
30
  "typescript": "^4",
31
- "@modern-js/generator-common": "2.4.16",
32
- "@modern-js/generator-utils": "2.4.16",
33
- "@scripts/build": "1.22.5",
34
- "@scripts/jest-config": "1.22.5"
31
+ "@modern-js/generator-common": "2.4.18",
32
+ "@modern-js/generator-utils": "2.4.18",
33
+ "@scripts/build": "1.22.7",
34
+ "@scripts/jest-config": "1.22.7"
35
35
  },
36
36
  "sideEffects": false,
37
37
  "modernConfig": {
package/src/index.ts ADDED
@@ -0,0 +1,269 @@
1
+ import path from 'path';
2
+ import {
3
+ fs,
4
+ getPackageVersion,
5
+ getModernPluginVersion,
6
+ isTsProject,
7
+ readTsConfigByFile,
8
+ } from '@modern-js/generator-utils';
9
+ import { GeneratorContext, GeneratorCore } from '@modern-js/codesmith';
10
+ import { AppAPI } from '@modern-js/codesmith-api-app';
11
+ import { JsonAPI } from '@modern-js/codesmith-api-json';
12
+ import {
13
+ BFFSchema,
14
+ BFFType,
15
+ i18n,
16
+ Framework,
17
+ Language,
18
+ FrameworkAppendTypeContent,
19
+ Solution,
20
+ } from '@modern-js/generator-common';
21
+
22
+ function isEmptyApiDir(apiDir: string) {
23
+ const files = fs.readdirSync(apiDir);
24
+ if (files.length === 0) {
25
+ return true;
26
+ }
27
+ return files.every(file => {
28
+ if (fs.statSync(path.join(apiDir, file)).isDirectory()) {
29
+ const childFiles = fs.readdirSync(path.join(apiDir, file));
30
+ return childFiles.length === 0;
31
+ }
32
+ return false;
33
+ });
34
+ }
35
+
36
+ export const handleTemplateFile = async (
37
+ context: GeneratorContext,
38
+ generator: GeneratorCore,
39
+ appApi: AppAPI,
40
+ ) => {
41
+ const jsonAPI = new JsonAPI(generator);
42
+
43
+ const ans = await appApi.getInputBySchema(BFFSchema, context.config);
44
+
45
+ const appDir = context.materials.default.basePath;
46
+ const apiDir = path.join(appDir, 'api');
47
+
48
+ if (fs.existsSync(apiDir) && !isEmptyApiDir(apiDir)) {
49
+ const files = fs.readdirSync(apiDir);
50
+ if (files.length > 0) {
51
+ generator.logger.warn("'api' is already exist");
52
+ throw Error("'api' is already exist");
53
+ }
54
+ }
55
+
56
+ const { bffType, framework } = ans;
57
+
58
+ const language = isTsProject(appDir) ? Language.TS : Language.JS;
59
+
60
+ if (language === Language.JS && framework === Framework.Nest) {
61
+ generator.logger.warn('nest not support js project');
62
+ throw Error('nest not support js project');
63
+ }
64
+
65
+ const getBffPluginVersion = (packageName: string) => {
66
+ return getModernPluginVersion(Solution.MWA, packageName, {
67
+ registry: context.config.registry,
68
+ distTag: context.config.distTag,
69
+ });
70
+ };
71
+
72
+ let updateInfo: Record<string, string> = {};
73
+
74
+ if (framework === Framework.Express || framework === Framework.Koa) {
75
+ updateInfo = {
76
+ [`devDependencies.@types/${
77
+ framework as string
78
+ }`]: `^${await getPackageVersion(`@types/${framework as string}`)}`,
79
+ };
80
+ }
81
+
82
+ if (framework === Framework.Nest) {
83
+ updateInfo = {
84
+ 'dependencies.@nestjs/core': `^${await getPackageVersion(
85
+ '@nestjs/core',
86
+ )}`,
87
+ 'dependencies.@nestjs/common': `^${await getPackageVersion(
88
+ '@nestjs/common',
89
+ )}`,
90
+ };
91
+ if (bffType === BFFType.Func) {
92
+ updateInfo['dependencies.express'] = `^${await getPackageVersion(
93
+ 'express',
94
+ )}`;
95
+ updateInfo[
96
+ 'devDependencies.@types/express'
97
+ ] = `^${await getPackageVersion('@types/express')}`;
98
+ }
99
+ } else {
100
+ updateInfo = {
101
+ ...updateInfo,
102
+ [`dependencies.${framework as string}`]: `^${await getPackageVersion(
103
+ framework as string,
104
+ )}`,
105
+ };
106
+ }
107
+
108
+ await jsonAPI.update(
109
+ context.materials.default.get(path.join(appDir, 'package.json')),
110
+ {
111
+ query: {},
112
+ update: {
113
+ $set: {
114
+ 'dependencies.@modern-js/plugin-bff': `${await getBffPluginVersion(
115
+ '@modern-js/plugin-bff',
116
+ )}`,
117
+ [`dependencies.@modern-js/plugin-${
118
+ framework as string
119
+ }`]: `${await getBffPluginVersion(
120
+ `@modern-js/plugin-${framework as string}`,
121
+ )}`,
122
+ ...updateInfo,
123
+ },
124
+ },
125
+ },
126
+ );
127
+
128
+ if (language === Language.TS) {
129
+ const tsconfigJSON = readTsConfigByFile(path.join(appDir, 'tsconfig.json'));
130
+
131
+ if (!(tsconfigJSON.include || []).includes('api')) {
132
+ await jsonAPI.update(
133
+ context.materials.default.get(path.join(appDir, 'tsconfig.json')),
134
+ {
135
+ query: {},
136
+ update: {
137
+ $set: {
138
+ include: [...(tsconfigJSON.include || []), 'api'],
139
+ },
140
+ },
141
+ },
142
+ );
143
+ }
144
+ }
145
+
146
+ if (bffType === BFFType.Func) {
147
+ if (language === Language.TS) {
148
+ await jsonAPI.update(
149
+ context.materials.default.get(path.join(appDir, 'tsconfig.json')),
150
+ {
151
+ query: {},
152
+ update: {
153
+ $set: {
154
+ 'compilerOptions.paths.@api/*': ['./api/*'],
155
+ },
156
+ },
157
+ },
158
+ );
159
+ }
160
+ await appApi.forgeTemplate(
161
+ 'templates/function/base/*',
162
+ undefined,
163
+ resourceKey =>
164
+ resourceKey
165
+ .replace('templates/function/base/', 'api/')
166
+ .replace('.handlebars', `.${language}`),
167
+ );
168
+ await appApi.forgeTemplate(
169
+ `templates/function/info/*`,
170
+ resourceKey => resourceKey.includes(language),
171
+ resourceKey =>
172
+ resourceKey
173
+ .replace('templates/function/info/', 'api/info/')
174
+ .replace('.handlebars', ``),
175
+ );
176
+ await appApi.forgeTemplate(
177
+ `templates/function/app/${language}/${
178
+ framework as string
179
+ }.${language}.handlebars`,
180
+ undefined,
181
+ resourceKey =>
182
+ resourceKey.replace(
183
+ `templates/function/app/${language}/${
184
+ framework as string
185
+ }.${language}.handlebars`,
186
+ `api/_app.${language}`,
187
+ ),
188
+ );
189
+ } else {
190
+ if (language === Language.TS) {
191
+ await jsonAPI.update(
192
+ context.materials.default.get(path.join(appDir, 'tsconfig.json')),
193
+ {
194
+ query: {},
195
+ update: {
196
+ $set: {
197
+ 'compilerOptions.paths.@api/*': ['./api/lambda/*'],
198
+ },
199
+ },
200
+ },
201
+ );
202
+ }
203
+ await appApi.forgeTemplate(
204
+ `templates/framework/lambda/*`,
205
+ undefined,
206
+ resourceKey =>
207
+ resourceKey
208
+ .replace(`templates/framework/`, 'api/')
209
+ .replace('.handlebars', `.${language}`),
210
+ );
211
+ await appApi.forgeTemplate(
212
+ `templates/framework/app/${framework as string}/**/*`,
213
+ resourceKey =>
214
+ framework === Framework.Egg || framework === Framework.Koa
215
+ ? resourceKey.includes(language)
216
+ : true,
217
+ resourceKey =>
218
+ resourceKey
219
+ .replace(`templates/framework/app/${framework as string}/`, 'api/')
220
+ .replace(
221
+ '.handlebars',
222
+ framework === Framework.Express ? `.${language}` : '',
223
+ ),
224
+ );
225
+ }
226
+
227
+ const appendTypeContent = FrameworkAppendTypeContent[framework as Framework];
228
+
229
+ if (appendTypeContent && language === Language.TS) {
230
+ const typePath = path.join(appDir, 'src', 'modern-app-env.d.ts');
231
+ if (fs.existsSync(typePath)) {
232
+ const npmrc = fs.readFileSync(typePath, 'utf-8');
233
+ if (!npmrc.includes(appendTypeContent)) {
234
+ fs.writeFileSync(typePath, `${npmrc}${appendTypeContent}\n`, 'utf-8');
235
+ }
236
+ } else {
237
+ fs.ensureFileSync(typePath);
238
+ fs.writeFileSync(typePath, appendTypeContent, 'utf-8');
239
+ }
240
+ }
241
+ };
242
+
243
+ export default async (context: GeneratorContext, generator: GeneratorCore) => {
244
+ const appApi = new AppAPI(context, generator);
245
+
246
+ const { locale } = context.config;
247
+ i18n.changeLanguage({ locale });
248
+ appApi.i18n.changeLanguage({ locale });
249
+
250
+ if (!(await appApi.checkEnvironment())) {
251
+ // eslint-disable-next-line no-process-exit
252
+ process.exit(1);
253
+ }
254
+
255
+ generator.logger.debug(`start run @modern-js/bff-generator`);
256
+ generator.logger.debug(`context=${JSON.stringify(context)}`);
257
+ generator.logger.debug(`context.data=${JSON.stringify(context.data)}`);
258
+
259
+ try {
260
+ await handleTemplateFile(context, generator, appApi);
261
+ } catch (e) {
262
+ // eslint-disable-next-line no-process-exit
263
+ process.exit(1);
264
+ }
265
+
266
+ await appApi.runInstall(undefined, { ignoreScripts: true });
267
+
268
+ generator.logger.debug(`forge @modern-js/bff-generator succeed `);
269
+ };