mushroom-cli 1.2.0-alpha.9 → 1.2.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 (52) hide show
  1. package/README.md +199 -161
  2. package/dist/check-update.js +6 -0
  3. package/dist/common.js +280 -0
  4. package/dist/config.js +394 -0
  5. package/dist/docs/bootstrap-theme.min.css +6 -0
  6. package/dist/docs/bootstrap.min.css +6 -0
  7. package/dist/docs/bootstrap.min.js +7 -0
  8. package/dist/docs/doc-mt.js +633 -0
  9. package/dist/docs/docs.html +5380 -0
  10. package/{docs → dist/docs}/docs.v2.html +5205 -5065
  11. package/dist/docs/docs.v2.js +2036 -0
  12. package/dist/docs/jquery.min.js +4 -0
  13. package/dist/docs/mt-dom-1.0.js +1398 -0
  14. package/dist/docs/mt.extension.js +199 -0
  15. package/dist/gen/gen-api-docs-v1.js +110 -0
  16. package/dist/gen/gen-api-docs.js +327 -0
  17. package/{gen → dist/gen}/gen-csharp.js +1256 -1399
  18. package/{gen → dist/gen}/gen-db-docs.js +204 -222
  19. package/{gen → dist/gen}/gen-js-driver-tarball.js +81 -101
  20. package/{gen → dist/gen}/gen-js-driver.js +116 -133
  21. package/dist/gen/gen-ts-driver.js +600 -0
  22. package/{gen.js → dist/gen.js} +109 -124
  23. package/{help.js → dist/help.js} +53 -55
  24. package/dist/init/init-json.js +92 -0
  25. package/dist/init/init-netcore.js +30 -0
  26. package/dist/init.js +23 -0
  27. package/dist/master-file/master-file.js +185 -0
  28. package/dist/merge.js +70 -0
  29. package/dist/mr.js +77 -0
  30. package/dist/types.js +1 -0
  31. package/dist/update/tsCode.js +82 -0
  32. package/dist/update.js +20 -0
  33. package/package.json +64 -29
  34. package/check-update.js +0 -9
  35. package/common.js +0 -273
  36. package/config.js +0 -445
  37. package/docs/doc-mt.js +0 -523
  38. package/docs/docs.html +0 -5190
  39. package/docs/docs.v2.js +0 -1558
  40. package/docs/mt-dom-1.0.js +0 -1268
  41. package/docs/mt.extension.js +0 -174
  42. package/gen/gen-api-docs-v1.js +0 -125
  43. package/gen/gen-api-docs.js +0 -298
  44. package/gen/gen-ts-driver.js +0 -471
  45. package/init/init-json.js +0 -106
  46. package/init/init-netcore.js +0 -32
  47. package/init.js +0 -28
  48. package/master-file/master-file.js +0 -234
  49. package/merge.js +0 -84
  50. package/mr.js +0 -82
  51. package/update/tsCode.js +0 -20
  52. package/update.js +0 -24
