UNPKG

@eliseev_s/tolk-tlb-transpiler

Version:

Transpile Tolk structs to TLB definitions and generate TypeScript wrappers for TON blockchain smart contracts

223 lines 9.51 kB
"use strict"; // ============================================================================ // Utility Handlers - Convenient Functions for Tolk-to-TLB Transpilation // ============================================================================ 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 () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.formatTlbDefinitions = formatTlbDefinitions; exports.getTlbStats = getTlbStats; exports.transpileTolkToTlbDefinitions = transpileTolkToTlbDefinitions; exports.transpileTolkFileToTlbDefinitions = transpileTolkFileToTlbDefinitions; exports.transpileTolkToTlb = transpileTolkToTlb; exports.generateContractWrapper = generateContractWrapper; exports.generateContractWrapperFromFiles = generateContractWrapperFromFiles; const parser_1 = require("./parser"); const fs_1 = require("fs"); const wrapper_generator_1 = require("./wrapper-generator"); /** * Format TLB definitions into a readable string format * * @param definitions - Array of TLB definitions * @param options - Formatting options * @returns Formatted TLB string */ function formatTlbDefinitions(definitions, headerComment = 'TLB Schema Generated') { const output = []; if (headerComment) { output.push('// ============================================================================'); output.push(`// ${headerComment}`); output.push('// ============================================================================'); output.push(''); } for (const definition of definitions) { output.push(`// ${definition.name}`); for (const constructor of definition.statement) { output.push(constructor); } output.push(''); } return output.join('\n'); } /** * Get statistics about TLB definitions * * @param definitions - Array of TLB definitions * @returns Statistics object */ function getTlbStats(definitions) { let totalConstructors = 0; const definitionNames = []; for (const definition of definitions) { definitionNames.push(definition.name); totalConstructors += definition.statement.length; } return { totalDefinitions: definitions.length, totalConstructors, definitionNames, }; } /** * Transpile Tolk code and return TLB definitions * * @param tolkCode - The Tolk source code * @returns Promise resolving to TLB definitions */ async function transpileTolkToTlbDefinitions(tolkCode) { const processor = await parser_1.TolkASTProcessor.initialize(); // If argument is a file path, resolve imports if ((0, fs_1.existsSync)(tolkCode)) { return processor.transpileFile(tolkCode); } // Otherwise treat it as raw source code return processor.transpile(tolkCode); } /** * Transpile Tolk file with import resolution and return TLB definitions */ async function transpileTolkFileToTlbDefinitions(entryFilePath) { const processor = await parser_1.TolkASTProcessor.initialize(); return processor.transpileFile(entryFilePath); } /** * Transpile Tolk code and return formatted TLB string * * @param tolkCode - The Tolk source code * @param formatOptions - Optional formatting options * @returns Promise resolving to formatted TLB string */ async function transpileTolkToTlb(tolkCode, formatOptions) { const definitions = await transpileTolkToTlbDefinitions(tolkCode); return formatTlbDefinitions(definitions, formatOptions); } /** * Generate TypeScript wrapper with TLB types for smart contract interaction * * @param tolkStructuresCode - Tolk code containing struct definitions * @param tolkGetMethodsCode - Tolk code containing get method definitions * @param contractName - Name of the contract (e.g., "Minter") * @returns Object with TLB definitions, TypeScript code, and wrapper code */ async function generateContractWrapper(tolkStructuresCode, tolkGetMethodsCode, contractName) { // Initialize processor const processor = await parser_1.TolkASTProcessor.initialize(); // Process structures to get TLB definitions const tlbDefinitions = processor.transpile(tolkStructuresCode); // Get structures for send method generation const structuresTree = processor.parse(tolkStructuresCode); processor.processAST(structuresTree); const structures = processor.getStructs(); const typeAliases = processor.getTypeAliases(); // Parse get methods from get methods file const getMethodsTree = processor.parse(tolkGetMethodsCode); processor.processAST(getMethodsTree); // This will populate getMethods const getMethods = processor.getGetMethods(); // Create wrapper generator instance using static factory method const wrapperGenerator = await wrapper_generator_1.WrapperGenerator.create({ contractName, storageType: `${contractName}Storage`, incomingMessageType: `${contractName}IncomingMessage`, internalMessageType: `${contractName}InternalMessage`, getMethods, structures, typeAliases, tlbDefinitions, }); // Get all generated components const tlbString = wrapperGenerator.getTlbString(); const typescriptCode = wrapperGenerator.getTypescriptCode(); const wrapperCode = wrapperGenerator.getWrapperCode(); const fullCode = wrapperGenerator.render(); return { tlbDefinitions, tlbString, typescriptCode, wrapperCode, fullCode, }; } /** * Generate TypeScript wrapper with TLB types using Tolk files (supports imports) * * @param structuresPath - Path to Tolk file with struct definitions (supports imports) * @param getMethodsPath - Path to Tolk file with get methods (can import structs) * @param contractName - Name of the contract (e.g., "Minter") */ async function generateContractWrapperFromFiles(structuresPath, getMethodsPath, contractName) { // Processor A: collect structures graph from structuresPath const procStructs = await parser_1.TolkASTProcessor.initialize(); const tlbDefinitions = procStructs.transpileFile(structuresPath); const structsA = procStructs.getStructs(); const aliasesA = procStructs.getTypeAliases(); // Processor B: collect definitions reachable from getMethodsPath and parse get methods const procGet = await parser_1.TolkASTProcessor.initialize(); procGet.transpileFile(getMethodsPath); // populates structs/aliases from imports const getMethodsTree = procGet.parse(require('fs').readFileSync(getMethodsPath, 'utf-8')); // Use internal parser to extract get methods without clearing collected definitions const getMethods = (await Promise.resolve().then(() => __importStar(require('./get-methods-parser')))).GetMethodsParser.parseGetMethods(getMethodsTree.rootNode, (node) => procGet.resolveType(node)); // Merge structures and aliases from both graphs (by name) const structMap = new Map(); for (const s of structsA) structMap.set(s.name, s); for (const s of procGet.getStructs()) if (!structMap.has(s.name)) structMap.set(s.name, s); const structures = Array.from(structMap.values()); const aliasMap = new Map(); for (const a of aliasesA) aliasMap.set(a.name, a); for (const a of procGet.getTypeAliases()) if (!aliasMap.has(a.name)) aliasMap.set(a.name, a); const typeAliases = Array.from(aliasMap.values()); // Create wrapper generator instance const wrapperGenerator = await wrapper_generator_1.WrapperGenerator.create({ contractName, storageType: `${contractName}Storage`, incomingMessageType: `${contractName}IncomingMessage`, internalMessageType: `${contractName}InternalMessage`, getMethods, structures, typeAliases, tlbDefinitions, }); // Compose outputs const tlbString = wrapperGenerator.getTlbString(); const typescriptCode = wrapperGenerator.getTypescriptCode(); const wrapperCode = wrapperGenerator.getWrapperCode(); const fullCode = wrapperGenerator.render(); return { tlbDefinitions, tlbString, typescriptCode, wrapperCode, fullCode }; } //# sourceMappingURL=handlers.js.map