mushroom-cli 1.1.0-alpha.10 → 1.1.0-alpha.13

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/common.js CHANGED
@@ -1,11 +1,11 @@
1
1
  const fs = require("fs");
2
2
 
3
- function ensureFolder(path) {
3
+ function ensureFolder(path, isFolder) {
4
4
  const index = path.lastIndexOf("/");
5
- if (index <= 0){
5
+ if (!isFolder && index <= 0){
6
6
  return;
7
7
  }
8
- path = path.substr(0, index);
8
+ if (!isFolder) path = path.substring(0, index);
9
9
  if (path === "." || path === "..")
10
10
  return;
11
11
 
package/config.js CHANGED
@@ -75,8 +75,8 @@ function configGenDocs(args, mushroomConfig, projectName){
75
75
  const strRoles = args[index];
76
76
  if (strRoles) {
77
77
  const minusIndex = strRoles.indexOf("-");
78
- let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substr(0, minusIndex);
79
- const deniedRoles = minusIndex == -1 ? "" : strRoles.substr(minusIndex + 1);
78
+ let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substring(0, minusIndex);
79
+ const deniedRoles = minusIndex == -1 ? "" : strRoles.substring(minusIndex + 1);
80
80
  if (!grantedRoles)
81
81
  grantedRoles = "*";
82
82
  parameters.allowRoles = grantedRoles.split(",");
@@ -173,8 +173,8 @@ function configGenJavascriptDriver(args, mushroomConfig, projectName){
173
173
  const strRoles = args[index];
174
174
  if (strRoles) {
175
175
  const minusIndex = strRoles.indexOf("-");
176
- let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substr(0, minusIndex);
177
- const deniedRoles = minusIndex == -1 ? "" : strRoles.substr(minusIndex + 1);
176
+ let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substring(0, minusIndex);
177
+ const deniedRoles = minusIndex == -1 ? "" : strRoles.substring(minusIndex + 1);
178
178
  if (!grantedRoles)
179
179
  grantedRoles = "*";
180
180
  parameters.allowRoles = grantedRoles.split(",");
@@ -233,8 +233,8 @@ function configGenTypescriptDriver(args, mushroomConfig, projectName){
233
233
  const strRoles = args[index];
234
234
  if (strRoles) {
235
235
  const minusIndex = strRoles.indexOf("-");
236
- let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substr(0, minusIndex);
237
- const deniedRoles = minusIndex == -1 ? "" : strRoles.substr(minusIndex + 1);
236
+ let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substring(0, minusIndex);
237
+ const deniedRoles = minusIndex == -1 ? "" : strRoles.substring(minusIndex + 1);
238
238
  if (!grantedRoles)
239
239
  grantedRoles = "*";
240
240
  parameters.allowRoles = grantedRoles.split(",");
@@ -325,8 +325,8 @@ function configGenCSharpDriver(args, mushroomConfig, projectName){
325
325
  const strRoles = args[index];
326
326
  if (strRoles) {
327
327
  const minusIndex = strRoles.indexOf("-");
328
- let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substr(0, minusIndex);
329
- const deniedRoles = minusIndex == -1 ? "" : strRoles.substr(minusIndex + 1);
328
+ let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substring(0, minusIndex);
329
+ const deniedRoles = minusIndex == -1 ? "" : strRoles.substring(minusIndex + 1);
330
330
  if (!grantedRoles)
331
331
  grantedRoles = "*";
332
332
  parameters.allowRoles = grantedRoles.split(",");
@@ -38,7 +38,7 @@ function processGenDocs(aliasProject, entities, source, html, args, projectName,
38
38
  if (typeof msg != "string") return;
39
39
 
40
40
  if (msg.indexOf("MUSHROOM-CLI:") === 0) {
41
- console.log("GenDocEngine:" + msg.substr("MUSHROOM-CLI:".length));
41
+ console.log("GenDocEngine:" + msg.substring("MUSHROOM-CLI:".length));
42
42
  }
43
43
 
44
44
  if (msg === "MUSHROOM-CLI: FAIL"){
package/gen/gen-csharp.js CHANGED
@@ -3,6 +3,31 @@ const common = require("../common.js");
3
3
  const package = require("./../package.json");
4
4
 
5
5
  //#region shared function
6
+ const newLine = `
7
+ `;
8
+ const header = `// NOTE: This file was generated by Mushroom CLI (https://www.npmjs.com/package/mushroom-cli), please do not modify
9
+ // NOTE: Version and compatibility information: please see in Info.cs file
10
+
11
+ // ReSharper disable CheckNamespace
12
+ // ReSharper disable CommentTypo
13
+ // ReSharper disable EmptyNamespace
14
+ // ReSharper disable IdentifierTypo
15
+ // ReSharper disable InconsistentNaming
16
+ // ReSharper disable PartialTypeWithSinglePart
17
+ // ReSharper disable RedundantUsingDirective
18
+ // ReSharper disable StringLiteralTypo
19
+ // ReSharper disable UnusedMember.Global
20
+ // ReSharper disable UnusedMember.Local
21
+ // ReSharper disable UnusedParameter.Local
22
+ // ReSharper disable UnusedTypeParameter
23
+
24
+
25
+ using MongoDB.Bson;
26
+ using MongoDB.Bson.Serialization.Attributes;
27
+ using MongoDB.Driver;
28
+ using JsonPropertyAttribute = Newtonsoft.Json.JsonPropertyAttribute;
29
+ using NullValueHandling = Newtonsoft.Json.NullValueHandling;`;
30
+
6
31
  function singleLine(str) {
7
32
  if (!str)
8
33
  return "";
@@ -25,7 +50,7 @@ function toCSharpName(str) {
25
50
  return "_";
26
51
  const name = toVietnameseNonTongue(str).replace(/\W/g, "_");
27
52
  const c = name.charAt(0);
28
- return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substr(1);
53
+ return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substring(1);
29
54
  }
30
55
 
31
56
  function getCSharpTypeFromMushroomType(source, type, required) {
@@ -143,7 +168,8 @@ function generateCSharpClassMongoDb(source, className, fields, isRoot, descripti
143
168
  content +=
144
169
  ` /// <summary>
145
170
  /// ${singleLine(description)}
146
- /// </summary>\r\n`;
171
+ /// </summary>
172
+ `;
147
173
  }
148
174
  var supperClass = "";
149
175
  if (isRoot) {
@@ -171,12 +197,12 @@ function generateCSharpClassMongoDb(source, className, fields, isRoot, descripti
171
197
  type = field.codeHint.type.csharp;
172
198
  }
173
199
  else if (field.type === "object") {
174
- strClasses += generateCSharpClassMongoDb(source, className + "_" + propertyName, field.fields, false, null, out) + "\r\n";
200
+ strClasses += generateCSharpClassMongoDb(source, className + "_" + propertyName, field.fields, false, null, out) + newLine;
175
201
  type = className + "_" + propertyName;
176
202
  }
177
203
  else if (field.type === "array") {
178
204
  if (field.items.type === "object") {
179
- strClasses += generateCSharpClassMongoDb(source, className + "_" + propertyName, field.items.fields, false, null, out) + "\r\n";
205
+ strClasses += generateCSharpClassMongoDb(source, className + "_" + propertyName, field.items.fields, false, null, out) + newLine;
180
206
  type = `System.Collections.Generic.List<${className}_${propertyName}>`;
181
207
  } else {
182
208
  type = `System.Collections.Generic.List<${getCSharpTypeFromMushroomType(source, field.items.type, field.items.validation && field.items.validation.required)}>`;
@@ -190,34 +216,34 @@ function generateCSharpClassMongoDb(source, className, fields, isRoot, descripti
190
216
  `;
191
217
 
192
218
  if (isRoot && fieldName === "id") {
193
- content += ` [BsonId${field.type === "AutoId" && source.idType === "GUID" ? "(IdGenerator = typeof(MongoDB.Bson.Serialization.IdGenerators.GuidGenerator))" : ""}]\r\n`;
219
+ content += ` [BsonId${field.type === "AutoId" && source.idType === "GUID" ? "(IdGenerator = typeof(MongoDB.Bson.Serialization.IdGenerators.GuidGenerator))" : ""}]${newLine}`;
194
220
  }
195
221
  content += ` [BsonElement("${isRoot && fieldName === "id" ? "_id" : fieldName}")]
196
222
  [BsonIgnoreIfNull]
197
223
  [JsonProperty(PropertyName = "${fieldName}", NullValueHandling = NullValueHandling.Ignore)]
198
224
  `;
199
225
  if ((field.type === "AutoId" || field.type === "IdRef") && source.idType === "ObjectId") {
200
- content += " [BsonRepresentation(BsonType.ObjectId)]\r\n";
226
+ content += " [BsonRepresentation(BsonType.ObjectId)]" + newLine;
201
227
  }
202
228
  if (field.type === "AutoId" && source.idType === "GUID") {
203
- content += " [BsonRepresentation(BsonType.String)]\r\n";
229
+ content += " [BsonRepresentation(BsonType.String)]" + newLine;
204
230
  }
205
231
  if (field.type === "datetime") {
206
- content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]\r\n";
232
+ content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]" + newLine;
207
233
  }
208
234
  if (field.type === "array") {
209
235
  if ((field.items.type === "AutoId" || field.items.type === "IdRef") && source.idType === "ObjectId") {
210
- content += " [BsonRepresentation(BsonType.ObjectId)]\r\n";
236
+ content += " [BsonRepresentation(BsonType.ObjectId)]" + newLine;
211
237
  }
212
238
  if (field.items.type === "AutoId" && source.idType === "GUID") {
213
- content += " [BsonRepresentation(BsonType.String)]\r\n";
239
+ content += " [BsonRepresentation(BsonType.String)]" + newLine;
214
240
  }
215
241
  if (field.items.type === "datetime") {
216
- content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]\r\n";
242
+ content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]" + newLine;
217
243
  }
218
244
  }
219
245
 
220
- content += ` public ${type} ${propertyName} { get; set; }\r\n\r\n`;
246
+ content += ` public ${type} ${propertyName} { get; set; }${newLine}${newLine}`;
221
247
 
222
248
  strEnumClasses += generateEnumClass(source, out, field, `${className.toUpperCase()}_${propertyName.toUpperCase()}_ENUM`);
223
249
  }
@@ -233,14 +259,14 @@ function generateCSharpClassMongoDb(source, className, fields, isRoot, descripti
233
259
  //console.log("strEnumClasses("+typeof(strEnumClasses)+"):" + strEnumClasses);
234
260
  }
235
261
 
236
- return strClasses + "\r\n" + content;
262
+ return strClasses + newLine + content;
237
263
  }
238
264
 
239
265
  function getCSharpFunc(methodName, methodType) {
240
266
  if (methodType === "static") return methodName;
241
267
  const idx = methodName.lastIndexOf('.');
242
268
  if (idx === -1) return methodName;
243
- return `new ${methodName.substr(0, idx)}()${methodName.substr(idx)}`;
269
+ return `new ${methodName.substring(0, idx)}()${methodName.substring(idx)}`;
244
270
  }
245
271
 
246
272
  function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
@@ -250,6 +276,11 @@ function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
250
276
  throw new Error(`Not found gen c#-mongo configuration. Please run 'npx mr config ${projectName} gen c#-mongo OUTPUT_FILE.cs${alias === "default" ? "" : " alias " + alias}' first`);
251
277
  }
252
278
 
279
+ if (aliasProject.outputToFolder) {
280
+ genCSharpMongoDbClassesToFolder(projectName, alias, source, aliasProject);
281
+ return;
282
+ }
283
+
253
284
  const entities = common.getEntities(source, aliasProject.allowRoles, true);
254
285
 
255
286
  const namespace = toCSharpName(source.name);
@@ -268,7 +299,7 @@ function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
268
299
  collectionNames += ` public static string ${className}CollectionName => "${entities[entityName].storageName}";
269
300
  public static IMongoCollection<Resources.${className}> ${className}Collection => GetDatabase().GetCollection<Resources.${className}>(${className}CollectionName);
270
301
  `;
271
- resourceNames += ` public static string ${className} => "${entityName}";\r\n`;
302
+ resourceNames += ` public static string ${className} => "${entityName}";${newLine}`;
272
303
  strClasses += generateCSharpClassMongoDb(source, className, entities[entityName].fields, true, entities[entityName].description, out);
273
304
 
274
305
  const actions = entities[entityName].actions || {};
@@ -360,7 +391,7 @@ function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
360
391
  }
361
392
  return prev;
362
393
  }, {});
363
- const strDelegatorReferences = Object.keys(delegators).map(method => delegators[method].map(ev => ` // ${ev.source}`).join("\r\n") + "\r\n" + ` RegisterCustomMethod(${getCSharpFunc(method, delegators[method][0].type)});`).join("\r\n");
394
+ const strDelegatorReferences = Object.keys(delegators).map(method => delegators[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterCustomMethod(${getCSharpFunc(method, delegators[method][0].type)});`).join(newLine);
364
395
 
365
396
  const viewHandlers = (out.viewHandlers || []).reduce((prev, cur) => {
366
397
  if (cur.method in prev) {
@@ -373,7 +404,7 @@ function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
373
404
  }
374
405
  return prev;
375
406
  }, {});
376
- const strViewHandlerReferences = Object.keys(viewHandlers).map(method => viewHandlers[method].map(ev => ` // ${ev.source}`).join("\r\n") + "\r\n" + ` RegisterCustomViewMethod(${getCSharpFunc(method, viewHandlers[method][0].type)});`).join("\r\n");
407
+ const strViewHandlerReferences = Object.keys(viewHandlers).map(method => viewHandlers[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterCustomViewMethod(${getCSharpFunc(method, viewHandlers[method][0].type)});`).join(newLine);
377
408
 
378
409
  const eventHandlers = (out.eventHandlers || []).reduce((prev, cur) => {
379
410
  if (cur.method in prev) {
@@ -386,18 +417,18 @@ function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
386
417
  }
387
418
  return prev;
388
419
  }, {});
389
- const strEventHandlerReferences = Object.keys(eventHandlers).map(method => eventHandlers[method].map(ev => ` // ${ev.source}`).join("\r\n") + "\r\n" + ` RegisterEvent(${getCSharpFunc(method, eventHandlers[method][0].type)});`).join("\r\n");
420
+ const strEventHandlerReferences = Object.keys(eventHandlers).map(method => eventHandlers[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterEvent(${getCSharpFunc(method, eventHandlers[method][0].type)});`).join(newLine);
390
421
 
391
422
  const strJobReferences = Array.isArray(source.jobs)
392
423
  ? source.jobs
393
424
  .filter(job => job !== null && typeof(job) === "object" && job.action && typeof (job.action) === "string" && job.action.indexOf("lib:") === 0)
394
- .map(job => ` RegisterJob<${job.action.substr(4).split(',')[0]}>();`)
395
- .join("\r\n")
425
+ .map(job => ` RegisterJob<${job.action.substring(4).split(',')[0]}>();`)
426
+ .join(newLine)
396
427
  : "";
397
428
 
398
429
  const code = `// This file was generated by Mushroom CLI ${package.version} (https://www.npmjs.com/package/mushroom-cli), please do not modify
399
430
 
400
- // NOTE: Compatible with Mushroom Server version 0.2.18 or higher
431
+ // NOTE: Compatible with Mushroom Server version 0.2.18 or higher (https://www.nuget.org/packages/Mushroom/)
401
432
 
402
433
  // ReSharper disable RedundantUsingDirective
403
434
  // ReSharper disable InconsistentNaming
@@ -488,6 +519,359 @@ ${strJobReferences}
488
519
  console.log(`Generated CSharp MongoDb Classes for ${projectName}@${alias} to ${aliasProject.output}`);
489
520
  });
490
521
  }
522
+
523
+ function generateCSharpClassMongoDbToFolder(source, className, fields, isRoot, description, out, aliasProject) {
524
+ var content = "";
525
+ const namespace = toCSharpName(source.name);
526
+ if (description) {
527
+ content +=
528
+ ` /// <summary>
529
+ /// ${singleLine(description)}
530
+ /// </summary>
531
+ `;
532
+ }
533
+ var supperClass = "";
534
+ if (isRoot) {
535
+ // thêm cho trường hợp không khai báo id hoặc id.type
536
+ if (!fields.id) {
537
+ fields.id = {
538
+ type: "AutoId"
539
+ };
540
+ }
541
+ if (!fields.id.type) fields.id.type = "AutoId";
542
+
543
+ supperClass = " : Mushroom.Models.IResource<" + getCSharpTypeFromMushroomType(source, fields.id.type, true) + ">";
544
+ }
545
+ content += ` public class ${className}${supperClass}
546
+ {
547
+ `;
548
+ for (var fieldName in fields) {
549
+ if (!fields.hasOwnProperty(fieldName))
550
+ continue;
551
+
552
+ var field = fields[fieldName];
553
+ var type;
554
+ var propertyName = toCSharpName(fieldName);
555
+ if (field.codeHint && field.codeHint.type && field.codeHint.type.csharp) {
556
+ type = field.codeHint.type.csharp;
557
+ }
558
+ else if (field.type === "object") {
559
+ generateCSharpClassMongoDbToFolder(source, className + "_" + propertyName, field.fields, false, null, out, aliasProject) + newLine;
560
+ type = className + "_" + propertyName;
561
+ }
562
+ else if (field.type === "array") {
563
+ if (field.items.type === "object") {
564
+ generateCSharpClassMongoDbToFolder(source, className + "_" + propertyName, field.items.fields, false, null, out, aliasProject) + newLine;
565
+ type = `System.Collections.Generic.List<${className}_${propertyName}>`;
566
+ } else {
567
+ type = `System.Collections.Generic.List<${getCSharpTypeFromMushroomType(source, field.items.type, field.items.validation && field.items.validation.required)}>`;
568
+ }
569
+ } else
570
+ type = getCSharpTypeFromMushroomType(source, field.type, field.validation && field.validation.required);
571
+ content +=
572
+ ` /// <summary>
573
+ /// ${singleLine(field.description)}
574
+ /// </summary>
575
+ `;
576
+
577
+ if (isRoot && fieldName === "id") {
578
+ content += ` [BsonId${field.type === "AutoId" && source.idType === "GUID" ? "(IdGenerator = typeof(MongoDB.Bson.Serialization.IdGenerators.GuidGenerator))" : ""}]${newLine}`;
579
+ }
580
+ content += ` [BsonElement("${isRoot && fieldName === "id" ? "_id" : fieldName}")]
581
+ [BsonIgnoreIfNull]
582
+ [JsonProperty(PropertyName = "${fieldName}", NullValueHandling = NullValueHandling.Ignore)]
583
+ `;
584
+ if ((field.type === "AutoId" || field.type === "IdRef") && source.idType === "ObjectId") {
585
+ content += " [BsonRepresentation(BsonType.ObjectId)]" + newLine;
586
+ }
587
+ if (field.type === "AutoId" && source.idType === "GUID") {
588
+ content += " [BsonRepresentation(BsonType.String)]" + newLine;
589
+ }
590
+ if (field.type === "datetime") {
591
+ content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]" + newLine;
592
+ }
593
+ if (field.type === "array") {
594
+ if ((field.items.type === "AutoId" || field.items.type === "IdRef") && source.idType === "ObjectId") {
595
+ content += " [BsonRepresentation(BsonType.ObjectId)]" + newLine;
596
+ }
597
+ if (field.items.type === "AutoId" && source.idType === "GUID") {
598
+ content += " [BsonRepresentation(BsonType.String)]" + newLine;
599
+ }
600
+ if (field.items.type === "datetime") {
601
+ content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]" + newLine;
602
+ }
603
+ }
604
+
605
+ content += ` public ${type} ${propertyName} { get; set; }
606
+
607
+ `;
608
+
609
+ let strEnumClasses = generateEnumClass(source, {}, field, `${className.toUpperCase()}_${propertyName.toUpperCase()}_ENUM`);
610
+
611
+ const match = strEnumClasses.match(/public static class\s+(\w+)/);
612
+ if (!match) continue;
613
+ common.ensureFolder(aliasProject.output + "/Enums", true);
614
+ strEnumClasses = `${header}
615
+
616
+ namespace ${namespace}.Enums
617
+ {
618
+ ${strEnumClasses}
619
+ }
620
+ `;
621
+
622
+ fs.writeFileSync(aliasProject.output + "/Enums/" + match[1] + ".cs", strEnumClasses);
623
+ }
624
+
625
+ content += ` [BsonExtraElements]
626
+ public System.Collections.Generic.Dictionary<string, object> Mushroom_ExtraProperties { get; set; }
627
+
628
+ }
629
+ `;
630
+
631
+ //return strClasses + newLine + content;
632
+ common.ensureFolder(aliasProject.output + "/Resources", true);
633
+
634
+ content = `${header}
635
+
636
+ namespace ${namespace}.Resources
637
+ {
638
+ ${content}
639
+ }
640
+ `;
641
+
642
+ fs.writeFileSync(aliasProject.output + "/Resources/" + className + ".cs", content);
643
+ }
644
+
645
+ function genCSharpMongoDbClassesToFolder(projectName, alias, source, aliasProject) {
646
+
647
+ if (fs.existsSync(aliasProject.output)) {
648
+ try {
649
+ fs.unlinkSync(aliasProject.output); // xóa file nếu có
650
+ } catch(e) {}
651
+ try {
652
+ fs.rmdirSync(aliasProject.output); // xóa thư mục nếu có
653
+ } catch(e) {}
654
+ }
655
+ fs.mkdirSync(aliasProject.output, { recursive: true, mode: 0755 });
656
+
657
+ const entities = common.getEntities(source, aliasProject.allowRoles, true);
658
+
659
+ const namespace = toCSharpName(source.name);
660
+
661
+ let collectionNames = "";
662
+ let resourceNames = "";
663
+
664
+ const out = {};
665
+ for (let entityName in entities) {
666
+ if (!entities.hasOwnProperty(entityName))
667
+ continue;
668
+
669
+ const className = toCSharpName(entityName);
670
+ collectionNames += ` public static string ${className}CollectionName => "${entities[entityName].storageName}";
671
+ public static IMongoCollection<Resources.${className}> ${className}Collection => GetDatabase().GetCollection<Resources.${className}>(${className}CollectionName);
672
+ `;
673
+ resourceNames += ` public static string ${className} => "${entityName}";
674
+ `;
675
+ //strClasses += generateCSharpClassMongoDbToFolder(source, className, entities[entityName].fields, true, entities[entityName].description, out);
676
+
677
+ generateCSharpClassMongoDbToFolder(source, className, entities[entityName].fields, true, entities[entityName].description, out, aliasProject);
678
+
679
+ const actions = entities[entityName].actions || {};
680
+ for (let actionName in actions) {
681
+ const action = actions[actionName];
682
+ if (!Array.isArray(action))
683
+ continue;
684
+
685
+ action.forEach(a => {
686
+ if (!a)
687
+ return;
688
+ if (typeof a.delegator === "string" && a.delegator.indexOf("lib:") === 0) {
689
+ out.delegators = out.delegators || [];
690
+ const method = a.delegator.substr(4, a.delegator.length - 4);
691
+ let type = a.codeHint && a.codeHint.delegator && a.codeHint.delegator.csharp
692
+ ? a.codeHint.delegator.csharp.methodType
693
+ : null;
694
+ if (type !== "non-static") type = "static";
695
+ out.delegators.push({
696
+ method: method,
697
+ source: `entity: ${entityName}, action: ${actionName}, grant: ${a.grant}`,
698
+ type: type
699
+ });
700
+ }
701
+
702
+ if (!a.events && !(typeof a.events === "object")) return;
703
+
704
+ for (let eventName in a.events) {
705
+ if (!Array.isArray(a.events[eventName])) return;
706
+
707
+ out.eventHandlers = out.eventHandlers || [];
708
+ a.events[eventName].forEach((ev, i) => {
709
+ if (typeof ev !== "string" || ev.indexOf("lib:") !== 0) return;
710
+ const method = ev.substr(4, ev.length - 4);
711
+ let type = a.codeHint && a.codeHint.events
712
+ && Array.isArray(a.codeHint.events[eventName])
713
+ && a.codeHint.events[eventName][i]
714
+ && a.codeHint.events[eventName][i].csharp
715
+ ? a.codeHint.events[eventName][i].csharp.methodType
716
+ : null;
717
+ if (type !== "non-static") type = "static";
718
+ out.eventHandlers.push({
719
+ method: method,
720
+ source: `entity: ${entityName}, action: ${actionName}, grant: ${a.grant}, event: ${eventName}`,
721
+ type: type
722
+ });
723
+ });
724
+ }
725
+ });
726
+ }
727
+
728
+ const views = entities[entityName].views || {};
729
+ for (let viewName in views) {
730
+ const view = views[viewName];
731
+ if (!Array.isArray(view))
732
+ continue;
733
+
734
+ view.forEach(v => {
735
+ if (!v) return;
736
+
737
+ if (typeof v.query === "string" && v.query.indexOf("lib:") === 0) {
738
+ out.viewHandlers = out.viewHandlers || [];
739
+ const method = v.query.substr(4, v.query.length - 4);
740
+ let type = v.codeHint && v.codeHint.query && v.codeHint.query.csharp
741
+ ? v.codeHint.query.csharp.methodType
742
+ : null;
743
+ if (type !== "non-static") type = "static";
744
+ out.viewHandlers.push({
745
+ method: method,
746
+ source: `entity: ${entityName}, view: ${viewName}, grant: ${v.grant}`,
747
+ type: type
748
+ });
749
+ }
750
+ });
751
+ }
752
+ }
753
+
754
+
755
+ const delegators = (out.delegators || []).reduce((prev, cur) => {
756
+ if (cur.method in prev) {
757
+ if (prev[cur.method].indexOf(cur.source) === -1) {
758
+ prev[cur.method].push(cur);
759
+ }
760
+ }
761
+ else {
762
+ prev[cur.method] = [cur];
763
+ }
764
+ return prev;
765
+ }, {});
766
+ const strDelegatorReferences = Object.keys(delegators).map(method => delegators[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterCustomMethod(${getCSharpFunc(method, delegators[method][0].type)});`).join(newLine);
767
+
768
+ const viewHandlers = (out.viewHandlers || []).reduce((prev, cur) => {
769
+ if (cur.method in prev) {
770
+ if (prev[cur.method].indexOf(cur.source) === -1) {
771
+ prev[cur.method].push(cur);
772
+ }
773
+ }
774
+ else {
775
+ prev[cur.method] = [cur];
776
+ }
777
+ return prev;
778
+ }, {});
779
+ const strViewHandlerReferences = Object.keys(viewHandlers).map(method => viewHandlers[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterCustomViewMethod(${getCSharpFunc(method, viewHandlers[method][0].type)});`).join(newLine);
780
+
781
+ const eventHandlers = (out.eventHandlers || []).reduce((prev, cur) => {
782
+ if (cur.method in prev) {
783
+ if (prev[cur.method].indexOf(cur.source) === -1) {
784
+ prev[cur.method].push(cur);
785
+ }
786
+ }
787
+ else {
788
+ prev[cur.method] = [cur];
789
+ }
790
+ return prev;
791
+ }, {});
792
+ const strEventHandlerReferences = Object.keys(eventHandlers).map(method => eventHandlers[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterEvent(${getCSharpFunc(method, eventHandlers[method][0].type)});`).join(newLine);
793
+
794
+ const strJobReferences = Array.isArray(source.jobs)
795
+ ? source.jobs
796
+ .filter(job => job !== null && typeof(job) === "object" && job.action && typeof (job.action) === "string" && job.action.indexOf("lib:") === 0)
797
+ .map(job => ` RegisterJob<${job.action.substring(4).split(',')[0]}>();`)
798
+ .join(newLine)
799
+ : "";
800
+
801
+ const dbConnectorFileContent = `${header}
802
+
803
+ namespace ${namespace}
804
+ {
805
+ public static class DbConnector
806
+ {
807
+ ${collectionNames}
808
+ public static IMongoDatabase GetDatabase() => Mushroom.MushroomDaoFactory.GetDbAdapter() as IMongoDatabase;
809
+
810
+ public static async System.Threading.Tasks.Task<T> FindByIdAsync<T, TId>(this IMongoCollection<T> collection, TId id) where T : Mushroom.Models.IResource<TId>
811
+ {
812
+ return await (await collection.FindAsync(Builders<T>.Filter.Eq(doc => doc.Id, id))).FirstOrDefaultAsync();
813
+ }
814
+
815
+ public static async System.Threading.Tasks.Task<T> FindByIdAsync<T, TId>(this IMongoCollection<T> collection, TId id, FindOptions<T> findOptions) where T : Mushroom.Models.IResource<TId>
816
+ {
817
+ return await (await collection.FindAsync(Builders<T>.Filter.Eq(doc => doc.Id, id), findOptions)).FirstOrDefaultAsync();
818
+ }
819
+
820
+ public static async System.Threading.Tasks.Task<T> FindByIdAsync<T, TId>(this IMongoCollection<T> collection, TId id, ProjectionDefinition<T> projection) where T : Mushroom.Models.IResource<TId>
821
+ {
822
+ return await (await collection.FindAsync(Builders<T>.Filter.Eq(doc => doc.Id, id), new FindOptions<T> { Projection = projection })).FirstOrDefaultAsync();
823
+ }
824
+ }
825
+ }
826
+ `;
827
+
828
+ const resourceNamesFileContent = `${header}
829
+
830
+ namespace ${namespace}
831
+ {
832
+ public static class ResourceNames
833
+ {
834
+ ${resourceNames}
835
+ }
836
+ }
837
+ `;
838
+
839
+ const refactorHelperFileContent = `${header}
840
+
841
+ #if DEBUG
842
+ namespace ${namespace}
843
+ {
844
+ class RefactorHelper
845
+ {
846
+ private RefactorHelper() { }
847
+ private void RegisterCustomMethod(System.Func<Mushroom.ActionArguments, System.Threading.Tasks.Task> fn) { }
848
+ private void RegisterCustomMethod(System.Action<Mushroom.ActionArguments> fn) { }
849
+ private void RegisterCustomViewMethod(System.Func<Mushroom.ViewArguments, System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<object>>> fn) { }
850
+ private void RegisterCustomViewMethod(System.Action<Mushroom.ViewArguments> fn) { }
851
+ private void RegisterEvent(System.Func<object, Mushroom.ActionArguments, System.Threading.Tasks.Task> fn) { }
852
+ private void RegisterEvent(System.Action<object, Mushroom.ActionArguments> fn) { }
853
+ private void RegisterJob<T>() where T : Mushroom.Job.JobBase { }
854
+ private void Help()
855
+ {
856
+ ${strDelegatorReferences}
857
+ ${strViewHandlerReferences}
858
+ ${strEventHandlerReferences}
859
+ ${strJobReferences}
860
+ }
861
+ }
862
+ }
863
+ #endif
864
+ `;
865
+
866
+ const infoFileContent = `// Mushroom CLI version: ${package.version}${newLine}// Compatible with Mushroom Server version: 0.2.18 or higher (https://www.nuget.org/packages/Mushroom/)`
867
+
868
+ fs.writeFileSync(aliasProject.output + "/DbConnector.cs", dbConnectorFileContent);
869
+ fs.writeFileSync(aliasProject.output + "/ResourceNames.cs", resourceNamesFileContent);
870
+ fs.writeFileSync(aliasProject.output + "/RefactorHelper.cs", refactorHelperFileContent);
871
+ fs.writeFileSync(aliasProject.output + "/Info.cs", infoFileContent);
872
+
873
+ console.log(`Generated CSharp MongoDb Classes for ${projectName}@${alias} to folder ${aliasProject.output}`);
874
+ }
491
875
  //#endregion
492
876
 
493
877
  //#region CSharp Driver
@@ -515,12 +899,12 @@ function generateCSharpClassDriver(source, className, fields, description, out)
515
899
  const propertyName = toCSharpName(fieldName);
516
900
  let type;
517
901
  if (field.type === "object") {
518
- strClasses += generateCSharpClassDriver(source, className + "_" + propertyName, field.fields, null, out) + "\r\n";
902
+ strClasses += generateCSharpClassDriver(source, className + "_" + propertyName, field.fields, null, out) + newLine;
519
903
  type = className + "_" + propertyName;
520
904
  }
521
905
  else if (field.type === "array") {
522
906
  if (field.items.type === "object") {
523
- strClasses += generateCSharpClassDriver(source, className + "_" + propertyName, field.items.fields, null, out) + "\r\n";
907
+ strClasses += generateCSharpClassDriver(source, className + "_" + propertyName, field.items.fields, null, out) + newLine;
524
908
  type = `System.Collections.Generic.List<${className}_${propertyName}>`;
525
909
  } else {
526
910
  type = `System.Collections.Generic.List<${getCSharpTypeFromMushroomType(source, field.items.type, field.items.validation && field.items.validation.required)}>`;
@@ -545,8 +929,8 @@ function generateCSharpClassDriver(source, className, fields, description, out)
545
929
  }
546
930
 
547
931
 
548
- content += " }\r\n";
549
- return strClasses + "\r\n" + content;
932
+ content += " }" + newLine;
933
+ return strClasses + newLine + content;
550
934
  }
551
935
 
552
936
  function genCSharpDriver(args, projectName, project, alias, source) {
@@ -578,8 +962,8 @@ function genCSharpDriver(args, projectName, project, alias, source) {
578
962
  var className = toCSharpName(entityName);
579
963
 
580
964
  strClasses += generateCSharpClassDriver(source, className, entities[entityName].fields, entities[entityName].description, out);
581
- codeStaticCtor += ` ${className} = new ${className}Connector(client);\r\n`;
582
- codeStaticProperties += ` public static ${className}Connector ${className} { get; }\r\n\r\n`;
965
+ codeStaticCtor += ` ${className} = new ${className}Connector(client);${newLine}`;
966
+ codeStaticProperties += ` public static ${className}Connector ${className} { get; }${newLine}${newLine}`;
583
967
 
584
968
  var entity = entities[entityName];
585
969
 
@@ -689,7 +1073,7 @@ function genCSharpDriver(args, projectName, project, alias, source) {
689
1073
  if (actionName.indexOf("_raw_http_method_"))
690
1074
  break;
691
1075
 
692
- var customMethod = toCSharpName(actionName.substr("_raw_http_method_".length));
1076
+ var customMethod = toCSharpName(actionName.substring("_raw_http_method_".length));
693
1077
 
694
1078
  codeConnectors += ` public async System.Threading.Tasks.Task<${className}${customMethod}Result> ${customMethod}(${className}${customMethod}Arg arg)
695
1079
  {
@@ -738,11 +1122,11 @@ function genCSharpDriver(args, projectName, project, alias, source) {
738
1122
 
739
1123
  partial void BuildCustomUrl();
740
1124
 
741
- private string OriginUrl => "${entityName}s/${actionName.substr("_raw_http_method_".length)}";
1125
+ private string OriginUrl => "${entityName}s/${actionName.substring("_raw_http_method_".length)}";
742
1126
 
743
- private string CustomUrl { get; set; } = "${entityName}s/${actionName.substr("_raw_http_method_".length)}";
1127
+ private string CustomUrl { get; set; } = "${entityName}s/${actionName.substring("_raw_http_method_".length)}";
744
1128
 
745
- public override string Method { get; } = "${actionName.substr("_raw_http_method_".length)}";
1129
+ public override string Method { get; } = "${actionName.substring("_raw_http_method_".length)}";
746
1130
 
747
1131
  public ${className}${customMethod}Body Data { get; set; }
748
1132
 
@@ -833,15 +1217,15 @@ function genCSharpDriver(args, projectName, project, alias, source) {
833
1217
  ${viewExtraClass}`;
834
1218
  }
835
1219
 
836
- codeConnectors += " }\r\n\r\n";
1220
+ codeConnectors += " }" + newLine + newLine;
837
1221
  }
838
1222
 
839
1223
  if (out.strEnumClasses)
840
1224
  strEnumClasses += out.strEnumClasses;
841
1225
 
842
- const code = `// This file was generated by Mushroom CLI (https://www.npmjs.com/package/mushroom-cli), please do not modify
1226
+ const code = `// This file was generated by Mushroom CLI ${package.version} (https://www.npmjs.com/package/mushroom-cli), please do not modify
843
1227
 
844
- // Require package: Mushroom.Driver version 1.4.0 or later https://www.nuget.org/packages/Mushroom.Driver/
1228
+ // Require package: Mushroom.Driver version 1.4.0 or later (https://www.nuget.org/packages/Mushroom.Driver/)
845
1229
 
846
1230
  // ReSharper disable InconsistentNaming
847
1231
  // ReSharper disable PartialTypeWithSinglePart
@@ -36,23 +36,34 @@ function genJavascriptDriverString(aliasProject, source) {
36
36
 
37
37
  if (Array.isArray(aliasProject.features)) {
38
38
  if (aliasProject.features.includes("auth")) {
39
- extensionsImportLines.push('import * as AuthExtension from "mushroomjs-auth";');
39
+ extensionsImportLines.push('//import * as AuthExtension from "mushroomjs-auth";');
40
+ extensionsImportLines.push('var AuthExtension = require("mushroomjs-auth");');
40
41
  extensionsExportLines.push('Auth: AuthExtension');
41
42
  extensionsCodeLines.push("AuthExtension.useAuth(AuthExtension.AuthLocalStorage);");
42
43
  }
43
44
  if (aliasProject.features.includes("file")) {
44
- extensionsImportLines.push('import * as FileExtension from "mushroomjs-file";');
45
+ extensionsImportLines.push('//import * as FileExtension from "mushroomjs-file";');
46
+ extensionsImportLines.push('var FileExtension = require("mushroomjs-file");');
45
47
  extensionsExportLines.push('File: FileExtension');
46
48
  extensionsCodeLines.push("FileExtension.useFile();");
47
49
  }
48
50
  }
49
51
 
50
- let code = `import mushroom, {defineAsyncResource} from "mushroomjs";
51
- export * from "mushroomjs";
52
+ let code = `//import mushroom, {defineAsyncResource} from "mushroomjs";
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ var mushroom_1 = require("mushroomjs");
55
+ var mushroom = mushroom_1.default;
56
+ var defineAsyncResource = mushroom_1.defineAsyncResource;
57
+
58
+ //export * from "mushroomjs";
59
+ for (var m in mushroom_1) exports[m] = mushroom_1[m];
60
+
52
61
  ${extensionsImportLines.join("\n")}
53
- export const extensions = {
62
+ //export const extensions = {
63
+ var extensions = {
54
64
  ${extensionsExportLines.join(",\n ")}
55
65
  };
66
+ exports.extensions = extensions;
56
67
 
57
68
  "use strict";
58
69
 
@@ -88,7 +99,8 @@ mushroom.$using(${JSON.stringify(common.getRootUrl(source))});
88
99
 
89
100
  ${extensionsCodeLines.join('\n')}
90
101
 
91
- export default mushroom;`;
102
+ //export default mushroom;
103
+ exports.default = mushroom;`;
92
104
 
93
105
  return code;
94
106
  }
@@ -38,7 +38,7 @@ function toTypeScriptClassName(str) {
38
38
  return "_";
39
39
  const name = toVietnameseNonTongue(str).replace(/\W/g, "_");
40
40
  const c = name.charAt(0);
41
- return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substr(1);
41
+ return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substring(1);
42
42
  }
43
43
 
44
44
  function getCSharpTypeFromMushroomType(type) {
@@ -196,7 +196,7 @@ export type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoI
196
196
  }
197
197
  default: {
198
198
  if (actionName.indexOf("_raw_http_method_") === 0) {
199
- customMethodCode += ` ${actionName.substr("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
199
+ customMethodCode += ` ${actionName.substring("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
200
200
  `;
201
201
  break;
202
202
  }
@@ -363,7 +363,7 @@ export declare type IdValue = ${source.idType == "AutoIncInt" || source.idType =
363
363
  }
364
364
  default: {
365
365
  if (actionName.indexOf("_raw_http_method_") === 0) {
366
- customMethodCode += ` ${actionName.substr("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
366
+ customMethodCode += ` ${actionName.substring("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
367
367
  `;
368
368
  break;
369
369
  }
package/gen.js CHANGED
@@ -24,8 +24,8 @@ async function gen(args) {
24
24
 
25
25
  const atIndex = projectName.indexOf("@");
26
26
  if (atIndex !== -1) {
27
- alias = projectName.substr(atIndex + 1);
28
- projectName = projectName.substr(0, atIndex);
27
+ alias = projectName.substring(atIndex + 1);
28
+ projectName = projectName.substring(0, atIndex);
29
29
  if (!projectName) {
30
30
  help(args);
31
31
  return;
@@ -205,7 +205,7 @@ function processMasterFile(basePath, master) {
205
205
  action.defaultSortings = action.sorting.split(',').map(f => {
206
206
  const c = f.charAt(0);
207
207
  return {
208
- field: c === "+" || c === "-" ? f.substr(1) : f,
208
+ field: c === "+" || c === "-" ? f.substring(1) : f,
209
209
  type: c === "-" ? "Desc" : "Asc"
210
210
  }
211
211
  });
@@ -216,7 +216,7 @@ function processMasterFile(basePath, master) {
216
216
  action.allowSortings = action.allowSorting.split(',').map(f => {
217
217
  const c = f.charAt(0);
218
218
  return {
219
- field: c === "+" || c === "-" ? f.substr(1) : f,
219
+ field: c === "+" || c === "-" ? f.substring(1) : f,
220
220
  type: c === "-" ? "Desc" : c === "+" ? "Asc" : "Both"
221
221
  }
222
222
  });
package/mr.js CHANGED
@@ -5,12 +5,12 @@ const config = require("./config.js");
5
5
  const gen = require("./gen.js");
6
6
  const help = require("./help.js");
7
7
 
8
- const package = require("./package.json");
8
+ const pkg = require("./package.json");
9
9
  const checkUpdate = require("./check-update");
10
10
 
11
- const versionGroup = package.version.match(/([^-]+)(-(\w+).*)?/);
11
+ const versionGroup = pkg.version.match(/([^-]+)(-(\w+).*)?/);
12
12
  const currentDistTag = versionGroup[3] ? versionGroup[3] : "latest";
13
- console.log("Mushroom CLI version " + package.version);
13
+ console.log("Mushroom CLI version " + pkg.version);
14
14
 
15
15
  async function run(args) {
16
16
  let debugMode = false;
@@ -63,7 +63,7 @@ async function run(args) {
63
63
  if (checkUpdateTask !== null)
64
64
  try {
65
65
  var data = await checkUpdateTask;
66
- if (data["dist-tags"] && data["dist-tags"][currentDistTag] && data["dist-tags"][currentDistTag] !== package.version) {
66
+ if (data["dist-tags"] && data["dist-tags"][currentDistTag] && data["dist-tags"][currentDistTag] !== pkg.version) {
67
67
  console.warn(`YOUR mushroom-cli VERSION IS NOT LATEST (dist-tags: ${currentDistTag}). PLEASE RUN: npm i mushroom-cli@${data["dist-tags"][currentDistTag]}`);
68
68
  }
69
69
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mushroom-cli",
3
- "version": "1.1.0-alpha.10",
3
+ "version": "1.1.0-alpha.13",
4
4
  "description": "Mushroom CLI",
5
5
  "main": "mr.js",
6
6
  "scripts": {
@@ -17,10 +17,10 @@
17
17
  "author": "suco2007",
18
18
  "license": "ISC",
19
19
  "dependencies": {
20
- "jsdom": "^16.2.2",
21
- "json5": "^2.1.2",
22
- "node-fetch": "^2.6.0",
23
- "open": "^7.0.3",
20
+ "jsdom": "^19.0.0",
21
+ "json5": "^2.2.1",
22
+ "node-fetch": "^2.6.7",
23
+ "open": "^8.4.0",
24
24
  "readline-sync": "^1.4.10",
25
25
  "targz": "^1.0.1"
26
26
  }