@colyseus/schema 1.0.44 → 1.0.45

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.
@@ -51,12 +51,19 @@ var capitalize = function (s) {
51
51
  return s.charAt(0).toUpperCase() + s.slice(1);
52
52
  };
53
53
  function generate(context, options) {
54
- return __spreadArray(__spreadArray([], __read(context.classes.map(function (structure) { return ({
54
+ // enrich typeMaps with enums
55
+ context.enums.forEach(function (structure) {
56
+ typeMaps[structure.name] = structure.name;
57
+ });
58
+ return __spreadArray(__spreadArray(__spreadArray([], __read(context.classes.map(function (structure) { return ({
55
59
  name: "".concat(structure.name, ".cs"),
56
60
  content: generateClass(structure, options.namespace)
57
61
  }); })), false), __read(context.interfaces.map(function (structure) { return ({
58
62
  name: "".concat(structure.name, ".cs"),
59
- content: generateInterface(structure, options.namespace)
63
+ content: generateInterface(structure, options.namespace),
64
+ }); })), false), __read(context.enums.filter(function (structure) { return structure.name !== 'OPERATION'; }).map(function (structure) { return ({
65
+ name: "".concat(structure.name, ".cs"),
66
+ content: generateEnum(structure, options.namespace),
60
67
  }); })), false);
61
68
  }
62
69
  exports.generate = generate;
@@ -64,6 +71,29 @@ function generateClass(klass, namespace) {
64
71
  var indent = (namespace) ? "\t" : "";
65
72
  return "".concat((0, types_1.getCommentHeader)(), "\n\nusing Colyseus.Schema;\n").concat(namespace ? "\nnamespace ".concat(namespace, " {") : "", "\n").concat(indent, "public partial class ").concat(klass.name, " : ").concat(klass.extends, " {\n").concat(klass.properties.map(function (prop) { return generateProperty(prop, indent); }).join("\n\n"), "\n").concat(indent, "}\n").concat(namespace ? "}" : "", "\n");
66
73
  }
74
+ function generateEnum(_enum, namespace) {
75
+ var indent = namespace ? "\t" : "";
76
+ return "".concat((0, types_1.getCommentHeader)(), "\n").concat(namespace ? "\nnamespace ".concat(namespace, " {") : "", "\n").concat(indent, "public struct ").concat(_enum.name, " {\n\n").concat(_enum.properties
77
+ .map(function (prop) {
78
+ var dataType = "int";
79
+ var value;
80
+ if (prop.type) {
81
+ if (isNaN(Number(prop.type))) {
82
+ value = prop.type;
83
+ dataType = "string";
84
+ }
85
+ else {
86
+ value = Number(prop.type);
87
+ dataType = Number.isInteger(value) ? 'int' : 'float';
88
+ }
89
+ }
90
+ else {
91
+ value = _enum.properties.indexOf(prop);
92
+ }
93
+ return "".concat(indent, "\tpublic const ").concat(dataType, " ").concat(prop.name, " = ").concat(value, ";");
94
+ })
95
+ .join("\n"), "\n").concat(indent, "}");
96
+ }
67
97
  function generateProperty(prop, indent) {
68
98
  if (indent === void 0) { indent = ""; }
69
99
  var typeArgs = "\"".concat(prop.type, "\"");
@@ -1 +1 @@
1
- {"version":3,"file":"csharp.js","sourceRoot":"","sources":["../../../src/codegen/languages/csharp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,kCAA8E;AAI9E,IAAM,QAAQ,GAAG;IACb,QAAQ,EAAE,QAAQ;IAClB,QAAQ,EAAE,OAAO;IACjB,SAAS,EAAE,MAAM;IACjB,MAAM,EAAE,OAAO;IACf,OAAO,EAAE,MAAM;IACf,OAAO,EAAE,OAAO;IAChB,QAAQ,EAAE,QAAQ;IAClB,OAAO,EAAE,KAAK;IACd,QAAQ,EAAE,MAAM;IAChB,OAAO,EAAE,MAAM;IACf,QAAQ,EAAE,OAAO;IACjB,SAAS,EAAE,OAAO;IAClB,SAAS,EAAE,QAAQ;CACtB,CAAA;AAED;;GAEG;AACH,IAAM,UAAU,GAAG,UAAC,CAAC;IACjB,IAAI,OAAO,CAAC,KAAK,QAAQ;QAAE,OAAO,EAAE,CAAA;IACpC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAClD,CAAC,CAAA;AAED,SAAgB,QAAQ,CAAE,OAAgB,EAAE,OAAwB;IAChE,8CACO,OAAO,CAAC,OAAO,CAAC,GAAG,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SAAiB;IAC3D,IAAM,MAAM,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;IACvC,OAAO,UAAG,IAAA,wBAAgB,GAAE,yCAG9B,SAAS,CAAC,CAAC,CAAC,sBAAe,SAAS,OAAI,CAAC,CAAC,CAAC,EAAE,eAC7C,MAAM,0BAAgB,MAAM,CAAC,IAAI,iBACjC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,UAAA,IAAI,IAAI,OAAA,YAAK,MAAM,oBAAU,OAAO,CAAC,IAAI,CAAC,cAAI,IAAI,CAAC,IAAI,MAAG,EAAlD,CAAkD,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,eAC5F,MAAM,gBACN,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,OACrB,CAAC;AACF,CAAC;AAED,SAAS,YAAY,CAAC,IAAc;IAChC,OAAO,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AACpC,CAAC;AAED,SAAS,OAAO,CAAC,IAAc;IAC3B,OAAO,CAAC,IAAI,CAAC,IAAI,KAAK,OAAO,CAAC;QAC1B,CAAC,CAAC,UAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,SAAS,OAAI;QACnD,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC","sourcesContent":["import { Class, Property, File, getCommentHeader, Interface } from \"../types\";\nimport { GenerateOptions } from \"../api\";\nimport { Context } from \"../types\";\n\nconst typeMaps = {\n \"string\": \"string\",\n \"number\": \"float\",\n \"boolean\": \"bool\",\n \"int8\": \"sbyte\",\n \"uint8\": \"byte\",\n \"int16\": \"short\",\n \"uint16\": \"ushort\",\n \"int32\": \"int\",\n \"uint32\": \"uint\",\n \"int64\": \"long\",\n \"uint64\": \"ulong\",\n \"float32\": \"float\",\n \"float64\": \"double\",\n}\n\n/**\n * C# Code Generator\n */\nconst capitalize = (s) => {\n if (typeof s !== 'string') return ''\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nexport function generate (context: Context, options: GenerateOptions): File[] {\n return [\n ...context.classes.map(structure => ({\n name: `${structure.name}.cs`,\n content: generateClass(structure, options.namespace)\n })),\n ...context.interfaces.map(structure => ({\n name: `${structure.name}.cs`,\n content: generateInterface(structure, options.namespace)\n }))\n ];\n}\n\nfunction generateClass(klass: Class, namespace: string) {\n const indent = (namespace) ? \"\\t\" : \"\";\n return `${getCommentHeader()}\n\nusing Colyseus.Schema;\n${namespace ? `\\nnamespace ${namespace} {` : \"\"}\n${indent}public partial class ${klass.name} : ${klass.extends} {\n${klass.properties.map(prop => generateProperty(prop, indent)).join(\"\\n\\n\")}\n${indent}}\n${namespace ? \"}\" : \"\"}\n`;\n}\n\nfunction generateProperty(prop: Property, indent: string = \"\") {\n let typeArgs = `\"${prop.type}\"`;\n let property = \"public\";\n let langType: string;\n let initializer = \"\";\n\n if (prop.childType) {\n const isUpcaseFirst = prop.childType.match(/^[A-Z]/);\n\n if(prop.type === \"ref\") {\n langType = (isUpcaseFirst)\n ? prop.childType\n : getChildType(prop);\n\n } else {\n const containerClass = capitalize(prop.type);\n\n langType = (isUpcaseFirst)\n ? `${containerClass}Schema<${prop.childType}>`\n : `${containerClass}Schema<${getChildType(prop)}>`;\n }\n\n typeArgs += `, typeof(${langType})`;\n\n if (!isUpcaseFirst) {\n typeArgs += `, \"${prop.childType}\"`;\n }\n\n initializer = `new ${langType}()`;\n\n } else {\n langType = getType(prop);\n initializer = `default(${langType})`;\n }\n\n property += ` ${langType} ${prop.name}`;\n\n let ret = (prop.deprecated) ? `\\t\\t[System.Obsolete(\"field '${prop.name}' is deprecated.\", true)]\\n` : '';\n\n return ret + `\\t${indent}[Type(${prop.index}, ${typeArgs})]\n\\t${indent}${property} = ${initializer};`;\n}\n\nfunction generateInterface(struct: Interface, namespace: string) {\n const indent = (namespace) ? \"\\t\" : \"\";\n return `${getCommentHeader()}\n\nusing Colyseus.Schema;\n${namespace ? `\\nnamespace ${namespace} {` : \"\"}\n${indent}public class ${struct.name} {\n${struct.properties.map(prop => `\\t${indent}public ${getType(prop)} ${prop.name};`).join(\"\\n\")}\n${indent}}\n${namespace ? \"}\" : \"\"}\n`;\n}\n\nfunction getChildType(prop: Property) {\n return typeMaps[prop.childType];\n}\n\nfunction getType(prop: Property) {\n return (prop.type === \"array\")\n ? `${typeMaps[prop.childType] || prop.childType}[]`\n : typeMaps[prop.type];\n}"]}
1
+ {"version":3,"file":"csharp.js","sourceRoot":"","sources":["../../../src/codegen/languages/csharp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,kCAOkB;AAIlB,IAAM,QAAQ,GAAG;IACb,QAAQ,EAAE,QAAQ;IAClB,QAAQ,EAAE,OAAO;IACjB,SAAS,EAAE,MAAM;IACjB,MAAM,EAAE,OAAO;IACf,OAAO,EAAE,MAAM;IACf,OAAO,EAAE,OAAO;IAChB,QAAQ,EAAE,QAAQ;IAClB,OAAO,EAAE,KAAK;IACd,QAAQ,EAAE,MAAM;IAChB,OAAO,EAAE,MAAM;IACf,QAAQ,EAAE,OAAO;IACjB,SAAS,EAAE,OAAO;IAClB,SAAS,EAAE,QAAQ;CACtB,CAAA;AAED;;GAEG;AACH,IAAM,UAAU,GAAG,UAAC,CAAC;IACjB,IAAI,OAAO,CAAC,KAAK,QAAQ;QAAE,OAAO,EAAE,CAAA;IACpC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAClD,CAAC,CAAA;AAED,SAAgB,QAAQ,CAAC,OAAgB,EAAE,OAAwB;IAC/D,6BAA6B;IAC7B,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,UAAC,SAAS;QAC5B,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,IA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,EAAE,CAAC;IAE1G,OAAO,GAAG,GAAG,YAAK,MAAM,mBAAS,IAAI,CAAC,KAAK,eAAK,QAAQ,mBACxD,MAAM,SAAG,QAAQ,gBAAM,WAAW,MAAG,CAAC;AAC1C,CAAC;AAED,SAAS,iBAAiB,CAAC,MAAiB,EAAE,SAAiB;IAC3D,IAAM,MAAM,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;IACvC,OAAO,UAAG,IAAA,wBAAgB,GAAE,yCAG9B,SAAS,CAAC,CAAC,CAAC,sBAAe,SAAS,OAAI,CAAC,CAAC,CAAC,EAAE,eAC7C,MAAM,0BAAgB,MAAM,CAAC,IAAI,iBACjC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,UAAA,IAAI,IAAI,OAAA,YAAK,MAAM,oBAAU,OAAO,CAAC,IAAI,CAAC,cAAI,IAAI,CAAC,IAAI,MAAG,EAAlD,CAAkD,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,eAC5F,MAAM,gBACN,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,OACrB,CAAC;AACF,CAAC;AAED,SAAS,YAAY,CAAC,IAAc;IAChC,OAAO,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AACpC,CAAC;AAED,SAAS,OAAO,CAAC,IAAc;IAC3B,OAAO,CAAC,IAAI,CAAC,IAAI,KAAK,OAAO,CAAC;QAC1B,CAAC,CAAC,UAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,SAAS,OAAI;QACnD,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC","sourcesContent":["import {\n Class,\n Property,\n File,\n getCommentHeader,\n Interface,\n Enum,\n} from \"../types\";\nimport { GenerateOptions } from \"../api\";\nimport { Context } from \"../types\";\n\nconst typeMaps = {\n \"string\": \"string\",\n \"number\": \"float\",\n \"boolean\": \"bool\",\n \"int8\": \"sbyte\",\n \"uint8\": \"byte\",\n \"int16\": \"short\",\n \"uint16\": \"ushort\",\n \"int32\": \"int\",\n \"uint32\": \"uint\",\n \"int64\": \"long\",\n \"uint64\": \"ulong\",\n \"float32\": \"float\",\n \"float64\": \"double\",\n}\n\n/**\n * C# Code Generator\n */\nconst capitalize = (s) => {\n if (typeof s !== 'string') return ''\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nexport function generate(context: Context, options: GenerateOptions): File[] {\n // enrich typeMaps with enums\n context.enums.forEach((structure) => {\n typeMaps[structure.name] = structure.name;\n });\n return [\n ...context.classes.map(structure => ({\n name: `${structure.name}.cs`,\n content: generateClass(structure, options.namespace)\n })),\n ...context.interfaces.map(structure => ({\n name: `${structure.name}.cs`,\n content: generateInterface(structure, options.namespace),\n })),\n ...context.enums.filter(structure => structure.name !== 'OPERATION').map((structure) => ({\n name: `${structure.name}.cs`,\n content: generateEnum(structure, options.namespace),\n })),\n ];\n}\n\nfunction generateClass(klass: Class, namespace: string) {\n const indent = (namespace) ? \"\\t\" : \"\";\n return `${getCommentHeader()}\n\nusing Colyseus.Schema;\n${namespace ? `\\nnamespace ${namespace} {` : \"\"}\n${indent}public partial class ${klass.name} : ${klass.extends} {\n${klass.properties.map((prop) => generateProperty(prop, indent)).join(\"\\n\\n\")}\n${indent}}\n${namespace ? \"}\" : \"\"}\n`;\n}\n\nfunction generateEnum(_enum: Enum, namespace: string) {\n const indent = namespace ? \"\\t\" : \"\";\n return `${getCommentHeader()}\n${namespace ? `\\nnamespace ${namespace} {` : \"\"}\n${indent}public struct ${_enum.name} {\n\n${_enum.properties\n .map((prop) => {\n let dataType: string = \"int\";\n let value: any;\n\n if(prop.type) {\n if(isNaN(Number(prop.type))) {\n value = prop.type;\n dataType = \"string\";\n } else {\n value = Number(prop.type);\n dataType = Number.isInteger(value)? 'int': 'float';\n }\n } else {\n value = _enum.properties.indexOf(prop);\n }\n return `${indent}\\tpublic const ${dataType} ${prop.name} = ${value};`;\n })\n .join(\"\\n\")}\n${indent}}`\n}\n\nfunction generateProperty(prop: Property, indent: string = \"\") {\n let typeArgs = `\"${prop.type}\"`;\n let property = \"public\";\n let langType: string;\n let initializer = \"\";\n\n if (prop.childType) {\n const isUpcaseFirst = prop.childType.match(/^[A-Z]/);\n\n if(prop.type === \"ref\") {\n langType = (isUpcaseFirst)\n ? prop.childType\n : getChildType(prop);\n\n } else {\n const containerClass = capitalize(prop.type);\n\n langType = (isUpcaseFirst)\n ? `${containerClass}Schema<${prop.childType}>`\n : `${containerClass}Schema<${getChildType(prop)}>`;\n }\n\n typeArgs += `, typeof(${langType})`;\n\n if (!isUpcaseFirst) {\n typeArgs += `, \"${prop.childType}\"`;\n }\n\n initializer = `new ${langType}()`;\n\n } else {\n langType = getType(prop);\n initializer = `default(${langType})`;\n }\n\n property += ` ${langType} ${prop.name}`;\n\n let ret = (prop.deprecated) ? `\\t\\t[System.Obsolete(\"field '${prop.name}' is deprecated.\", true)]\\n` : '';\n\n return ret + `\\t${indent}[Type(${prop.index}, ${typeArgs})]\n\\t${indent}${property} = ${initializer};`;\n}\n\nfunction generateInterface(struct: Interface, namespace: string) {\n const indent = (namespace) ? \"\\t\" : \"\";\n return `${getCommentHeader()}\n\nusing Colyseus.Schema;\n${namespace ? `\\nnamespace ${namespace} {` : \"\"}\n${indent}public class ${struct.name} {\n${struct.properties.map(prop => `\\t${indent}public ${getType(prop)} ${prop.name};`).join(\"\\n\")}\n${indent}}\n${namespace ? \"}\" : \"\"}\n`;\n}\n\nfunction getChildType(prop: Property) {\n return typeMaps[prop.childType];\n}\n\nfunction getType(prop: Property) {\n return (prop.type === \"array\")\n ? `${typeMaps[prop.childType] || prop.childType}[]`\n : typeMaps[prop.type];\n}"]}
@@ -1,8 +1,9 @@
1
1
  import * as ts from "typescript";
2
- import { Class, Interface, Context } from "./types";
2
+ import { Class, Interface, Context, Enum } from "./types";
3
3
  export declare function parseFiles(fileNames: string[], decoratorName?: string, context?: Context): {
4
4
  classes: Class[];
5
5
  interfaces: Interface[];
6
+ enums: Enum[];
6
7
  };
7
8
  /**
8
9
  * TypeScript 4.8+ has introduced a change on how to access decorators.
@@ -26,7 +26,7 @@ function defineProperty(property, initializer) {
26
26
  }
27
27
  }
28
28
  function inspectNode(node, context, decoratorName) {
29
- var _a, _b, _c, _d, _e;
29
+ var _a, _b, _c, _d, _e, _f;
30
30
  switch (node.kind) {
31
31
  case ts.SyntaxKind.ImportClause:
32
32
  var specifier = node.parent.moduleSpecifier;
@@ -56,6 +56,12 @@ function inspectNode(node, context, decoratorName) {
56
56
  context.addStructure(currentStructure);
57
57
  }
58
58
  break;
59
+ case ts.SyntaxKind.EnumDeclaration:
60
+ var enumName = node.name.escapedText.toString();
61
+ currentStructure = new types_1.Enum();
62
+ currentStructure.name = enumName;
63
+ context.addStructure(currentStructure);
64
+ break;
59
65
  case ts.SyntaxKind.ExtendsKeyword:
60
66
  // console.log(node.getText());
61
67
  break;
@@ -146,6 +152,19 @@ function inspectNode(node, context, decoratorName) {
146
152
  }
147
153
  currentProperty = undefined;
148
154
  break;
155
+ case ts.SyntaxKind.EnumMember:
156
+ if (currentStructure instanceof types_1.Enum) {
157
+ var initializer = (_f = node.initializer) === null || _f === void 0 ? void 0 : _f.getText();
158
+ var name = node.getFirstToken().getText();
159
+ var property = currentProperty || new types_1.Property();
160
+ property.name = name;
161
+ if (initializer !== undefined) {
162
+ property.type = initializer;
163
+ }
164
+ currentStructure.addProperty(property);
165
+ currentProperty = undefined;
166
+ }
167
+ break;
149
168
  }
150
169
  ts.forEachChild(node, function (n) { return inspectNode(n, context, decoratorName); });
151
170
  }
@@ -1 +1 @@
1
- {"version":3,"file":"parser.js","sourceRoot":"","sources":["../../src/codegen/parser.ts"],"names":[],"mappings":";;;AAAA,+BAAiC;AACjC,2BAA6B;AAC7B,yBAAkC;AAClC,iCAA0E;AAE1E,IAAI,gBAA4B,CAAC;AACjC,IAAI,eAAyB,CAA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WAAW,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC;gBAEnC,MAAM;aACT;YAAC,OAAO,CAAC,EAAE;gBACR,6DAA6D;aAChE;SACJ;QAED,IAAI,UAAU,EAAE;YACZ,WAAW,CAAC,UAAU,EAAE,OAAO,EAAE,aAAa,CAAC,CAAC;SACnD;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC,aAAa,EAAE,CAAC;AACnC,CAAC;AA5DD,gCA4DC;AAED;;;;GAIG;AACH,SAAgB,aAAa,CAAC,IAAgC;;IAC1D,IAAI,IAAI,IAAI,SAAS,EAAE;QAAE,OAAO,SAAS,CAAC;KAAE;IAE5C,2BAA2B;IAC3B,aAAa;IACb,IAAI,IAAI,CAAC,UAAU,EAAE;QAAE,OAAO,IAAI,CAAC,UAAU,CAAC;KAAE;IAEhD,2BAA2B;IAC3B,aAAa;IACb,IAAI,EAAE,CAAC,iBAAiB,IAAI,EAAE,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;QACpD,aAAa;QACb,IAAM,UAAU,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QAC1C,OAAO,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;KAC1D;IAED,aAAa;IACb,OAAO,MAAA,IAAI,CAAC,SAAS,0CAAE,MAAM,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC;AAClD,CAAC;AAjBD,sCAiBC","sourcesContent":["import * as ts from \"typescript\";\nimport * as path from \"path\";\nimport { readFileSync } from \"fs\";\nimport { IStructure, Class, Interface, Property, Context } from \"./types\";\n\nlet currentStructure: IStructure;\nlet currentProperty: Property;\n\nlet globalContext: Context;\n\nfunction defineProperty(property: Property, initializer: any) {\n if (ts.isIdentifier(initializer)) {\n property.type = \"ref\";\n property.childType = initializer.text;\n\n } else if (initializer.kind == ts.SyntaxKind.ObjectLiteralExpression) {\n property.type = initializer.properties[0].name.text;\n property.childType = initializer.properties[0].initializer.text;\n\n } else if (initializer.kind == ts.SyntaxKind.ArrayLiteralExpression) {\n property.type = \"array\";\n property.childType = initializer.elements[0].text;\n\n } else {\n property.type = initializer.text;\n }\n}\n\nfunction inspectNode(node: ts.Node, context: Context, decoratorName: string) {\n switch (node.kind) {\n case ts.SyntaxKind.ImportClause:\n const specifier = (node.parent as any).moduleSpecifier;\n if (specifier && (specifier.text as string).startsWith('.')) {\n const currentDir = path.dirname(node.getSourceFile().fileName);\n const pathToImport = path.resolve(currentDir, specifier.text);\n parseFiles([pathToImport], decoratorName, globalContext);\n }\n break;\n\n case ts.SyntaxKind.ClassDeclaration:\n currentStructure = new Class();\n\n const heritageClauses = (node as ts.ClassLikeDeclarationBase).heritageClauses;\n if (heritageClauses && heritageClauses.length > 0) {\n (currentStructure as Class).extends = heritageClauses[0].types[0].expression.getText();\n }\n\n context.addStructure(currentStructure);\n break;\n\n case ts.SyntaxKind.InterfaceDeclaration:\n //\n // Only generate Interfaces if it has \"Message\" on its name.\n // Example: MyMessage\n //\n const interfaceName = (node as ts.TypeParameterDeclaration).name.escapedText.toString();\n if (interfaceName.indexOf(\"Message\") !== -1) {\n currentStructure = new Interface();\n currentStructure.name = interfaceName;\n\n context.addStructure(currentStructure);\n }\n break;\n\n case ts.SyntaxKind.ExtendsKeyword:\n // console.log(node.getText());\n break;\n\n case ts.SyntaxKind.PropertySignature:\n if (currentStructure instanceof Interface) {\n const interfaceDeclaration = node.parent;\n\n if (\n currentStructure.name !== (interfaceDeclaration as ts.TypeParameterDeclaration).name.escapedText.toString()\n ) {\n // skip if property if for a another interface than the one we're interested in.\n break;\n }\n\n // define a property of an interface\n const property = new Property();\n property.name = (node as any).name.escapedText.toString();\n property.type = (node as any).type.getText();\n currentStructure.addProperty(property);\n }\n break;\n\n case ts.SyntaxKind.Identifier:\n if (\n node.getText() === \"deprecated\" &&\n node.parent.kind !== ts.SyntaxKind.ImportSpecifier\n ) {\n currentProperty = new Property();\n currentProperty.deprecated = true;\n break;\n }\n\n if (node.getText() === decoratorName) {\n const prop: any = node.parent?.parent?.parent;\n const propDecorator = getDecorators(prop);\n const hasExpression = prop?.expression?.arguments;\n const hasDecorator = (propDecorator?.length > 0);\n\n /**\n * neither a `@type()` decorator or `type()` call. skip.\n */\n if (!hasDecorator && !hasExpression) {\n break;\n }\n\n // using as decorator\n if (propDecorator) {\n /**\n * Calling `@type()` as decorator\n */\n const typeDecorator: any = propDecorator.find((decorator => {\n return (decorator.expression as any).expression.escapedText === decoratorName;\n })).expression;\n\n const property = currentProperty || new Property();\n property.name = prop.name.escapedText;\n currentStructure.addProperty(property);\n\n const typeArgument = typeDecorator.arguments[0];\n defineProperty(property, typeArgument);\n\n } else if (\n prop.expression.arguments?.[1] &&\n prop.expression.expression.arguments?.[0]\n ) {\n /**\n * Calling `type()` as a regular method\n */\n const property = currentProperty || new Property();\n property.name = prop.expression.arguments[1].text;\n currentStructure.addProperty(property);\n\n const typeArgument = prop.expression.expression.arguments[0];\n defineProperty(property, typeArgument);\n }\n\n\n } else if (\n node.getText() === \"defineTypes\" &&\n (\n node.parent.kind === ts.SyntaxKind.CallExpression ||\n node.parent.kind === ts.SyntaxKind.PropertyAccessExpression\n )\n ) {\n /**\n * JavaScript source file (`.js`)\n * Using `defineTypes()`\n */\n const callExpression = (node.parent.kind === ts.SyntaxKind.PropertyAccessExpression)\n ? node.parent.parent as ts.CallExpression\n : node.parent as ts.CallExpression;\n\n if (callExpression.kind !== ts.SyntaxKind.CallExpression) {\n break;\n }\n\n const className = callExpression.arguments[0].getText()\n currentStructure.name = className;\n\n const types = callExpression.arguments[1] as any;\n for (let i=0; i<types.properties.length; i++) {\n const prop = types.properties[i];\n\n const property = currentProperty || new Property();\n property.name = prop.name.escapedText;\n currentStructure.addProperty(property);\n\n defineProperty(property, prop.initializer);\n }\n\n }\n\n if (node.parent.kind === ts.SyntaxKind.ClassDeclaration) {\n currentStructure.name = node.getText();\n }\n\n currentProperty = undefined;\n\n break;\n }\n\n ts.forEachChild(node, (n) => inspectNode(n, context, decoratorName));\n}\n\nlet parsedFiles: { [filename: string]: boolean };\n\nexport function parseFiles(\n fileNames: string[],\n decoratorName: string = \"type\",\n context: Context = new Context()\n) {\n /**\n * Re-set globalContext for each test case\n */\n if (globalContext !== context) {\n parsedFiles = {};\n globalContext = context;\n }\n\n fileNames.forEach((fileName) => {\n let sourceFile: ts.Node;\n let sourceFileName: string;\n\n const fileNameAlternatives = [];\n\n if (\n !fileName.endsWith(\".ts\") &&\n !fileName.endsWith(\".js\") &&\n !fileName.endsWith(\".mjs\")\n ) {\n fileNameAlternatives.push(`${fileName}.ts`);\n fileNameAlternatives.push(`${fileName}/index.ts`);\n\n } else {\n fileNameAlternatives.push(fileName);\n }\n\n for (let i = 0; i < fileNameAlternatives.length; i++) {\n try {\n sourceFileName = path.resolve(fileNameAlternatives[i]);\n\n if (parsedFiles[sourceFileName]) {\n break;\n }\n\n sourceFile = ts.createSourceFile(\n sourceFileName,\n readFileSync(sourceFileName).toString(),\n ts.ScriptTarget.Latest,\n true\n );\n\n parsedFiles[sourceFileName] = true;\n\n break;\n } catch (e) {\n // console.log(`${fileNameAlternatives[i]} => ${e.message}`);\n }\n }\n\n if (sourceFile) {\n inspectNode(sourceFile, context, decoratorName);\n }\n });\n\n return context.getStructures();\n}\n\n/**\n * TypeScript 4.8+ has introduced a change on how to access decorators.\n * - https://github.com/microsoft/TypeScript/pull/49089\n * - https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/#decorators-are-placed-on-modifiers-on-typescripts-syntax-trees\n */\nexport function getDecorators(node: ts.Node | null | undefined,): undefined | ts.Decorator[] {\n if (node == undefined) { return undefined; }\n\n // TypeScript 4.7 and below\n // @ts-ignore\n if (node.decorators) { return node.decorators; }\n\n // TypeScript 4.8 and above\n // @ts-ignore\n if (ts.canHaveDecorators && ts.canHaveDecorators(node)) {\n // @ts-ignore\n const decorators = ts.getDecorators(node);\n return decorators ? Array.from(decorators) : undefined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AAC,CAAC;SACnD;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC,aAAa,EAAE,CAAC;AACnC,CAAC;AA5DD,gCA4DC;AAED;;;;GAIG;AACH,SAAgB,aAAa,CAAC,IAAgC;;IAC1D,IAAI,IAAI,IAAI,SAAS,EAAE;QAAE,OAAO,SAAS,CAAC;KAAE;IAE5C,2BAA2B;IAC3B,aAAa;IACb,IAAI,IAAI,CAAC,UAAU,EAAE;QAAE,OAAO,IAAI,CAAC,UAAU,CAAC;KAAE;IAEhD,2BAA2B;IAC3B,aAAa;IACb,IAAI,EAAE,CAAC,iBAAiB,IAAI,EAAE,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;QACpD,aAAa;QACb,IAAM,UAAU,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QAC1C,OAAO,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;KAC1D;IAED,aAAa;IACb,OAAO,MAAA,IAAI,CAAC,SAAS,0CAAE,MAAM,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC;AAClD,CAAC;AAjBD,sCAiBC","sourcesContent":["import * as ts from \"typescript\";\nimport * as path from \"path\";\nimport { readFileSync } from \"fs\";\nimport { IStructure, Class, Interface, Property, Context, Enum } from \"./types\";\n\nlet currentStructure: IStructure;\nlet currentProperty: Property;\n\nlet globalContext: Context;\n\nfunction defineProperty(property: Property, initializer: any) {\n if (ts.isIdentifier(initializer)) {\n property.type = \"ref\";\n property.childType = initializer.text;\n\n } else if (initializer.kind == ts.SyntaxKind.ObjectLiteralExpression) {\n property.type = initializer.properties[0].name.text;\n property.childType = initializer.properties[0].initializer.text;\n\n } else if (initializer.kind == ts.SyntaxKind.ArrayLiteralExpression) {\n property.type = \"array\";\n property.childType = initializer.elements[0].text;\n\n } else {\n property.type = initializer.text;\n }\n}\n\nfunction inspectNode(node: ts.Node, context: Context, decoratorName: string) {\n switch (node.kind) {\n case ts.SyntaxKind.ImportClause:\n const specifier = (node.parent as any).moduleSpecifier;\n if (specifier && (specifier.text as string).startsWith('.')) {\n const currentDir = path.dirname(node.getSourceFile().fileName);\n const pathToImport = path.resolve(currentDir, specifier.text);\n parseFiles([pathToImport], decoratorName, globalContext);\n }\n break;\n\n case ts.SyntaxKind.ClassDeclaration:\n currentStructure = new Class();\n\n const heritageClauses = (node as ts.ClassLikeDeclarationBase).heritageClauses;\n if (heritageClauses && heritageClauses.length > 0) {\n (currentStructure as Class).extends = heritageClauses[0].types[0].expression.getText();\n }\n\n context.addStructure(currentStructure);\n break;\n\n case ts.SyntaxKind.InterfaceDeclaration:\n //\n // Only generate Interfaces if it has \"Message\" on its name.\n // Example: MyMessage\n //\n const interfaceName = (node as ts.TypeParameterDeclaration).name.escapedText.toString();\n if (interfaceName.indexOf(\"Message\") !== -1) {\n currentStructure = new Interface();\n currentStructure.name = interfaceName;\n\n context.addStructure(currentStructure);\n }\n break;\n\n case ts.SyntaxKind.EnumDeclaration:\n const enumName = (\n node as ts.EnumDeclaration\n ).name.escapedText.toString();\n currentStructure = new Enum();\n currentStructure.name = enumName;\n context.addStructure(currentStructure);\n break;\n\n case ts.SyntaxKind.ExtendsKeyword:\n // console.log(node.getText());\n break;\n\n case ts.SyntaxKind.PropertySignature:\n if (currentStructure instanceof Interface) {\n const interfaceDeclaration = node.parent;\n\n if (\n currentStructure.name !== (interfaceDeclaration as ts.TypeParameterDeclaration).name.escapedText.toString()\n ) {\n // skip if property if for a another interface than the one we're interested in.\n break;\n }\n\n // define a property of an interface\n const property = new Property();\n property.name = (node as any).name.escapedText.toString();\n property.type = (node as any).type.getText();\n currentStructure.addProperty(property);\n }\n break;\n\n case ts.SyntaxKind.Identifier:\n if (\n node.getText() === \"deprecated\" &&\n node.parent.kind !== ts.SyntaxKind.ImportSpecifier\n ) {\n currentProperty = new Property();\n currentProperty.deprecated = true;\n break;\n }\n\n if (node.getText() === decoratorName) {\n const prop: any = node.parent?.parent?.parent;\n const propDecorator = getDecorators(prop);\n const hasExpression = prop?.expression?.arguments;\n const hasDecorator = (propDecorator?.length > 0);\n\n /**\n * neither a `@type()` decorator or `type()` call. skip.\n */\n if (!hasDecorator && !hasExpression) {\n break;\n }\n\n // using as decorator\n if (propDecorator) {\n /**\n * Calling `@type()` as decorator\n */\n const typeDecorator: any = propDecorator.find((decorator => {\n return (decorator.expression as any).expression.escapedText === decoratorName;\n })).expression;\n\n const property = currentProperty || new Property();\n property.name = prop.name.escapedText;\n currentStructure.addProperty(property);\n\n const typeArgument = typeDecorator.arguments[0];\n defineProperty(property, typeArgument);\n\n } else if (\n prop.expression.arguments?.[1] &&\n prop.expression.expression.arguments?.[0]\n ) {\n /**\n * Calling `type()` as a regular method\n */\n const property = currentProperty || new Property();\n property.name = prop.expression.arguments[1].text;\n currentStructure.addProperty(property);\n\n const typeArgument = prop.expression.expression.arguments[0];\n defineProperty(property, typeArgument);\n }\n\n\n } else if (\n node.getText() === \"defineTypes\" &&\n (\n node.parent.kind === ts.SyntaxKind.CallExpression ||\n node.parent.kind === ts.SyntaxKind.PropertyAccessExpression\n )\n ) {\n /**\n * JavaScript source file (`.js`)\n * Using `defineTypes()`\n */\n const callExpression = (node.parent.kind === ts.SyntaxKind.PropertyAccessExpression)\n ? node.parent.parent as ts.CallExpression\n : node.parent as ts.CallExpression;\n\n if (callExpression.kind !== ts.SyntaxKind.CallExpression) {\n break;\n }\n\n const className = callExpression.arguments[0].getText()\n currentStructure.name = className;\n\n const types = callExpression.arguments[1] as any;\n for (let i=0; i<types.properties.length; i++) {\n const prop = types.properties[i];\n\n const property = currentProperty || new Property();\n property.name = prop.name.escapedText;\n currentStructure.addProperty(property);\n\n defineProperty(property, prop.initializer);\n }\n\n }\n\n if (node.parent.kind === ts.SyntaxKind.ClassDeclaration) {\n currentStructure.name = node.getText();\n }\n\n currentProperty = undefined;\n\n break;\n\n case ts.SyntaxKind.EnumMember:\n if (currentStructure instanceof Enum) {\n const initializer = (node as any).initializer?.getText();\n const name = node.getFirstToken().getText();\n const property = currentProperty || new Property();\n property.name = name;\n if (initializer !== undefined) {\n property.type = initializer;\n }\n currentStructure.addProperty(property);\n currentProperty = undefined;\n }\n break;\n }\n\n ts.forEachChild(node, (n) => inspectNode(n, context, decoratorName));\n}\n\nlet parsedFiles: { [filename: string]: boolean };\n\nexport function parseFiles(\n fileNames: string[],\n decoratorName: string = \"type\",\n context: Context = new Context()\n) {\n /**\n * Re-set globalContext for each test case\n */\n if (globalContext !== context) {\n parsedFiles = {};\n globalContext = context;\n }\n\n fileNames.forEach((fileName) => {\n let sourceFile: ts.Node;\n let sourceFileName: string;\n\n const fileNameAlternatives = [];\n\n if (\n !fileName.endsWith(\".ts\") &&\n !fileName.endsWith(\".js\") &&\n !fileName.endsWith(\".mjs\")\n ) {\n fileNameAlternatives.push(`${fileName}.ts`);\n fileNameAlternatives.push(`${fileName}/index.ts`);\n\n } else {\n fileNameAlternatives.push(fileName);\n }\n\n for (let i = 0; i < fileNameAlternatives.length; i++) {\n try {\n sourceFileName = path.resolve(fileNameAlternatives[i]);\n\n if (parsedFiles[sourceFileName]) {\n break;\n }\n\n sourceFile = ts.createSourceFile(\n sourceFileName,\n readFileSync(sourceFileName).toString(),\n ts.ScriptTarget.Latest,\n true\n );\n\n parsedFiles[sourceFileName] = true;\n\n break;\n } catch (e) {\n // console.log(`${fileNameAlternatives[i]} => ${e.message}`);\n }\n }\n\n if (sourceFile) {\n inspectNode(sourceFile, context, decoratorName);\n }\n });\n\n return context.getStructures();\n}\n\n/**\n * TypeScript 4.8+ has introduced a change on how to access decorators.\n * - https://github.com/microsoft/TypeScript/pull/49089\n * - https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/#decorators-are-placed-on-modifiers-on-typescripts-syntax-trees\n */\nexport function getDecorators(node: ts.Node | null | undefined,): undefined | ts.Decorator[] {\n if (node == undefined) { return undefined; }\n\n // TypeScript 4.7 and below\n // @ts-ignore\n if (node.decorators) { return node.decorators; }\n\n // TypeScript 4.8 and above\n // @ts-ignore\n if (ts.canHaveDecorators && ts.canHaveDecorators(node)) {\n // @ts-ignore\n const decorators = ts.getDecorators(node);\n return decorators ? Array.from(decorators) : undefined;\n }\n\n // @ts-ignore\n return node.modifiers?.filter(ts.isDecorator);\n}\n"]}
@@ -2,9 +2,11 @@ export declare function getCommentHeader(singleLineComment?: string): string;
2
2
  export declare class Context {
3
3
  classes: Class[];
4
4
  interfaces: Interface[];
5
+ enums: Enum[];
5
6
  getStructures(): {
6
7
  classes: Class[];
7
8
  interfaces: Interface[];
9
+ enums: Enum[];
8
10
  };
9
11
  addStructure(structure: IStructure): void;
10
12
  private getParentClass;
@@ -30,6 +32,12 @@ export declare class Class implements IStructure {
30
32
  addProperty(property: Property): void;
31
33
  postProcessing(): void;
32
34
  }
35
+ export declare class Enum implements IStructure {
36
+ context: Context;
37
+ name: string;
38
+ properties: Property[];
39
+ addProperty(property: Property): void;
40
+ }
33
41
  export declare class Property {
34
42
  index: number;
35
43
  name: string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getInheritanceTree = exports.Property = exports.Class = exports.Interface = exports.Context = exports.getCommentHeader = void 0;
3
+ exports.getInheritanceTree = exports.Property = exports.Enum = exports.Class = exports.Interface = exports.Context = exports.getCommentHeader = void 0;
4
4
  var fs = require("fs");
5
5
  var VERSION = JSON.parse(fs.readFileSync(__dirname + "/../../package.json").toString()).version;
6
6
  var COMMENT_HEADER = "\nTHIS FILE HAS BEEN GENERATED AUTOMATICALLY\nDO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING\n\nGENERATED USING @colyseus/schema ".concat(VERSION, "\n");
@@ -13,6 +13,7 @@ var Context = /** @class */ (function () {
13
13
  function Context() {
14
14
  this.classes = [];
15
15
  this.interfaces = [];
16
+ this.enums = [];
16
17
  }
17
18
  Context.prototype.getStructures = function () {
18
19
  var _this = this;
@@ -32,6 +33,7 @@ var Context = /** @class */ (function () {
32
33
  return false;
33
34
  }),
34
35
  interfaces: this.interfaces,
36
+ enums: this.enums,
35
37
  };
36
38
  };
37
39
  Context.prototype.addStructure = function (structure) {
@@ -42,6 +44,9 @@ var Context = /** @class */ (function () {
42
44
  else if (structure instanceof Interface) {
43
45
  this.interfaces.push(structure);
44
46
  }
47
+ else if (structure instanceof Enum) {
48
+ this.enums.push(structure);
49
+ }
45
50
  };
46
51
  Context.prototype.getParentClass = function (klass) {
47
52
  return this.classes.find(function (c) { return c.name === klass.extends; });
@@ -112,6 +117,16 @@ var Class = /** @class */ (function () {
112
117
  return Class;
113
118
  }());
114
119
  exports.Class = Class;
120
+ var Enum = /** @class */ (function () {
121
+ function Enum() {
122
+ this.properties = [];
123
+ }
124
+ Enum.prototype.addProperty = function (property) {
125
+ this.properties.push(property);
126
+ };
127
+ return Enum;
128
+ }());
129
+ exports.Enum = Enum;
115
130
  var Property = /** @class */ (function () {
116
131
  function Property() {
117
132
  }
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/codegen/types.ts"],"names":[],"mappings":";;;AAAA,uBAAyB;AAEzB,IAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,SAAS,GAAG,qBAAqB,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,OAAO,CAAC;AAClG,IAAM,cAAc,GAAG,wJAIY,OAAO,OACzC,CAAC;AAEF,SAAgB,gBAAgB,CAAC,iBAAgC;IAAhC,kCAAA,EAAA,wBAAgC;IAC7D,OAAO,UAAG,cAAc,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,UAAA,IAAI,IAAI,OAAA,UAAG,iBAAiB,cAAI,IAAI,CAAE,EAA9B,CAA8B,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAE,CAAC;AAClG,CAAC;AAFD,4CAEC;AAED;IAAA;QACI,YAAO,GAAY,EA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nC,CAAC;IAED,8BAAc,GAAd;QACI;;WAEG;QACH,IAAI,WAAW,GAAU,IAAI,CAAC;QAE9B,OACI,WAAW;YACX,CAAC,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,IAAI,KAAK,WAAW,CAAC,OAAO,EAA9B,CAA8B,CAAC,CAAC,EAChF;YACE,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,UAAA,IAAI;gBACxB,IAAI,CAAC,KAAK,IAAI,WAAW,CAAC,UAAU,CAAC,MAAM,CAAC;YAChD,CAAC,CAAC,CAAC;SACN;IACL,CAAC;IACL,YAAC;AAAD,CAAC,AA1BD,IA0BC;AA1BY,sBAAK;AA4BlB;IAAA;IAMA,CAAC;IAAD,eAAC;AAAD,CAAC,AAND,IAMC;AANY,4BAAQ;AAarB,SAAgB,kBAAkB,CAAC,KAAY,EAAE,UAAmB,EAAE,WAA2B;IAA3B,4BAAA,EAAA,kBAA2B;IAC7F,IAAI,YAAY,GAAG,KAAK,CAAC;IACzB,IAAI,eAAe,GAAY,EAAE,CAAC;IAElC,IAAI,WAAW,EAAE;QACb,eAAe,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;KACtC;IAED,OAAO,YAAY,CAAC,OAAO,KAAK,QAAQ,EAAE;QACtC,YAAY,GAAG,UAAU,CAAC,IAAI,CAAC,UAAA,KAAK,IAAI,OAAA,KAAK,CAAC,IAAI,IAAI,YAAY,CAAC,OAAO,EAAlC,CAAkC,CAAC,CAAC;QAC5E,eAAe,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;KACtC;IAED,OAAO,eAAe,CAAC;AAC3B,CAAC;AAdD,gDAcC","sourcesContent":["import * as fs from \"fs\";\n\nconst VERSION = JSON.parse(fs.readFileSync(__dirname + \"/../../package.json\").toString()).version;\nconst COMMENT_HEADER = `\nTHIS FILE HAS BEEN GENERATED AUTOMATICALLY\nDO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING\n\nGENERATED USING @colyseus/schema ${VERSION}\n`;\n\nexport function getCommentHeader(singleLineComment: string = \"//\") {\n return `${COMMENT_HEADER.split(\"\\n\").map(line => `${singleLineComment} ${line}`).join(\"\\n\")}`;\n}\n\nexport class Context {\n classes: Class[] = [];\n interfaces: Interface[] = [];\n\n getStructures() {\n return {\n classes: this.classes.filter(klass => {\n if (this.isSchemaClass(klass)) {\n return true;\n\n } else {\n let parentClass = klass;\n while (parentClass = this.getParentClass(parentClass)) {\n if (this.isSchemaClass(parentClass)) {\n return true;\n }\n }\n }\n return false;\n }),\n interfaces: this.interfaces,\n };\n }\n\n addStructure(structure: IStructure) {\n structure.context = this;\n\n if (structure instanceof Class) {\n this.classes.push(structure);\n\n } else if (structure instanceof Interface) {\n this.interfaces.push(structure);\n }\n }\n\n private getParentClass(klass: Class) {\n return this.classes.find(c => c.name === klass.extends);\n }\n\n private isSchemaClass(klass: Class) {\n let isSchema: boolean = false;\n\n let currentClass = klass;\n while (!isSchema && currentClass) {\n //\n // TODO: ideally we should check for actual @colyseus/schema module\n // reference rather than arbitrary strings.\n //\n isSchema = (\n currentClass.extends === \"Schema\" ||\n currentClass.extends === \"schema.Schema\" ||\n currentClass.extends === \"Schema.Schema\"\n );\n\n //\n // When extending from `schema.Schema`, it is required to\n // normalize as \"Schema\" for code generation.\n //\n if (currentClass === klass && isSchema) {\n klass.extends = \"Schema\";\n }\n\n currentClass = this.getParentClass(currentClass);\n }\n\n return isSchema;\n }\n}\n\nexport interface IStructure {\n context: Context;\n name: string;\n properties: Property[];\n addProperty(property: Property);\n}\n\nexport class Interface implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n\n addProperty(property: Property) {\n if (property.type.indexOf(\"[]\") >= 0) {\n // is array!\n property.childType = property.type.match(/([^\\[]+)/i)[1];\n property.type = \"array\";\n this.properties.push(property);\n\n } else {\n this.properties.push(property);\n }\n }\n}\n\nexport class Class implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n extends: string;\n\n addProperty(property: Property) {\n property.index = this.properties.length;\n this.properties.push(property);\n }\n\n postProcessing() {\n /**\n * Ensure the proprierties `index` are correct using inheritance\n */\n let parentKlass: Class = this;\n\n while (\n parentKlass &&\n (parentKlass = this.context.classes.find(k => k.name === parentKlass.extends))\n ) {\n this.properties.forEach(prop => {\n prop.index += parentKlass.properties.length;\n });\n }\n }\n}\n\nexport class Property {\n index: number;\n name: string;\n type: string;\n childType: string;\n deprecated?: boolean;\n}\n\nexport interface File {\n name: string\n content: string;\n}\n\nexport function getInheritanceTree(klass: Class, allClasses: Class[], includeSelf: boolean = true) {\n let currentClass = klass;\n let inheritanceTree: Class[] = [];\n\n if (includeSelf) {\n inheritanceTree.push(currentClass);\n }\n\n while (currentClass.extends !== \"Schema\") {\n currentClass = allClasses.find(klass => klass.name == currentClass.extends);\n inheritanceTree.push(currentClass);\n }\n\n return inheritanceTree;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/codegen/types.ts"],"names":[],"mappings":";;;AAAA,uBAAyB;AAEzB,IAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,SAAS,GAAG,qBAAqB,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,OAAO,CAAC;AAClG,IAAM,cAAc,GAAG,wJAIY,OAAO,OACzC,CAAC;AAEF,SAAgB,gBAAgB,CAAC,iBAAgC;IAAhC,kCAAA,EAAA,wBAAgC;IAC7D,OAAO,UAAG,cAAc,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,UAAA,IAAI,IAAI,OAAA,UAAG,iBAAiB,cAAI,IAAI,CAAE,EAA9B,CAA8B,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAE,CAAC;AAClG,CAAC;AAFD,4CAEC;AAED;IAAA;QACI,YAAO,GAAY,EAAE,CAAC;QACtB,eAAU,GAAgB,EAAE,CAAC;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I,OAAA,KAAK,CAAC,IAAI,IAAI,YAAY,CAAC,OAAO,EAAlC,CAAkC,CAAC,CAAC;QAC5E,eAAe,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;KACtC;IAED,OAAO,eAAe,CAAC;AAC3B,CAAC;AAdD,gDAcC","sourcesContent":["import * as fs from \"fs\";\n\nconst VERSION = JSON.parse(fs.readFileSync(__dirname + \"/../../package.json\").toString()).version;\nconst COMMENT_HEADER = `\nTHIS FILE HAS BEEN GENERATED AUTOMATICALLY\nDO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING\n\nGENERATED USING @colyseus/schema ${VERSION}\n`;\n\nexport function getCommentHeader(singleLineComment: string = \"//\") {\n return `${COMMENT_HEADER.split(\"\\n\").map(line => `${singleLineComment} ${line}`).join(\"\\n\")}`;\n}\n\nexport class Context {\n classes: Class[] = [];\n interfaces: Interface[] = [];\n enums: Enum[] = [];\n\n getStructures() {\n return {\n classes: this.classes.filter(klass => {\n if (this.isSchemaClass(klass)) {\n return true;\n\n } else {\n let parentClass = klass;\n while (parentClass = this.getParentClass(parentClass)) {\n if (this.isSchemaClass(parentClass)) {\n return true;\n }\n }\n }\n return false;\n }),\n interfaces: this.interfaces,\n enums: this.enums,\n };\n }\n\n addStructure(structure: IStructure) {\n structure.context = this;\n\n if (structure instanceof Class) {\n this.classes.push(structure);\n } else if (structure instanceof Interface) {\n this.interfaces.push(structure);\n } else if (structure instanceof Enum) {\n this.enums.push(structure);\n }\n }\n\n private getParentClass(klass: Class) {\n return this.classes.find(c => c.name === klass.extends);\n }\n\n private isSchemaClass(klass: Class) {\n let isSchema: boolean = false;\n\n let currentClass = klass;\n while (!isSchema && currentClass) {\n //\n // TODO: ideally we should check for actual @colyseus/schema module\n // reference rather than arbitrary strings.\n //\n isSchema = (\n currentClass.extends === \"Schema\" ||\n currentClass.extends === \"schema.Schema\" ||\n currentClass.extends === \"Schema.Schema\"\n );\n\n //\n // When extending from `schema.Schema`, it is required to\n // normalize as \"Schema\" for code generation.\n //\n if (currentClass === klass && isSchema) {\n klass.extends = \"Schema\";\n }\n\n currentClass = this.getParentClass(currentClass);\n }\n\n return isSchema;\n }\n}\n\nexport interface IStructure {\n context: Context;\n name: string;\n properties: Property[];\n addProperty(property: Property);\n}\n\nexport class Interface implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n\n addProperty(property: Property) {\n if (property.type.indexOf(\"[]\") >= 0) {\n // is array!\n property.childType = property.type.match(/([^\\[]+)/i)[1];\n property.type = \"array\";\n this.properties.push(property);\n\n } else {\n this.properties.push(property);\n }\n }\n}\n\nexport class Class implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n extends: string;\n\n addProperty(property: Property) {\n property.index = this.properties.length;\n this.properties.push(property);\n }\n\n postProcessing() {\n /**\n * Ensure the proprierties `index` are correct using inheritance\n */\n let parentKlass: Class = this;\n\n while (\n parentKlass &&\n (parentKlass = this.context.classes.find(k => k.name === parentKlass.extends))\n ) {\n this.properties.forEach(prop => {\n prop.index += parentKlass.properties.length;\n });\n }\n }\n}\n\nexport class Enum implements IStructure {\n context: Context;\n name: string;\n properties: Property[] = [];\n\n addProperty(property: Property) {\n this.properties.push(property);\n }\n}\n\nexport class Property {\n index: number;\n name: string;\n type: string;\n childType: string;\n deprecated?: boolean;\n}\n\nexport interface File {\n name: string\n content: string;\n}\n\nexport function getInheritanceTree(klass: Class, allClasses: Class[], includeSelf: boolean = true) {\n let currentClass = klass;\n let inheritanceTree: Class[] = [];\n\n if (includeSelf) {\n inheritanceTree.push(currentClass);\n }\n\n while (currentClass.extends !== \"Schema\") {\n currentClass = allClasses.find(klass => klass.name == currentClass.extends);\n inheritanceTree.push(currentClass);\n }\n\n return inheritanceTree;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colyseus/schema",
3
- "version": "1.0.44",
3
+ "version": "1.0.45",
4
4
  "description": "Binary state serializer with delta encoding for games",
5
5
  "bin": {
6
6
  "schema-codegen": "./bin/schema-codegen"
@@ -1,4 +1,11 @@
1
- import { Class, Property, File, getCommentHeader, Interface } from "../types";
1
+ import {
2
+ Class,
3
+ Property,
4
+ File,
5
+ getCommentHeader,
6
+ Interface,
7
+ Enum,
8
+ } from "../types";
2
9
  import { GenerateOptions } from "../api";
3
10
  import { Context } from "../types";
4
11
 
@@ -26,7 +33,11 @@ const capitalize = (s) => {
26
33
  return s.charAt(0).toUpperCase() + s.slice(1);
27
34
  }
28
35
 
29
- export function generate (context: Context, options: GenerateOptions): File[] {
36
+ export function generate(context: Context, options: GenerateOptions): File[] {
37
+ // enrich typeMaps with enums
38
+ context.enums.forEach((structure) => {
39
+ typeMaps[structure.name] = structure.name;
40
+ });
30
41
  return [
31
42
  ...context.classes.map(structure => ({
32
43
  name: `${structure.name}.cs`,
@@ -34,8 +45,12 @@ export function generate (context: Context, options: GenerateOptions): File[] {
34
45
  })),
35
46
  ...context.interfaces.map(structure => ({
36
47
  name: `${structure.name}.cs`,
37
- content: generateInterface(structure, options.namespace)
38
- }))
48
+ content: generateInterface(structure, options.namespace),
49
+ })),
50
+ ...context.enums.filter(structure => structure.name !== 'OPERATION').map((structure) => ({
51
+ name: `${structure.name}.cs`,
52
+ content: generateEnum(structure, options.namespace),
53
+ })),
39
54
  ];
40
55
  }
41
56
 
@@ -46,12 +61,40 @@ function generateClass(klass: Class, namespace: string) {
46
61
  using Colyseus.Schema;
47
62
  ${namespace ? `\nnamespace ${namespace} {` : ""}
48
63
  ${indent}public partial class ${klass.name} : ${klass.extends} {
49
- ${klass.properties.map(prop => generateProperty(prop, indent)).join("\n\n")}
64
+ ${klass.properties.map((prop) => generateProperty(prop, indent)).join("\n\n")}
50
65
  ${indent}}
51
66
  ${namespace ? "}" : ""}
52
67
  `;
53
68
  }
54
69
 
70
+ function generateEnum(_enum: Enum, namespace: string) {
71
+ const indent = namespace ? "\t" : "";
72
+ return `${getCommentHeader()}
73
+ ${namespace ? `\nnamespace ${namespace} {` : ""}
74
+ ${indent}public struct ${_enum.name} {
75
+
76
+ ${_enum.properties
77
+ .map((prop) => {
78
+ let dataType: string = "int";
79
+ let value: any;
80
+
81
+ if(prop.type) {
82
+ if(isNaN(Number(prop.type))) {
83
+ value = prop.type;
84
+ dataType = "string";
85
+ } else {
86
+ value = Number(prop.type);
87
+ dataType = Number.isInteger(value)? 'int': 'float';
88
+ }
89
+ } else {
90
+ value = _enum.properties.indexOf(prop);
91
+ }
92
+ return `${indent}\tpublic const ${dataType} ${prop.name} = ${value};`;
93
+ })
94
+ .join("\n")}
95
+ ${indent}}`
96
+ }
97
+
55
98
  function generateProperty(prop: Property, indent: string = "") {
56
99
  let typeArgs = `"${prop.type}"`;
57
100
  let property = "public";
@@ -1,7 +1,7 @@
1
1
  import * as ts from "typescript";
2
2
  import * as path from "path";
3
3
  import { readFileSync } from "fs";
4
- import { IStructure, Class, Interface, Property, Context } from "./types";
4
+ import { IStructure, Class, Interface, Property, Context, Enum } from "./types";
5
5
 
6
6
  let currentStructure: IStructure;
7
7
  let currentProperty: Property;
@@ -62,6 +62,15 @@ function inspectNode(node: ts.Node, context: Context, decoratorName: string) {
62
62
  }
63
63
  break;
64
64
 
65
+ case ts.SyntaxKind.EnumDeclaration:
66
+ const enumName = (
67
+ node as ts.EnumDeclaration
68
+ ).name.escapedText.toString();
69
+ currentStructure = new Enum();
70
+ currentStructure.name = enumName;
71
+ context.addStructure(currentStructure);
72
+ break;
73
+
65
74
  case ts.SyntaxKind.ExtendsKeyword:
66
75
  // console.log(node.getText());
67
76
  break;
@@ -182,6 +191,20 @@ function inspectNode(node: ts.Node, context: Context, decoratorName: string) {
182
191
  currentProperty = undefined;
183
192
 
184
193
  break;
194
+
195
+ case ts.SyntaxKind.EnumMember:
196
+ if (currentStructure instanceof Enum) {
197
+ const initializer = (node as any).initializer?.getText();
198
+ const name = node.getFirstToken().getText();
199
+ const property = currentProperty || new Property();
200
+ property.name = name;
201
+ if (initializer !== undefined) {
202
+ property.type = initializer;
203
+ }
204
+ currentStructure.addProperty(property);
205
+ currentProperty = undefined;
206
+ }
207
+ break;
185
208
  }
186
209
 
187
210
  ts.forEachChild(node, (n) => inspectNode(n, context, decoratorName));
@@ -15,6 +15,7 @@ export function getCommentHeader(singleLineComment: string = "//") {
15
15
  export class Context {
16
16
  classes: Class[] = [];
17
17
  interfaces: Interface[] = [];
18
+ enums: Enum[] = [];
18
19
 
19
20
  getStructures() {
20
21
  return {
@@ -33,6 +34,7 @@ export class Context {
33
34
  return false;
34
35
  }),
35
36
  interfaces: this.interfaces,
37
+ enums: this.enums,
36
38
  };
37
39
  }
38
40
 
@@ -41,9 +43,10 @@ export class Context {
41
43
 
42
44
  if (structure instanceof Class) {
43
45
  this.classes.push(structure);
44
-
45
46
  } else if (structure instanceof Interface) {
46
47
  this.interfaces.push(structure);
48
+ } else if (structure instanceof Enum) {
49
+ this.enums.push(structure);
47
50
  }
48
51
  }
49
52
 
@@ -134,6 +137,16 @@ export class Class implements IStructure {
134
137
  }
135
138
  }
136
139
 
140
+ export class Enum implements IStructure {
141
+ context: Context;
142
+ name: string;
143
+ properties: Property[] = [];
144
+
145
+ addProperty(property: Property) {
146
+ this.properties.push(property);
147
+ }
148
+ }
149
+
137
150
  export class Property {
138
151
  index: number;
139
152
  name: string;