UNPKG

tdjson

Version:

TypeScript types for libtdjson.so

431 lines 22.5 kB
"use strict"; var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var promises_1 = __importDefault(require("node:fs/promises")); var node_path_1 = __importDefault(require("node:path")); var node_buffer_1 = require("node:buffer"); var node_util_1 = require("node:util"); var node_fetch_1 = __importDefault(require("node-fetch")); var outdent_1 = require("outdent"); var invariant_1 = __importDefault(require("invariant")); var A = __importStar(require("arcsecond")); var pascal_case_1 = require("pascal-case"); var ttyStrings = __importStar(require("tty-strings")); function wordWrap(text) { return ttyStrings.wordWrap(text, 120); } function trimFilterJoin(strings) { return strings.map(function (s) { return s.trim(); }).filter(function (s) { return s.length > 0; }).join(' '); } var identifierParser = A.regex(/^\w+/).map(function (name) { return ({ type: 'Identifier', name: name, }); }); var commentParser = A.sequenceOf([ A.str('//@'), identifierParser, A.everyCharUntil(A.char('\n')), A.many(A.sequenceOf([ A.char('\n'), A.str('//-'), A.everyCharUntil(A.char('\n')), ]).map(function (_a) { var _b = __read(_a, 3), _0 = _b[0], _1 = _b[1], comment = _b[2]; return comment; })).map(function (s) { return trimFilterJoin(s); }), ]).map(function (_a) { var _b = __read(_a, 4), _0 = _b[0], tag = _b[1], comment = _b[2], comment_ = _b[3]; return ({ type: 'Comment', tag: tag.name, text: trimFilterJoin([comment, comment_]), }); }); var commentsParser = A.many(A.sequenceOf([ A.optionalWhitespace, commentParser, ]).map(function (_a) { var _b = __read(_a, 2), _ = _b[0], comment = _b[1]; return comment; })).map(function (comments) { return comments.flatMap(function (comment) { var _a = __read(comment.text.split('@')), head = _a[0], tail = _a.slice(1); return __spreadArray([ __assign(__assign({}, comment), { text: head }) ], __read(tail.map(function (commentText) { var _a = __read(commentText.split(' ')), tag = _a[0], textWords = _a.slice(1); return { type: 'Comment', tag: tag, text: textWords.join(' '), }; })), false); }); }); var typeAppParser = A.sequenceOf([ identifierParser, A.char('<'), A.recursiveParser(function () { return typeParser; }), A.char('>'), ]).map(function (_a) { var _b = __read(_a, 3), callee = _b[0], _1 = _b[1], argument = _b[2]; return ({ type: 'TypeApplication', callee: callee, argument: argument, }); }); var typeParser = A.choice([ typeAppParser, identifierParser, ]); var annotatedIdentifierParser = A.sequenceOf([ identifierParser, A.char(':'), typeParser, ]).map(function (_a) { var _b = __read(_a, 3), id = _b[0], _1 = _b[1], typeAnnotation = _b[2]; return ({ type: 'AnnotatedIdentifier', id: id, typeAnnotation: typeAnnotation, }); }); var typeVariableParser = A.sequenceOf([ A.char('{'), annotatedIdentifierParser, A.char('}'), ]).map(function (_a) { var _b = __read(_a, 2), _0 = _b[0], annotatedIdentifier = _b[1]; return annotatedIdentifier; }); var argumentParser = A.choice([ A.char('?'), A.char('#'), A.str('[ t ]'), annotatedIdentifierParser, identifierParser, typeVariableParser, ]); var argumentsParser = A.many(A.sequenceOf([ A.whitespace, argumentParser, ]).map(function (_a) { var _b = __read(_a, 2), _0 = _b[0], argument = _b[1]; return argument; })); var combinatorParser = A.sequenceOf([ identifierParser, argumentsParser, A.whitespace, A.char('='), A.whitespace, identifierParser, A.possibly(argumentsParser), ]).map(function (_a) { var _b = __read(_a, 7), name = _b[0], arguments_ = _b[1], _2 = _b[2], _3 = _b[3], _4 = _b[4], resultName = _b[5], resultArguments = _b[6]; return ({ type: 'Combinator', comments: [], left: { id: name, arguments: arguments_ !== null && arguments_ !== void 0 ? arguments_ : [], }, right: { id: resultName, arguments: resultArguments !== null && resultArguments !== void 0 ? resultArguments : [], }, }); }); var tdApiParser = A.sequenceOf([ A.possibly(A.sequenceOf([ commentsParser, A.whitespace, ]).map(function (_a) { var _b = __read(_a, 1), comments = _b[0]; return comments; })), combinatorParser, ]).map(function (_a) { var _b = __read(_a, 2), comments = _b[0], combinator = _b[1]; return (__assign(__assign({}, combinator), { comments: __spreadArray(__spreadArray([], __read(combinator.comments), false), __read((comments !== null && comments !== void 0 ? comments : [])), false) })); }); function stringifyTypeAnnotation(typeAnnotation) { if (typeAnnotation.type === 'Identifier') { if (typeAnnotation.name === 'String' || typeAnnotation.name === 'Int64' || typeAnnotation.name === 'string' || typeAnnotation.name === 'int64') { return 'string'; } if (typeAnnotation.name === 'Double' || typeAnnotation.name === 'Int32' || typeAnnotation.name === 'Int53' || typeAnnotation.name === 'double' || typeAnnotation.name === 'int32' || typeAnnotation.name === 'int53') { return 'number'; } if (typeAnnotation.name === 'Bool' || typeAnnotation.name === 'bool') { return 'boolean'; } if (typeAnnotation.name === 'Bytes' || typeAnnotation.name === 'bytes') { return 'string'; } if (typeAnnotation.name === 'Vector' || typeAnnotation.name === 'vector') { return 'Array'; } return (0, pascal_case_1.pascalCase)(typeAnnotation.name); } if (typeAnnotation.type === 'TypeApplication') { return "".concat(stringifyTypeAnnotation(typeAnnotation.callee), "<").concat(stringifyTypeAnnotation(typeAnnotation.argument), ">"); } (0, invariant_1.default)(false, 'Cannot stringify type annotation: %s', (0, node_util_1.inspect)(typeAnnotation)); } function stringifyCommentText(lines, thisInterfaceName) { var text = lines.map(function (line) { return line === null || line === void 0 ? void 0 : line.trim(); }).filter(Boolean).map(function (line) { if (line && !line.endsWith('.')) { line += '.'; } return line; }).join('\n'); if (thisInterfaceName) { text = text.replaceAll(/(?<!{)@(\w+)/g, function (_, referencedIdentifier) { return "{@link ".concat(thisInterfaceName, "#").concat(referencedIdentifier, "}"); }); } return wordWrap(text); } function stringifyConstructorName(constructor_) { return (0, pascal_case_1.pascalCase)(constructor_.left.id.name); } function stringifyConstructorArgument(constructor_, argument) { (0, invariant_1.default)(typeof argument === 'object' && argument.type === 'AnnotatedIdentifier', 'Can not stringify constructor argument: %s', (0, node_util_1.inspect)(argument)); var interfaceName = stringifyConstructorName(constructor_); var comment = constructor_.comments.find(function (comment) { return comment.tag === argument.id.name; }); var commentText = stringifyCommentText([comment === null || comment === void 0 ? void 0 : comment.text], interfaceName); var typeAnnotation = stringifyTypeAnnotation(argument.typeAnnotation); var isOptional = typeAnnotation === 'boolean'; var optionalPropertySign = isOptional ? '?' : ''; return (0, outdent_1.outdent)(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n\t\t/**\n\t\t", "\n\t\t*/\n\t\t", "", ": ", ";\n\t"], ["\n\t\t/**\n\t\t", "\n\t\t*/\n\t\t", "", ": ", ";\n\t"])), commentText, argument.id.name, optionalPropertySign, typeAnnotation); } function stringifyConstructor(constructor_, isFunction) { if (isFunction === void 0) { isFunction = false; } if (constructor_.right.id.name === 'Double' || constructor_.right.id.name === 'String' || constructor_.right.id.name === 'Int32' || constructor_.right.id.name === 'Int53' || constructor_.right.id.name === 'Int64' || constructor_.right.id.name === 'Bytes' || constructor_.right.id.name === 'Bool' || constructor_.right.id.name === 'Vector') { return ''; } var interfaceName = stringifyConstructorName(constructor_); var constructorCommentText = (isFunction ? (0, outdent_1.outdent)(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n\t\t\t\tRequest type for {@link Tdjson#", "}.\n\t\t\t"], ["\n\t\t\t\tRequest type for {@link Tdjson#", "}.\n\t\t\t"])), constructor_.left.id.name) : (constructor_.right.id.name === interfaceName ? '' : (0, outdent_1.outdent)(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n\t\t\t\t\t\tSubtype of {@link ", "}.\n\t\t\t\t\t"], ["\n\t\t\t\t\t\tSubtype of {@link ", "}.\n\t\t\t\t\t"])), constructor_.right.id.name))); var descriptionComment = constructor_.comments.find(function (comment) { return comment.tag === 'description'; }); var descriptionCommentText = stringifyCommentText([ descriptionComment === null || descriptionComment === void 0 ? void 0 : descriptionComment.text, constructorCommentText, ], interfaceName); return (0, outdent_1.outdent)(templateObject_4 || (templateObject_4 = __makeTemplateObject(["\n\t\t/**\n\t\t", "\n\t\t*/\n\t\texport interface ", " {\n\t\t\t'@type': ", ";\n\t\t\t", "\n\t\t}\n\t"], ["\n\t\t/**\n\t\t", "\n\t\t*/\n\t\texport interface ", " {\n\t\t\t'@type': ", ";\n\t\t\t", "\n\t\t}\n\t"])), descriptionCommentText, interfaceName, JSON.stringify(constructor_.left.id.name), constructor_.left.arguments.map(function (argument) { return stringifyConstructorArgument(constructor_, argument); }).join('\n')); } function stringifyFunctionOptionsType(function_) { var interfaceName = stringifyConstructorName(function_); return "Omit<".concat(interfaceName, ", '@type'>"); } function stringifyFunction(function_) { var descriptionComment = function_.comments.find(function (comment) { return comment.tag === 'description'; }); var descriptionCommentText = stringifyCommentText([ descriptionComment === null || descriptionComment === void 0 ? void 0 : descriptionComment.text, ]); var hasArguments = function_.left.arguments.length > 0; if (!hasArguments) { return (0, outdent_1.outdent)(templateObject_5 || (templateObject_5 = __makeTemplateObject(["\n\t\t\t/**\n\t\t\t", "\n\t\t\t*/\n\t\t\t", "(): Promise<", "> {\n\t\t\t\treturn this._request({\n\t\t\t\t\t'@type': ", ",\n\t\t\t\t});\n\t\t\t}\n\t\t"], ["\n\t\t\t/**\n\t\t\t", "\n\t\t\t*/\n\t\t\t", "(): Promise<", "> {\n\t\t\t\treturn this._request({\n\t\t\t\t\t'@type': ", ",\n\t\t\t\t});\n\t\t\t}\n\t\t"])), descriptionCommentText, function_.left.id.name, function_.right.id.name, JSON.stringify(function_.left.id.name)); } return (0, outdent_1.outdent)(templateObject_6 || (templateObject_6 = __makeTemplateObject(["\n\t\t/**\n\t\t", "\n\t\t*/\n\t\t", "(options: ", "): Promise<", "> {\n\t\t\treturn this._request({\n\t\t\t\t...options,\n\t\t\t\t'@type': ", ",\n\t\t\t});\n\t\t}\n\t"], ["\n\t\t/**\n\t\t", "\n\t\t*/\n\t\t", "(options: ", "): Promise<", "> {\n\t\t\treturn this._request({\n\t\t\t\t...options,\n\t\t\t\t'@type': ", ",\n\t\t\t});\n\t\t}\n\t"])), descriptionCommentText, function_.left.id.name, stringifyFunctionOptionsType(function_), function_.right.id.name, JSON.stringify(function_.left.id.name)); } function stringifyFunctions(functions) { return (0, outdent_1.outdent)(templateObject_7 || (templateObject_7 = __makeTemplateObject(["\n\t\texport abstract class Tdjson {\n\t\t\t", "\n\n\t\t\t/**\n\t\t\tSend a request to the actual libtdjson.so here. Do not forget to handle {@link Error} responses and timeouts.\n\t\t\t*/\n\t\t\tprotected abstract _request<R extends Request>(message: R): Promise<any>;\n\t\t}\n\t"], ["\n\t\texport abstract class Tdjson {\n\t\t\t", "\n\n\t\t\t/**\n\t\t\tSend a request to the actual libtdjson.so here. Do not forget to handle {@link Error} responses and timeouts.\n\t\t\t*/\n\t\t\tprotected abstract _request<R extends Request>(message: R): Promise<any>;\n\t\t}\n\t"])), functions.map(function (f) { return stringifyFunction(f); }).join('\n')); } function stringifyConstructorUnion(unionName, constructors) { if (unionName === 'Bool') { return ''; } var constructorsUnion = (__spreadArray([], __read(constructors), false).map(function (constructor_) { return '| ' + stringifyConstructorName(constructor_); }) .join('\n')); return (0, outdent_1.outdent)(templateObject_8 || (templateObject_8 = __makeTemplateObject(["\n\t\texport type ", " =\n\t\t\t", ";\n\t"], ["\n\t\texport type ", " =\n\t\t\t", ";\n\t"])), unionName, constructorsUnion); } function main() { return __awaiter(this, void 0, void 0, function () { var response, text, _a, constructorsText, functionsText, _b, constructors, functions, constructorUnions, typescript; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, (0, node_fetch_1.default)('https://raw.githubusercontent.com/tdlib/td/master/td/generate/scheme/td_api.tl')]; case 1: response = _c.sent(); return [4 /*yield*/, response.text()]; case 2: text = _c.sent(); text = text.replaceAll(/\n+/g, '\n').replaceAll(/[ \t]+/g, ' '); _a = __read(text.split('---functions---'), 2), constructorsText = _a[0], functionsText = _a[1]; _b = __read([constructorsText, functionsText].map(function (text) { var lines = text.split(/;\n(?!\/\/-)/).flatMap(function (line) { line = line.trim(); if (!line) { return []; } return [line]; }); var parseResult = lines.flatMap(function (line) { var lineParseResult = tdApiParser.run(line); var isError = lineParseResult.isError, index = lineParseResult.index; if (isError || index !== node_buffer_1.Buffer.byteLength(line, 'utf8')) { var before = line.slice(0, index); var after = line.slice(index, -1); console.error(lineParseResult, line.length); console.error([ before, after, ].join('<<HERE>>').trim()); (0, invariant_1.default)(false, 'Parsing failed or did not consume everything'); } return [lineParseResult.result]; }); return parseResult; }), 2), constructors = _b[0], functions = _b[1]; constructorUnions = constructors.reduce(function (groups, constructor_) { if (!groups.has(constructor_.right.id.name)) { groups.set(constructor_.right.id.name, new Set()); } var group = groups.get(constructor_.right.id.name); group.add(constructor_); return groups; }, new Map()); typescript = __spreadArray(__spreadArray(__spreadArray(__spreadArray([ '/* eslint-disable @typescript-eslint/no-unsafe-return */' ], __read(constructors.map(function (c) { return stringifyConstructor(c); })), false), __read(__spreadArray([], __read(constructorUnions.entries()), false).filter(function (_a) { var _b = __read(_a, 2), _ = _b[0], group = _b[1]; return group.size > 1; }).map(function (_a) { var _b = __read(_a, 2), unionName = _b[0], constructors = _b[1]; return stringifyConstructorUnion(unionName, constructors); })), false), __read(functions.map(function (c) { return stringifyConstructor(c, true); })), false), [ stringifyConstructorUnion('Request', functions), stringifyFunctions(functions), ], false).filter(Boolean).join('\n\n'); return [4 /*yield*/, promises_1.default.writeFile(node_path_1.default.join(__dirname, 'tdjson.ts'), typescript)]; case 3: _c.sent(); return [2 /*return*/]; } }); }); } void main(); var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6, templateObject_7, templateObject_8; //# sourceMappingURL=tdjson.generate.js.map