@cosmwasm/ts-codegen
Version:
@cosmwasm/ts-codegen converts your CosmWasm smart contracts into dev-friendly TypeScript classes so you can focus on shipping code.
66 lines (65 loc) • 2.08 kB
JavaScript
import generate from '@babel/generator';
import * as t from '@babel/types';
import { defaultOptions, } from '@cosmwasm/ts-codegen-ast';
import deepmerge from 'deepmerge';
import { writeFileSync } from 'fs';
import { sync as mkdirp } from 'mkdirp';
import { join } from 'path';
import { header } from '../utils/header';
/**
* BuilderPluginBase enable ts-codegen users implement their own plugins by only implement a few functions.
*/
export class BuilderPluginBase {
builder;
options;
utils;
/**
* prop to indicate to execute the render function in the lifecycle of main process or after
*/
lifecycle;
defaultContractName;
constructor(opts, builder) {
this.options = opts;
this.builder = builder;
this.lifecycle = 'main';
}
setBuilder(builder) {
this.builder = builder;
}
async render(outPath, name, contractInfo) {
if (!this.options) {
this.options = this.getDefaultOptions(this.options);
}
const { enabled } = this.options;
if (!enabled) {
return;
}
const context = this.initContext(contractInfo, this.options);
const results = await this.doRender(name, context);
if (!results || !results.length) {
return [];
}
return results.map((result) => {
const imports = context.getImports(this.utils, result.localname);
const nodes = [...imports, ...result.body];
// @ts-ignore
const code = header + generate(t.program(nodes)).code;
mkdirp(outPath);
const filename = join(outPath, result.localname);
writeFileSync(filename, code);
return {
type: result.type,
pluginType: result.pluginType,
contract: name,
localname: result.localname,
filename,
};
});
}
/**
* get default options
*/
getDefaultOptions(opts) {
return deepmerge(defaultOptions, opts ?? {});
}
}