Explorar o código

API Typescript improvement (#176)

* improves typesafety for autogenerated schema

* brings CONSTRUCTOR_ID as well as SUBCLASSOF_ID typesafety and adds types for requests
ehsan2003 %!s(int64=3) %!d(string=hai) anos
pai
achega
e6da9a345b
Modificáronse 2 ficheiros con 550 adicións e 79 borrados
  1. 438 0
      gramjs/tl/api.d.ts
  2. 112 79
      gramjs/tl/types-generator/template.js

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 438 - 0
gramjs/tl/api.d.ts


+ 112 - 79
gramjs/tl/types-generator/template.js

@@ -1,3 +1,4 @@
+
 // Not sure what they are for.
 const WEIRD_TYPES = new Set(["Bool", "X", "Type"]);
 
@@ -16,6 +17,12 @@ module.exports = ({ types, constructors, functions }) => {
         }, {});
     }
 
+    function getClassNameWithNameSpace(name, namespace) {
+        return namespace
+            ? namespace.toLowerCase() + "." + upperFirst(name)
+            : upperFirst(name);
+    }
+
     function renderTypes(types, indent) {
         return types
             .map(({ name, constructors }) =>
@@ -30,13 +37,19 @@ module.exports = ({ types, constructors, functions }) => {
 
     function renderConstructors(constructors, indent) {
         return constructors
-            .map(({ name, argsConfig }) => {
+            .map((args) => {
+                // console.log(args);
+                const { name, namespace, argsConfig,constructorId,subclassOfId }=args;
                 const argKeys = Object.keys(argsConfig);
-
+                // console.log(constructorId);
                 if (!argKeys.length) {
                     return `export class ${upperFirst(
                         name
                     )} extends VirtualClass<void> {
+    CONSTRUCTOR_ID: ${constructorId};
+    SUBCLASS_OF_ID: ${subclassOfId};
+    classType: "constructor";
+    className: "${getClassNameWithNameSpace(name, namespace)}";
     static fromReader(reader: Reader): ${upperFirst(name)};
 }`;
                 }
@@ -56,6 +69,10 @@ ${indent}  ${Object.keys(argsConfig)
                     )
                     .join(`\n${indent}  `)}
 ${indent}}${!hasRequiredArgs ? "" : ""}> {
+    CONSTRUCTOR_ID: ${constructorId};
+    SUBCLASS_OF_ID: ${subclassOfId};
+    classType: "constructor";
+${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
 ${indent}static fromReader(reader: Reader): ${upperFirst(name)};
 ${indent}  ${Object.keys(argsConfig)
                     .map((argName) =>
@@ -71,13 +88,19 @@ ${indent}}`.trim();
 
     function renderRequests(requests, indent) {
         return requests
-            .map(({ name, argsConfig, result }) => {
+            .map((args) => {
+                console.log(args);
+                const { name, argsConfig, result,constructorId,namespace,subclassOfId }=args;
                 const argKeys = Object.keys(argsConfig);
 
                 if (!argKeys.length) {
                     return `export class ${upperFirst(
                         name
                     )} extends Request<void, ${renderResult(result)}> {
+    CONSTRUCTOR_ID: ${constructorId};
+    SUBCLASS_OF_ID: ${subclassOfId};
+    classType: "request";
+${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
     static fromReader(reader: Reader): ${upperFirst(name)};
 }`;
                 }
@@ -97,6 +120,10 @@ ${indent}  ${argKeys
                     )
                     .join(`\n${indent}  `)}
 ${indent}}${!hasRequiredArgs ? "" : ""}>, ${renderResult(result)}> {
+    CONSTRUCTOR_ID: ${constructorId};
+    SUBCLASS_OF_ID: ${subclassOfId};
+    classType: "request";
+${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
 ${indent}static fromReader(reader: Reader): ${upperFirst(name)};
 ${indent}  ${argKeys
                     .map((argName) =>
@@ -163,117 +190,123 @@ ${indent}}`.trim();
         return `${str[0].toUpperCase()}${str.slice(1)}`;
     }
 
+    function lowerFirst(str) {
+        return `${str[0].toLowerCase()}${str.slice(1)}`;
+    }
+
     const typesByNs = groupByKey(types, "namespace");
     const constructorsByNs = groupByKey(constructors, "namespace");
     const requestsByNs = groupByKey(functions, "namespace");
 
     // language=TypeScript
     return `
-// This file is autogenerated. All changes will be overwritten.
+        // This file is autogenerated. All changes will be overwritten.
 
-import { BigInteger } from 'big-integer';
-import {EntityLike,MessageIDLike} from "../define";
+        import { BigInteger } from 'big-integer';
+        import { EntityLike, MessageIDLike } from "../define";
 
 
-export namespace Api {
+        export namespace Api {
 
-  type AnyLiteral = Record<string, any> | void;
+            type AnyLiteral = Record<string, any> | void;
 
-  type Reader = any; // To be defined.
-  type Client = any; // To be defined.
-  type Utils = any; // To be defined.
+            type Reader = any; // To be defined.
+            type Client = any; // To be defined.
+            type Utils = any; // To be defined.
 
-  type X = unknown;
-  type Type = unknown;
-  type Bool = boolean;
-  type int = number;
-  type double = number;
-  type float = number;
-  type int128 = BigInteger;
-  type int256 = BigInteger;
-  type long = BigInteger;
-  type bytes = Buffer;
+            type X = unknown;
+            type Type = unknown;
+            type Bool = boolean;
+            type int = number;
+            type double = number;
+            type float = number;
+            type int128 = BigInteger;
+            type int256 = BigInteger;
+            type long = BigInteger;
+            type bytes = Buffer;
 
-  class VirtualClass<Args extends AnyLiteral> {
-    static CONSTRUCTOR_ID: number;
-    static SUBCLASS_OF_ID: number;
-    static className: string;
-    static classType: 'constructor' | 'request';
+            class VirtualClass<Args extends AnyLiteral> {
+                static CONSTRUCTOR_ID: number;
+                static SUBCLASS_OF_ID: number;
+                static className: string;
+                static classType: 'constructor' | 'request';
 
-    static serializeBytes(data: Buffer | string): Buffer;
-    static serializeDate(date: Date | number): Buffer;
+                static serializeBytes(data: Buffer | string): Buffer;
 
-    getBytes():Buffer;
+                static serializeDate(date: Date | number): Buffer;
 
-    CONSTRUCTOR_ID: number;
-    SUBCLASS_OF_ID: number;
-    className: string;
-    classType: 'constructor' | 'request';
+                getBytes(): Buffer;
 
-    constructor(args: Args);
-  }
+                CONSTRUCTOR_ID: number;
+                SUBCLASS_OF_ID: number;
+                className: string;
+                classType: 'constructor' | 'request';
 
-  class Request<Args, Response> extends VirtualClass<Partial<Args>> {
-    static readResult(reader: Reader): Buffer;
-    resolve(client: Client, utils: Utils): Promise<void>;
+                constructor(args: Args);
+            }
+
+            class Request<Args, Response> extends VirtualClass<Partial<Args>> {
+                static readResult(reader: Reader): Buffer;
+
+                resolve(client: Client, utils: Utils): Promise<void>;
 
-    __response: Response;
-  }
+                __response: Response;
+            }
 
 
-  ${renderConstructors(constructorsByNs._, "  ")}
-  ${renderRequests(requestsByNs._, "  ")}
+            ${renderConstructors(constructorsByNs._, "  ")}
+            ${renderRequests(requestsByNs._, "  ")}
 
 
 // namespaces
 
-  ${Object.keys(constructorsByNs)
-      .map((namespace) =>
-          namespace !== "_"
-              ? `
+            ${Object.keys(constructorsByNs)
+                .map((namespace) =>
+                    namespace !== "_"
+                        ? `
   export namespace ${namespace} {
     ${renderConstructors(constructorsByNs[namespace], "    ")}
   }`
-              : ""
-      )
-      .join("\n")}
-  ${Object.keys(typesByNs)
-      .map((namespace) =>
-          namespace !== "_"
-              ? `
+                        : ""
+                )
+                .join("\n")}
+            ${Object.keys(typesByNs)
+                .map((namespace) =>
+                    namespace !== "_"
+                        ? `
   export namespace ${namespace} {
     ${renderTypes(typesByNs[namespace], "    ")}
   }`
-              : ""
-      )
-      .join("\n")}
-  ${Object.keys(requestsByNs)
-      .map((namespace) =>
-          namespace !== "_"
-              ? `
+                        : ""
+                )
+                .join("\n")}
+            ${Object.keys(requestsByNs)
+                .map((namespace) =>
+                    namespace !== "_"
+                        ? `
   export namespace ${namespace} {
     ${renderRequests(requestsByNs[namespace], "    ")}
   }`
-              : ""
-      )
-      .join("\n")}
+                        : ""
+                )
+                .join("\n")}
 
 // Types
-  export type TypeEntityLike = EntityLike;
-  ${renderTypes(typesByNs._, "  ")}
+            export type TypeEntityLike = EntityLike;
+            ${renderTypes(typesByNs._, "  ")}
 // All requests
-  export type AnyRequest = ${requestsByNs._.map(({ name }) =>
-      upperFirst(name)
-  ).join(" | ")}
-    | ${Object.keys(requestsByNs)
-        .filter((ns) => ns !== "_")
-        .map((ns) =>
-            requestsByNs[ns]
-                .map(({ name }) => `${ns}.${upperFirst(name)}`)
-                .join(" | ")
-        )
-        .join("\n    | ")};
-
-}
-`;
+            export type AnyRequest = ${requestsByNs._.map(({ name }) =>
+                    upperFirst(name)
+                ).join(" | ")}
+                | ${Object.keys(requestsByNs)
+                .filter((ns) => ns !== "_")
+                .map((ns) =>
+                    requestsByNs[ns]
+                        .map(({ name }) => `${ns}.${upperFirst(name)}`)
+                        .join(" | ")
+                )
+                .join("\n    | ")};
+
+        }
+    `;
 };

Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio