Skip to content

Commit

Permalink
feat: contract builder can build single file result
Browse files Browse the repository at this point in the history
  • Loading branch information
eng-cc committed Aug 16, 2023
1 parent 04fa7b2 commit b45b6c6
Show file tree
Hide file tree
Showing 10 changed files with 379 additions and 44 deletions.
14 changes: 14 additions & 0 deletions packages/contract/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@
"engines": {
"node": ">=16.0.0"
},
"exports": {
".": {
"import": "./dist/index.mjs",
"types": "./dist/index.d.mts"
},
"./contractHelper": {
"import": "./dist/contractHelper.mjs",
"types": "./dist/contractHelper.d.mts"
},
"./contract": {
"import": "./dist/contract.mjs",
"types": "./src/contract.d.ts"
}
},
"keywords": [],
"author": "",
"license": "ISC",
Expand Down
11 changes: 10 additions & 1 deletion packages/contract_builder/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,20 @@
"author": "",
"license": "ISC",
"dependencies": {
"@rollup/plugin-commonjs": "^25.0.4",
"@rollup/plugin-node-resolve": "^15.1.0",
"@rollup/plugin-terser": "^0.4.3",
"@rollup/plugin-typescript": "^11.1.2",
"@rollup/plugin-wasm": "^6.1.3",
"@swc/core": "^1.3.72",
"@swc/wasm-web": "^1.3.72",
"@trustack/vm": "workspace:^1.0.0",
"cac": "^6.7.14",
"chalk": "^5.3.0",
"multiformats": "^11.0.2"
"multiformats": "^11.0.2",
"rollup": "^3.28.0",
"rollup-plugin-typescript2": "^0.35.0",
"tslib": "^2.6.1",
"typescript": "^5.1.6"
}
}
33 changes: 19 additions & 14 deletions packages/contract_builder/src/ast.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,28 @@ export const BUILDER_NAMES = {

export const walkTop = (ast: Program): Program => {
// 处理import
while (ast.body[0].type === 'ImportDeclaration') {
const node = ast.body[0];
if (node.source.value === BUILDER_NAMES.MAIN_PACKAGE) {
ast.body.shift();
ast.body.forEach((topNode, i) => {
if (topNode.type === 'ImportDeclaration') {
if (topNode.source.value === BUILDER_NAMES.MAIN_PACKAGE) {
// remove import
ast.body[i] = {
type: 'EmptyStatement',
span: topNode.span,
};
}
}
}
});

// remove export
ast.body = ast.body.map((topNode, i) => {
if (
['ExportDeclaration', 'ExportDefaultDeclaration'].includes(topNode.type)
) {
// remove export
return (topNode as ExportDeclaration).declaration;
}
return topNode;
});
// ast.body = ast.body.map((topNode, i) => {
// if (
// ['ExportDeclaration', 'ExportDefaultDeclaration'].includes(topNode.type)
// ) {
// // remove export
// return (topNode as ExportDeclaration).declaration;
// }
// return topNode;
// });

// 除super之外的constructor逻辑
const constructorExpressionStatements: ExpressionStatement[] = [];
Expand Down
53 changes: 47 additions & 6 deletions packages/contract_builder/src/builder.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import { walkTop } from './ast.utils.js';
import type { Output, Program, Options, ParseOptions } from '@swc/core';
import {
Output,
Program,
Options,
ParseOptions,
parseSync,
bundle,
} from '@swc/core';
import { rollup } from 'rollup';
import terser from '@rollup/plugin-terser';
import typescript from 'rollup-plugin-typescript2';
import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import { wasm } from '@rollup/plugin-wasm';

export const buildCodeString = (
code: string,
Expand All @@ -8,11 +21,7 @@ export const buildCodeString = (
transformSync: (ast: Program, opt: Options) => Output;
},
): Output => {
const opt = buildConfig.parseSync(code, {
syntax: 'typescript',
target: 'es2022',
});
const contractAst = walkTop(opt);
const contractAst = parseAndProcessCode(code);
// const codeOpt = printSync(contractAst, {});
// console.log(opt);
// console.log(codeOpt);
Expand All @@ -27,3 +36,35 @@ export const buildCodeString = (

return contractCode;
};

export const parseAndProcessCode = (code: string) => {
const opt = parseSync(code, {
syntax: 'typescript',
target: 'es2022',
});
const contractAst = walkTop(opt);

return contractAst;
};
export const boundleContract = async (entry: string) => {
const bundle = await rollup({
input: entry,
plugins: [
(typescript as any)({
check: false,
}),
(commonjs as any)(),
wasm(),
(terser as any)({
ecma: 2020,
keep_classnames: true,
}),
nodeResolve(),
],
});
const res = await bundle.generate({
format: 'esm',
sourcemap: false,
});
return res.output[0].code;
};
39 changes: 21 additions & 18 deletions packages/contract_builder/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
/* eslint-disable no-console */
/* eslint-disable node/shebang */

import { readFileSync, writeFileSync } from 'fs';
import { readFileSync, rmSync, writeFileSync } from 'fs';
import { resolve } from 'path';
import { cac } from 'cac';
import chalk from 'chalk';
import { parseSync, transformSync } from '@swc/core';
import { printSync } from '@swc/core';

import { bytes } from 'multiformats';
import pkg from '../package.json' assert { type: 'json' };
import { buildCodeString } from './builder.js';
import { boundleContract, parseAndProcessCode } from './builder.js';
const version = pkg.version;
const cli = cac('sk-contract-builder');

Expand All @@ -24,27 +24,30 @@ const builder = async (input: string, opts: BuildOption) => {
try {
console.log(chalk.green('starting build contract...'));
input = resolve(input, './');
// console.log(codeSnippet);
let fileName: any = input.split('/').pop()?.split('.');

Check warning on line 27 in packages/contract_builder/src/cli.ts

View workflow job for this annotation

GitHub Actions / check

Unexpected any. Specify a different type
fileName?.pop();
fileName = fileName?.join('.');
const code = readFileSync(input).toString();
// console.log(code);
const res = buildCodeString(code, {
parseSync,
transformSync,
const ast = parseAndProcessCode(code);
const tsCode = printSync(ast, {});
const tsFile = resolve(input, `../${fileName}.processed.ts`);
writeFileSync(tsFile, tsCode.code, {
flag: 'w+',
});
// console.log(contractCode);
const resultUint8 = bytes.fromString(res.code);
// const resultU8String = `export default new Uint8Array([${resultUint8.toString()}]);`;
const boundleCode = await boundleContract(tsFile);
// const boundleCodeFile = resolve(input, '../index.contract.boundle.js');
// writeFileSync(boundleCodeFile, boundleCode, {
// flag: 'w+',
// });

const resultUint8 = bytes.fromString(boundleCode);
const resultU8String = `export default new Uint8Array([${resultUint8.toString()}]);`;
// console.log(resultUint8);
writeFileSync(
resolve(input, '../index.contract.bin'),
resultUint8.toString(),
{
flag: 'w+',
},
);
writeFileSync(resolve(input, '../index.contract.js'), res.code, {
writeFileSync(resolve(input, `../${fileName}.js`), resultU8String, {
flag: 'w+',
});
rmSync(tsFile);
console.log(chalk.green('contract build success'));
} catch (error) {
console.log(error);
Expand Down
1 change: 1 addition & 0 deletions packages/land_app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"@math.gl/web-mercator": "^3.6.3",
"@trustack/common": "workspace:^1.0.0",
"@trustack/contract": "workspace:^1.0.0",
"@trustack/contract_builder": "workspace:^1.0.0",
"@trustack/node-modules-polyfill": "^0.2.5",
"@trustack/rollup-plugin-node-polyfills": "^0.2.2",
"@xstate/react": "^3.2.2",
Expand Down
2 changes: 1 addition & 1 deletion packages/sknode/tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"declaration": true,
"isolatedModules": false,
"esModuleInterop": true,
"types": ["node", "jest", "@trustack/contract/src/contract"],
"types": ["node", "jest", "@trustack/contract/contract"],
"lib": ["ESNext", "DOM"],
"outDir": "./dist",
"baseUrl": "./src"
Expand Down
2 changes: 1 addition & 1 deletion packages/tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"declaration": true,
"isolatedModules": false,
"esModuleInterop": true,
"types": ["node", "jest", "@trustack/contract/src/contract"],
"types": ["node", "jest", "@trustack/contract/contract"],
"lib": ["ESNext", "DOM"]
},
"exclude": ["/**/__tests__"]
Expand Down
2 changes: 2 additions & 0 deletions packages/webui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"antd": "^5.7.3",
"buffer": "^6.0.3",
"esbuild": "^0.17.19",
"lodash": "^4.17.21",
"mime-types": "^2.1.35",
"multiformats": "^11.0.2",
"react": "^18.2.0",
Expand All @@ -36,6 +37,7 @@
"devDependencies": {
"@playwright/test": "^1.36.2",
"@rollup/plugin-inject": "^5.0.3",
"@types/lodash": "^4.14.196",
"@types/react": "^18.2.17",
"@types/react-dom": "^18.2.7",
"@vitejs/plugin-react-swc": "^3.3.2",
Expand Down
Loading

0 comments on commit b45b6c6

Please sign in to comment.