@@ -1,471 +0,0 @@
1
- const fs = require("fs");
2
- const common = require("../common.js");
3
-
4
- function isAllowCache(actions, defaultValue) {
5
- let result = defaultValue;
6
- for (let i = 0; i < actions.length; i++) {
7
- const action = actions[i];
8
-
9
- if (!action ||
10
- !action.cache ||
11
- !action.cache.client ||
12
- !action.cache.client.policy ||
13
- action.cache.client.policy === "unset")
14
- continue;
15
-
16
- if (action.cache.client.policy === "disabled")
17
- return false;
18
-
19
- if (action.cache.client.policy === "allow" || action.cache.client.policy === "required")
20
- result = true;
21
- }
22
- return result;
23
- }
24
-
25
- function toVietnameseNonTongue(str) {
26
- const signText = "ăâđêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềểễệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵýĂÂĐÐÊÔƠƯÀẢÃẠÁẰẲẴẶẮẦẨẪẬẤÈẺẼẸÉỀỂỄỆẾÌỈĨỊÍÒỎÕỌÓỒỔỖỘỐỜỞỠỢỚÙỦŨỤÚỪỬỮỰỨỲỶỸỴÝ";
27
- const unsignedText = "aadeoouaaaaaaaaaaaaaaaeeeeeeeeeeiiiiiooooooooooooooouuuuuuuuuuyyyyyAADDEOOUAAAAAAAAAAAAAAAEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOUUUUUUUUUUYYYYY";
28
- var returnValue = "";
29
- for (let i = 0; i < str.length; i++) {
30
- const index = signText.indexOf(str.charAt(i));
31
- returnValue += index !== -1 ? unsignedText.charAt(index) : str.charAt(i);
32
- }
33
- return returnValue;
34
- }
35
-
36
- function toTypeScriptClassName(str) {
37
- if (!str)
38
- return "_";
39
- const name = toVietnameseNonTongue(str).replace(/\W/g, "_");
40
- const c = name.charAt(0);
41
- return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substring(1);
42
- }
43
-
44
- function getCSharpTypeFromMushroomType(type) {
45
- switch (type) {
46
- case "string":
47
- return "string";
48
- case "object":
49
- case "array":
50
- return "";
51
- case "boolean":
52
- return "boolean";
53
- case "integer":
54
- case "long":
55
- case "double":
56
- return "number";
57
- case "datetime":
58
- return "ISODateValue";
59
- case "IdRef":
60
- case "AutoId":
61
- return "IdValue";
62
- }
63
- return "UNKNOWN_TYPE_" + type;
64
- }
65
-
66
- function generateTypescriptClass(objectDefination, indent, options) {
67
- if (!indent) indent = "";
68
- let code = "{\n";
69
- for (let fieldName in objectDefination) {
70
- const optionalMark = options?.checkRequired && objectDefination[fieldName].required ? "" : "?";
71
- if (objectDefination[fieldName].type == "object") {
72
- code += `${indent} ${fieldName}${optionalMark}: ${generateTypescriptClass(objectDefination[fieldName].fields, indent + " ")},
73
- `;
74
- }
75
- else if (objectDefination[fieldName].type == "array") {
76
- if (objectDefination[fieldName].items.type == "object") {
77
- code += `${indent} ${fieldName}${optionalMark}: ${generateTypescriptClass(objectDefination[fieldName].items.fields, indent + " ")}[],
78
- `;
79
- }
80
- else {
81
- code += `${indent} ${fieldName}${optionalMark}: ${getCSharpTypeFromMushroomType(objectDefination[fieldName].items.type)}[],
82
- `;
83
- }
84
- }
85
- else {
86
- code += `${indent} ${fieldName}${optionalMark}: ${getCSharpTypeFromMushroomType(objectDefination[fieldName].type)},
87
- `;
88
- }
89
- }
90
- code += indent + "}";
91
- return code;
92
- }
93
-
94
- function generateTypescriptClassFromViewParameters(parameters) {
95
- if (Array.isArray(parameters)){
96
- return '{\n' + parameters.map(p => ` ${p.field}${p.validation?.required && p.defaultValue === undefined ? "" : "?"}: ${getCSharpTypeFromMushroomType(p.type || "string")}${p.isArray ? "[]" : ""}`).join(',\n') + '\n}';
97
- }
98
- return '{}';
99
- }
100
-
101
- function genTypescriptDriverString(aliasProject, source) {
102
- if (!aliasProject) {
103
- return "";
104
- }
105
-
106
- const entities = common.getEntities(source, aliasProject.allowRoles);
107
-
108
- let extensionsImportLines = [];
109
- let extensionsExportLines = [];
110
- let extensionsTypes = [];
111
- let extensionsCodeLines = [];
112
-
113
- if (Array.isArray(aliasProject.features)) {
114
- if (aliasProject.features.includes("auth")) {
115
- extensionsImportLines.push('import * as AuthExtension from "mushroomjs-auth";');
116
- extensionsExportLines.push('File: FileExtension');
117
- extensionsTypes.push("AuthExtension.IMushroomAuth & ");
118
- extensionsCodeLines.push("AuthExtension.useAuth(AuthExtension.AuthLocalStorage, mushroom);");
119
- }
120
- if (aliasProject.features.includes("file")) {
121
- extensionsImportLines.push('import * as FileExtension from "mushroomjs-file";');
122
- extensionsExportLines.push('Auth: AuthExtension');
123
- extensionsTypes.push("FileExtension.IMushroomFile & ");
124
- extensionsCodeLines.push("FileExtension.useFile(mushroom);");
125
- }
126
- }
127
-
128
- let code = `import mushroom, { defineAsyncResource, defineAsyncView, fireEvent, createRestfulAsyncFunction, IdType, IMushroom, Mushroom, MushroomRequest, MushroomRequestSetting, MushroomRestfulRequest, MushroomResponse, MushroomResponseDataType, MushroomResourceBase, MushroomListResource, MushroomFindByIdResource, MushroomCreateResource, MushroomBatchCreateResource, MushroomUpdateResource, MushroomBatchUpdateResource, MushroomPartialUpdateResource, MushroomDeleteResource, MushroomBatchDeleteResource, MushroomExtensibleResource, MushroomViewFunction, MushroomError, IMushroomOfflineResponse, MushroomOfflineResponse, MushroomOfflineResponseState } from "mushroomjs";
129
- ${extensionsImportLines.join("\n")}
130
- export * from "mushroomjs";
131
- export const extensions = {
132
- ${extensionsExportLines.join(",\n ")}
133
- };
134
-
135
- export type ISODateValue = string | Date;
136
- export type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoIncLong" ? "number" : "string"};
137
-
138
- `;
139
- let iApiClassBody = "";
140
- for (let entityName in entities) {
141
- if (!entities.hasOwnProperty(entityName))
142
- continue;
143
-
144
- const entity = entities[entityName];
145
- const typescriptClassName = toTypeScriptClassName(entityName);
146
- code += `export interface ${typescriptClassName} ${generateTypescriptClass(entity.fields)};
147
- `;
148
-
149
-
150
- const actions = {};
151
- iApiClassBody += ` ${entityName}: MushroomResourceBase`;
152
- let customMethodCode = "";
153
- for (const actionName in entity.actions) {
154
- if (!entity.actions.hasOwnProperty(actionName))
155
- continue;
156
-
157
- actions[actionName] = {
158
- clientCache: (actionName === "findById" || actionName === "findMany") && isAllowCache(entity.actions[actionName], true) ? true : undefined,
159
- includeTotal: actionName === "findMany" && entity.actions[actionName].some(a => a.includeTotal) ? true: undefined,
160
- offlineMode: entity.actions[actionName].some(a => a.offlineMode === "disallow")
161
- ? "disallow"
162
- : !entity.actions[actionName].length || entity.actions[actionName].some(a => a.offlineMode === "allow")
163
- ? "allow"
164
- : undefined
165
- };
166
-
167
- switch (actionName) {
168
- case "findMany": {
169
- iApiClassBody += ` & MushroomListResource<${typescriptClassName}>`;
170
- break;
171
- }
172
- case "findById": {
173
- iApiClassBody += ` & MushroomFindByIdResource<${typescriptClassName}>`;
174
- break;
175
- }
176
- case "createOne": {
177
- iApiClassBody += ` & MushroomCreateResource<${typescriptClassName}>`;
178
- break;
179
- }
180
- case "createMany": {
181
- iApiClassBody += ` & MushroomBatchCreateResource<${typescriptClassName}>`;
182
- break;
183
- }
184
- case "updateOne": {
185
- iApiClassBody += ` & MushroomUpdateResource<${typescriptClassName}>`;
186
- break;
187
- }
188
- case "updateMany": {
189
- iApiClassBody += ` & MushroomBatchUpdateResource<${typescriptClassName}>`;
190
- break;
191
- }
192
- case "updatePartially": {
193
- iApiClassBody += ` & MushroomPartialUpdateResource<${typescriptClassName}>`;
194
- break;
195
- }
196
- case "deleteOne": {
197
- iApiClassBody += " & MushroomDeleteResource";
198
- break;
199
- }
200
- case "deleteMany": {
201
- iApiClassBody += " & MushroomBatchDeleteResource";
202
- break;
203
- }
204
- default: {
205
- if (actionName.indexOf("_raw_http_method_") === 0) {
206
- customMethodCode += ` ${actionName.substring("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
207
- `;
208
- break;
209
- }
210
- else {
211
- console.warn(`Unknown action name: ${entityName}.${actionName}`);
212
- break;
213
- }
214
- }
215
- }
216
- }
217
-
218
- if (customMethodCode) {
219
- code += `export interface ${typescriptClassName}$CustomMethodResource {
220
- ${customMethodCode}}
221
- `;
222
- iApiClassBody += ` & ${typescriptClassName}$CustomMethodResource`;
223
- }
224
-
225
- const views = {};
226
- let viewCode = "";
227
- for (const viewName in entity.views) {
228
- if (!entity.views.hasOwnProperty(viewName)) continue;
229
-
230
- const viewRoles = entity.views[viewName];
231
- if (!Array.isArray(viewRoles) || !viewRoles.length) continue;
232
-
233
- views[viewName] = { clientCache: true };
234
-
235
- const viewParameterTypes = viewRoles.map(view => {
236
- const inputType = `${typescriptClassName}$ViewsResource_${viewName}View_${view.grant === "*" ? "" : toTypeScriptClassName(view.grant)}Parameters`;
237
- const outputType = view.codeHint?.output ? `${typescriptClassName}$ViewsResource_${viewName}View_${view.grant === "*" ? "" : toTypeScriptClassName(view.grant)}Result` : 'any';
238
- code += `export interface ${inputType} ${generateTypescriptClassFromViewParameters(view.parameters)};
239
- `;
240
- if (view.codeHint?.output)
241
- code += `export interface ${outputType} ${generateTypescriptClass(view.codeHint.output.fields, undefined, {checkRequired: true})};
242
- `;
243
- return `MushroomViewFunction<${outputType}, ${inputType}>`;
244
- });
245
- viewCode += `
246
- ${viewName}Async: ${viewParameterTypes.join(' | ')},`;
247
- }
248
-
249
- if (viewCode) {
250
- code += `export interface ${typescriptClassName}$ViewsResource {
251
- views: {${viewCode}
252
- }
253
- }
254
- `;
255
- iApiClassBody += ` & ${typescriptClassName}$ViewsResource`;
256
- }
257
-
258
- iApiClassBody +=`,
259
- `;
260
-
261
- code += `defineAsyncResource<${typescriptClassName}>(${JSON.stringify({ name: entityName, actions: actions, views: views })});
262
-
263
- `;
264
- }
265
-
266
- code += `
267
- mushroom.$using(${JSON.stringify(common.getRootUrl(source))});
268
-
269
- (function(){
270
- ${extensionsCodeLines.join('\n')}
271
- })();
272
-
273
- export interface IApi extends IMushroom {
274
- ${iApiClassBody}};
275
-
276
- export type Api = ${extensionsTypes.join('')}IApi;
277
-
278
- export default mushroom as Api;`;
279
-
280
- return code;
281
- }
282
-
283
- function genDtsString(aliasProject, source) {
284
- if (!aliasProject) {
285
- return "";
286
- }
287
-
288
- const entities = common.getEntities(source, aliasProject.allowRoles);
289
-
290
- let extensionsImportLines = [];
291
- let extensionsExportLines = [];
292
- let extensionsTypes = [];
293
-
294
- if (Array.isArray(aliasProject.features)) {
295
- if (aliasProject.features.includes("auth")) {
296
- extensionsImportLines.push('import * as AuthExtension from "mushroomjs-auth";');
297
- extensionsExportLines.push('Auth: AuthExtension');
298
- extensionsTypes.push("AuthExtension.IMushroomAuth & ");
299
- }
300
- if (aliasProject.features.includes("file")) {
301
- extensionsImportLines.push('import * as FileExtension from "mushroomjs-file";');
302
- extensionsExportLines.push('File: FileExtension');
303
- extensionsTypes.push("FileExtension.IMushroomFile & ");
304
- }
305
- }
306
-
307
- let code = `import { IdType, IMushroom, Mushroom, MushroomRequest, MushroomRequestSetting, MushroomRestfulRequest, MushroomResponse, MushroomResponseDataType, MushroomResourceBase, MushroomListResource, MushroomFindByIdResource, MushroomCreateResource, MushroomBatchCreateResource, MushroomUpdateResource, MushroomBatchUpdateResource, MushroomPartialUpdateResource, MushroomDeleteResource, MushroomBatchDeleteResource, MushroomExtensibleResource, MushroomViewFunction, MushroomError, IMushroomOfflineResponse, MushroomOfflineResponse, MushroomOfflineResponseState } from "mushroomjs";
308
- ${extensionsImportLines.join("\n")}
309
- export * from "mushroomjs";
310
- export declare const extensions = {
311
- ${extensionsExportLines.join(",\n ")}
312
- };
313
-
314
- export declare type ISODateValue = string | Date;
315
- export declare type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoIncLong" ? "number" : "string"};
316
-
317
- `;
318
- let iApiClassBody = "";
319
- for (let entityName in entities) {
320
- if (!entities.hasOwnProperty(entityName))
321
- continue;
322
-
323
- const entity = entities[entityName];
324
- const typescriptClassName = toTypeScriptClassName(entityName);
325
- code += `export interface ${typescriptClassName} ${generateTypescriptClass(entity.fields)};
326
- `;
327
-
328
-
329
- const actions = {};
330
- iApiClassBody += ` ${entityName}: MushroomResourceBase`;
331
- let customMethodCode = "";
332
- for (const actionName in entity.actions) {
333
- if (!entity.actions.hasOwnProperty(actionName))
334
- continue;
335
-
336
- actions[actionName] = {
337
- clientCache: (actionName === "findById" || actionName === "findMany") && isAllowCache(entity.actions[actionName], true) ? true : undefined,
338
- includeTotal: actionName === "findMany" && entity.actions[actionName].some(a => a.includeTotal) ? true: undefined,
339
- offlineMode: entity.actions[actionName].some(a => a.offlineMode === "disallow")
340
- ? "disallow"
341
- : !entity.actions[actionName].length || entity.actions[actionName].some(a => a.offlineMode === "allow")
342
- ? "allow"
343
- : undefined
344
- };
345
-
346
- switch (actionName) {
347
- case "findMany": {
348
- iApiClassBody += ` & MushroomListResource<${typescriptClassName}>`;
349
- break;
350
- }
351
- case "findById": {
352
- iApiClassBody += ` & MushroomFindByIdResource<${typescriptClassName}>`;
353
- break;
354
- }
355
- case "createOne": {
356
- iApiClassBody += ` & MushroomCreateResource<${typescriptClassName}>`;
357
- break;
358
- }
359
- case "createMany": {
360
- iApiClassBody += ` & MushroomBatchCreateResource<${typescriptClassName}>`;
361
- break;
362
- }
363
- case "updateOne": {
364
- iApiClassBody += ` & MushroomUpdateResource<${typescriptClassName}>`;
365
- break;
366
- }
367
- case "updateMany": {
368
- iApiClassBody += ` & MushroomBatchUpdateResource<${typescriptClassName}>`;
369
- break;
370
- }
371
- case "updatePartially": {
372
- iApiClassBody += ` & MushroomPartialUpdateResource<${typescriptClassName}>`;
373
- break;
374
- }
375
- case "deleteOne": {
376
- iApiClassBody += " & MushroomDeleteResource";
377
- break;
378
- }
379
- case "deleteMany": {
380
- iApiClassBody += " & MushroomBatchDeleteResource";
381
- break;
382
- }
383
- default: {
384
- if (actionName.indexOf("_raw_http_method_") === 0) {
385
- customMethodCode += ` ${actionName.substring("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
386
- `;
387
- break;
388
- }
389
- else {
390
- console.warn(`Unknown action name: ${entityName}.${actionName}`);
391
- break;
392
- }
393
- }
394
- }
395
- }
396
-
397
- if (customMethodCode) {
398
- code += `export interface ${typescriptClassName}$CustomMethodResource {
399
- ${customMethodCode}}
400
- `;
401
- iApiClassBody += ` & ${typescriptClassName}$CustomMethodResource`;
402
- }
403
-
404
- const views = {};
405
- let viewCode = "";
406
- for (const viewName in entity.views) {
407
- if (!entity.views.hasOwnProperty(viewName)) continue;
408
-
409
- const viewRoles = entity.views[viewName];
410
- if (!Array.isArray(viewRoles) || !viewRoles.length) continue;
411
-
412
- views[viewName] = { clientCache: true };
413
-
414
- const viewParameterTypes = viewRoles.map(view => {
415
- const inputType = `${typescriptClassName}$ViewsResource_${viewName}View_${view.grant === "*" ? "" : toTypeScriptClassName(view.grant)}Parameters`;
416
- const outputType = view.codeHint?.output ? `${typescriptClassName}$ViewsResource_${viewName}View_${view.grant === "*" ? "" : toTypeScriptClassName(view.grant)}Result` : 'any';
417
- code += `export interface ${inputType} ${generateTypescriptClassFromViewParameters(view.parameters)};
418
- `;
419
- if (view.codeHint?.output)
420
- code += `export interface ${outputType} ${generateTypescriptClass(view.codeHint.output.fields, undefined, {checkRequired: true})};
421
- `;
422
- return `MushroomViewFunction<${outputType}, ${inputType}>`;
423
- });
424
- viewCode += `
425
- ${viewName}Async: ${viewParameterTypes.join(' | ')},`;
426
- }
427
-
428
- if (viewCode) {
429
- code += `export interface ${typescriptClassName}$ViewsResource {
430
- views: {${viewCode}
431
- }
432
- }
433
- `;
434
- iApiClassBody += ` & ${typescriptClassName}$ViewsResource`;
435
- }
436
-
437
- iApiClassBody +=`,
438
- `;
439
- }
440
-
441
- code += `
442
- export interface IApi extends IMushroom {
443
- ${iApiClassBody}};
444
-
445
- declare type Api = ${extensionsTypes.join('')}IApi;
446
- declare const _default: Api;
447
- export default _default;`;
448
-
449
- return code;
450
- }
451
-
452
- function genTypescriptDriver(args, projectName, project, alias, source) {
453
- const aliasProject = ((project.tsDriver || {}).alias || {})[alias];
454
-
455
- if (!aliasProject) {
456
- throw new Error(`Not found gen ts-driver configuration. Please run 'npx mushroom-cli config gen ${projectName} ts-driver OUTPUT_FILE.ts${alias === "default" ? "" : " alias " + alias}' first`);
457
- }
458
-
459
- const code = genTypescriptDriverString(aliasProject, source);
460
-
461
- common.ensureFolder(aliasProject.output);
462
-
463
- fs.writeFileSync(aliasProject.output, code);
464
- console.log(`Generated Typescript driver for ${projectName}@${alias} to ${aliasProject.output}`);
465
- }
466
-
467
- module.exports = {
468
- genTypescriptDriver,
469
- genTypescriptDriverString,
470
- genDtsString
471
- };
package/init/init-json.js DELETED
@@ -1,106 +0,0 @@
1
- const fs = require("fs");
2
- const fetch = require('node-fetch');
3
- const readlineSync = require("readline-sync");
4
- const help = require("../help.js");
5
- const common = require("../common.js");
6
-
7
- function initJson(args) {
8
- const path = args[2];
9
- if (!path) {
10
- help(args);
11
- return;
12
- }
13
-
14
- if (fs.existsSync(path)){
15
- console.error(`File ${path} is already existed`);
16
- return;
17
- }
18
-
19
- if (args[3] === "silent") {
20
- console.log("Fetch http://api.siten.vn/gen/template/default.json");
21
- fetch("http://api.siten.vn/gen/template/default.json").then(res => res.text()).then(text => {
22
- common.ensureFolder(path);
23
-
24
- fs.writeFile(path, text, err => {
25
- if (err)
26
- throw err;
27
- console.log(`Initialized json at ${path}`);
28
- });
29
- });
30
- return;
31
- }
32
-
33
- console.log("Fetch http://api.siten.vn/gen/template/template-def.json");
34
- fetch("http://api.siten.vn/gen/template/template-def.json").then(res => res.json()).then(templateConfig => {
35
- const info = {};
36
- templateConfig.fields.forEach(field => {
37
- while (true)
38
- {
39
- let question = `${field.required ? "[Required] " : ""}${field.label || field.name}`;
40
- if (Array.isArray(field.list)) {
41
- question += "\n";
42
- let i = 1;
43
- field.list.forEach(item => { question += "\t" + i++ + ". " + item + "\n"; });
44
- question += "Please choose";
45
- }
46
- if (field.defaultValue !== undefined) {
47
- question += ` (default: '${field.defaultValue}')`;
48
- }
49
- question += ": ";
50
- let choice = readlineSync.question(question);
51
- if (choice === "") {
52
- if (field.defaultValue != undefined)
53
- choice = field.defaultValue;
54
- }
55
- else if (Array.isArray(field.list)) {
56
- if (choice !== null && choice !== "" && !isNaN(choice))
57
- choice = field.list[choice - 1];
58
- else
59
- choice = undefined;
60
- if (choice === undefined) {
61
- console.warn("Invalid input");
62
- continue;
63
- }
64
- }
65
-
66
- if (choice === "" || choice === undefined || choice == null) {
67
- choice = "";
68
-
69
- if (field.required) {
70
- console.warn("Required input value");
71
- continue;
72
- }
73
- }
74
-
75
- if (choice !== "" && field.pattern) {
76
- const re = new RegExp(field.pattern, field.patternFlags);
77
- if (!re.test(choice)) {
78
- console.warn("Input doesn't match with pattern " + field.pattern);
79
- continue;
80
- }
81
- }
82
-
83
- info[field.name] = choice;
84
- break;
85
- }
86
- });
87
- //console.log(info);
88
-
89
- console.log(`Fetch ${templateConfig.templateUrl}`);
90
- fetch(templateConfig.templateUrl).then(res => res.text()).then(json => {
91
- json = json.replace(/\"\$\{([\w]+)\}\"/g, (s0, s1) => JSON.stringify(info[s1]));
92
- json = json.replace(/\$\{([\w]+)\}/g, (s0, s1) => JSON.stringify(info[s1]).replace(/^\"|\"$/g, ""));
93
-
94
- common.ensureFolder(path);
95
- //console.log(json);
96
-
97
- fs.writeFile(path, json, err => {
98
- if (err)
99
- throw err;
100
- console.log(`Initialized json at ${path}`);
101
- });
102
- });
103
- })
104
- }
105
-
106
- module.exports = initJson;
@@ -1,32 +0,0 @@
1
- const fs = require("fs");
2
- const { spawn } = require("child_process");
3
- const common = require("../common.js");
4
-
5
-
6
- function fetchFromGit() {
7
- return new Promise((resolve, reject) => {
8
- const git = spawn("git", ["clone", "https://tfs.siten.vn/tfs/Siten/CodeBase/_git/Mushroom", "-b", "full_extensions", "--single-branch"]);
9
- git.stdout.on('data', (data) => {
10
- console.log(`GIT: ${data}`);
11
- });
12
-
13
- git.stderr.on('data', (data) => {
14
- console.error(`GIT: ${data}`);
15
- });
16
-
17
- git.on('close', (code) => {
18
- if (code) {
19
- reject(new Error(`GIT exited with code ${code}`));
20
- return;
21
- }
22
- resolve();
23
- });
24
- })
25
- }
26
-
27
- async function initNetCore(args) {
28
- await fetchFromGit();
29
- common.processTemplate("Mushroom", "mushroom-template.json");
30
- }
31
-
32
- module.exports = initNetCore;
package/init.js DELETED
@@ -1,28 +0,0 @@
1
- const help = require("./help.js");
2
-
3
- const initJson = require("./init/init-json");
4
- const initNetCore = require("./init/init-netcore");
5
-
6
- async function init(args) {
7
- const configCommand = args[1];
8
- switch(configCommand) {
9
- case "json":
10
- initJson(args);
11
- break;
12
- case "netcore":
13
- await initNetCore(args);
14
- break;
15
- case "":
16
- case undefined:
17
- case "help":
18
- case "man":
19
- help("init");
20
- break;
21
- default:
22
- help(args, true);
23
- break;
24
- }
25
-
26
- }
27
-
28
- module.exports = init;