added harmony-network and new bundler

@types
neeboo 6 years ago
parent b823f1a03c
commit cff1cda279
  1. 2
      examples/temp.html
  2. 28
      examples/testNode.js
  3. 9
      gulpfile.js
  4. 9091
      includes/elliptic/elliptic.js
  5. 5
      package.json
  6. 8
      packages/harmony-account/package.json
  7. 4
      packages/harmony-account/src/account.ts
  8. 1
      packages/harmony-account/src/wallet.ts
  9. 2
      packages/harmony-account/tsconfig.json
  10. 10
      packages/harmony-crypto/package.json
  11. 5
      packages/harmony-crypto/tsconfig.json
  12. 10
      packages/harmony-network/package.json
  13. 8
      packages/harmony-network/src/http.ts
  14. 3
      packages/harmony-network/src/index.ts
  15. 148
      packages/harmony-network/src/messenger.ts
  16. 34
      packages/harmony-network/src/responseMiddleware.ts
  17. 46
      packages/harmony-network/src/rpcBuilder.ts
  18. 15
      packages/harmony-network/src/util.ts
  19. 2
      packages/harmony-network/tsconfig.json
  20. 16
      packages/harmony-utils/package.json
  21. 1
      packages/harmony-utils/src/index.ts
  22. 67
      packages/harmony-utils/src/transformers.ts
  23. 92
      packages/harmony-utils/src/validators.ts
  24. 2
      packages/harmony-utils/tsconfig.json
  25. 103
      scripts/bundle.ts
  26. 91
      scripts/projects.ts
  27. 192
      scripts/rollup/bundleBrowser.js
  28. 50
      tsconfig.base.json
  29. 6
      webpack.config.js

@ -36,6 +36,8 @@
</div>
<script src="../dist/HarmonyAccount.browser.js"></script>
<script src="../dist/HarmonyCrypto.browser.js"></script>
<script src="../dist/HarmonyUtils.browser.js"></script>
<script src="../dist/HarmonyNetwork.browser.js"></script>
</body>

@ -1,11 +1,20 @@
const { Account, Wallet } = require('../packages/harmony-account/lib/index.js');
const {
Account,
Wallet,
} = require('../packages/harmony-account/dist/index.js');
const {
getAddressFromPublicKey,
} = require('../packages/harmony-crypto/lib/index.js');
} = require('../packages/harmony-crypto/dist/index.js');
const {
isAddress,
isPrivateKey,
} = require('../packages/harmony-utils/lib/index.js');
} = require('../packages/harmony-utils/dist/index.js');
const { numberToHex } = require('../packages/harmony-utils/dist/index.js');
const {
HttpProvider,
Messenger,
} = require('../packages/harmony-network/dist/index.js');
// const a = Account.new();
@ -58,3 +67,16 @@ testWallet();
// console.log(a);
// });
// });
// const newProvider = new HttpProvider('https://dev-api.zilliqa.com');
// const msg = new Messenger(newProvider);
// const getBalance = async () => {
// const res = await msg.send(
// 'GetBalance',
// '9bfec715a6bd658fcb62b0f8cc9bfa2ade71434a',
// );
// console.log(res);
// };
// getBalance();

@ -1,7 +1,12 @@
const { task } = require('gulp');
const del = require('del');
const packages = ['harmony-crypto'];
const packages = [
'harmony-crypto',
'harmony-account',
'harmony-network',
'harmony-utils',
];
task('cleanBrowser', async () => {
await packages.map((p) => {
@ -12,7 +17,7 @@ task('cleanBrowser', async () => {
task('cleanServer', async () => {
await packages.map((p) => {
const pathToLib = `packages/${p}/node`;
const pathToLib = `packages/${p}/dist`;
return del.sync([pathToLib]);
});
});

File diff suppressed because it is too large Load Diff

@ -6,8 +6,10 @@
],
"scripts": {
"packages:cleanBrowser": "gulp cleanBrowser",
"packages:cleanServer": "gulp cleanServer",
"packages:browser": "yarn packages:cleanBrowser && rollup --c scripts/rollup/bundleBrowser.js",
"dist": "yarn packages:browser && rm -rf dist && cross-env NODE_ENV=production webpack --config webpack.config.js",
"packages:bundler": "yarn packages:cleanServer && yarn build:ts && ts-node -P scripts/tsconfig.json scripts/bundle.ts",
"dist": "yarn packages:bundler && rm -rf dist && cross-env NODE_ENV=production webpack --config webpack.config.js",
"bootstrap": "lerna bootstrap && yarn build",
"build": "yarn build:proto && yarn build:ts",
"build:ts": "tsc -b tsconfig.json",
@ -88,6 +90,7 @@
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-json": "^3.1.0",
"rollup-plugin-license": "^0.8.1",
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-globals": "^1.4.0",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-typescript2": "^0.17.1",

@ -2,8 +2,12 @@
"name": "@harmony/account",
"version": "0.0.1",
"description": "account and wallet for harmony",
"main": "lib/index.js",
"typings":"lib/index.d.ts",
"main": "dist/index.js",
"node": "dist/index.js",
"browser": "dist/index.js",
"module": "dist/index.esm.js",
"jsnext:main": "dist/index.esm.js",
"typings":"dist/index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},

@ -9,7 +9,7 @@ import {
Keystore,
} from '@harmony/crypto';
import { isPrivateKey } from '@harmony/utils';
import { isPrivateKey, add0xToString } from '@harmony/utils';
import { Shards, ShardId } from './types';
class Account {
@ -145,7 +145,7 @@ class Account {
if (!isPrivateKey(key)) {
throw new Error(`${key} is not PrivateKey`);
}
this.privateKey = key;
this.privateKey = add0xToString(key);
this.publicKey = getPubkeyFromPrivateKey(this.privateKey);
this.address = getAddressFromPrivateKey(this.privateKey);
this.shards = new Map().set('default', '');

@ -36,6 +36,7 @@ class Wallet {
}
const seed = bip39.mnemonicToSeed(phrase);
const hdKey = hdkey.fromMasterSeed(seed);
//TODO:hdkey should apply to Harmony's settings
const childKey = hdKey.derive(`m/44'/313'/0'/0/${index}`);
const privateKey = childKey.privateKey.toString('hex');
return this.addByPrivateKey(privateKey);

@ -3,7 +3,7 @@
"compilerOptions": {
"baseUrl": ".",
"paths": { "*": ["types/*"] },
"outDir": "lib",
"outDir": "dist",
"rootDir": "src"
},
"include": ["src", "../../typings/**/*.d.ts"],

@ -2,12 +2,12 @@
"name": "@harmony/crypto",
"version": "0.0.1",
"description": "crypto libraries for harmony",
"main": "lib/index.js",
"node": "lib/index.js",
"main": "dist/index.js",
"node": "dist/index.js",
"browser": "dist/index.js",
"module": "dist/index.js",
"jsnext:main": "dist/index.js",
"typings":"lib/index.d.ts",
"module": "dist/index.esm.js",
"jsnext:main": "dist/index.esm.js",
"typings":"dist/index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},

@ -1,8 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "lib",
"outDir": "dist",
"rootDir": "src"
},
"include": ["src", "../../typings/**/*.d.ts"]
"include": ["src", "../../typings/**/*.d.ts"],
"references": [{ "path": "../harmony-utils" }]
}

@ -2,12 +2,12 @@
"name": "@harmony/network",
"version": "0.0.1",
"description": "network suites for harmony",
"main": "lib/index.js",
"node": "lib/index.js",
"main": "dist/index.js",
"node": "dist/index.js",
"browser": "dist/index.js",
"module": "dist/index.js",
"jsnext:main": "dist/index.js",
"typings": "lib/index.d.ts",
"module": "dist/index.esm.js",
"jsnext:main": "dist/index.esm.js",
"typings": "dist/index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},

@ -45,7 +45,7 @@ class HttpProvider extends BaseProvider {
* @param {Function} callback - callback function
* @return {any} - RPC Response
*/
send(payload: RPCRequestPayload<object>, callback: any): Promise<any> {
send(payload: RPCRequestPayload<object>, callback?: any): Promise<any> {
return this.requestFunc({ payload, callback });
}
@ -121,10 +121,10 @@ class HttpProvider extends BaseProvider {
/**
* @function optionsHandler
* @memberof HttpProvider.prototype
* @param {Object} obj - options object
* @return {Object} - assign a new option object
* @param {object} obj - options object
* @return {object} - assign a new option object
*/
optionsHandler(obj: object) {
optionsHandler(obj: object): object {
if (this.options.user && this.options.password) {
const AUTH_TOKEN = `Basic ${Buffer.from(
`${this.options.user}:${this.options.password}`,

@ -1,5 +1,8 @@
export * from './baseProvider';
export * from './defaultFetcher';
export * from './messenger';
export * from './rpcBuilder';
export * from './util';
export * from './http';
export * from './net';
export * from './rpc';

@ -0,0 +1,148 @@
import { JsonRpc } from './rpcbuilder';
import { ResponseMiddleware } from './responseMiddleware';
import { HttpProvider } from './http';
import { getResultForData } from './util';
import { RPCMethod } from './rpc';
const defaultConfig = {
Default: {
CHAIN_ID: 0,
Network_ID: 'Default',
nodeProviderUrl: 'http://localhost:4200',
},
DevNet: {
CHAIN_ID: 333,
Network_ID: 'DevNet',
nodeProviderUrl: 'https://devnet.harmony.one',
},
TestNet: {
CHAIN_ID: 2,
Network_ID: 'TestNet',
nodeProviderUrl: 'https://devnet.harmony.one',
},
MainNet: {
CHAIN_ID: 1,
Network_ID: 'MainNet',
nodeProviderUrl: 'https://mainnet.harmony.one',
},
};
/**
* @class Messenger
* @description Messenger instance
* @param {HttpProvider} provider HttpProvider
* @param {Object} config config object
* @return {Messenger} Messenger instance
*/
class Messenger {
provider: HttpProvider;
config?: object;
// tslint:disable-next-line: variable-name
Network_ID: string = 'Default';
JsonRpc: JsonRpc;
constructor(provider: HttpProvider, config?: object) {
/**
* @var {Provider} provider
* @memberof Messenger.prototype
* @description Provider instance
*/
this.provider = provider;
/**
* @var {Object} config
* @memberof Messenger.prototype
* @description Messenger config
*/
this.config = config || defaultConfig;
/**
* @var {Number} Network_ID
* @memberof Messenger.prototype
* @description Network ID for current provider
*/
/**
* @var {JsonRpc} JsonRpc
* @memberof Messenger.prototype
* @description JsonRpc instance
*/
this.JsonRpc = new JsonRpc();
// set Network ID
this.setNetworkID(defaultConfig.Default.Network_ID);
}
/**
* @function send
* @memberof Messenger.prototype
* @param {String} method - RPC method
* @param {Object} params - RPC method params
* @return {Object} RPC result
*/
send = async (method: RPCMethod, params: any) => {
this.providerCheck();
try {
const payload = this.JsonRpc.toPayload(method, params);
this.setResMiddleware((data: any) => new ResponseMiddleware(data));
const result = await this.provider.send(payload);
return getResultForData(result); // getResultForData(result)
} catch (e) {
throw new Error(e);
}
};
/**
* @function setProvider
* @memberof Messenger
* @description provider setter
* @param {Provider} provider - provider instance
*/
setProvider(provider: HttpProvider) {
this.provider = provider;
}
/**
* @function providerCheck
* @memberof Messenger
* @description provider checker
* @return {Error|null} provider validator
*/
providerCheck() {
if (!this.provider) {
throw new Error('provider is not found');
}
}
/**
* @function setReqMiddleware
* @description set request middleware
* @memberof Messenger
* @param {any} middleware - middle ware for req
* @param {String} method - method name
*/
setReqMiddleware(middleware: any, method = '*') {
return this.provider.middlewares.request.use(middleware, method);
}
/**
* @function setResMiddleware
* @description set response middleware
* @memberof Messenger
* @param {any} middleware - middle ware for req
* @param {String} method - method name
*/
setResMiddleware(middleware: any, method = '*') {
return this.provider.middlewares.response.use(middleware, method);
}
/**
* @function setNetworkID
* @description set network id
* @memberof Messenger
* @param {String} id network id string
*/
setNetworkID(id: string) {
this.Network_ID = id;
}
}
export { Messenger };

@ -0,0 +1,34 @@
import { RPCResponseBody } from './types';
/**
* @class ResponseMiddleware
* @description Response middleware of RPC
* @param {Object} ResponseBody - response from rpc
* @return {ResponseMiddleware} response middleware instance
*/
class ResponseMiddleware {
result: any;
error: any;
raw: any;
constructor(ResponseBody: RPCResponseBody<any, any>) {
this.result = ResponseBody.result;
this.error = ResponseBody.error;
this.raw = ResponseBody;
}
get getResult() {
return typeof this.result === 'string'
? this.result
: { ...this.result, responseType: 'result' };
}
get getError() {
return typeof this.error === 'string'
? this.error
: { ...this.error, responseType: 'error' };
}
get getRaw() {
return { ...this.raw, responseType: 'raw' };
}
}
export { ResponseMiddleware };

@ -0,0 +1,46 @@
import { RPCRequestPayload } from './types';
import { RPCMethod } from './rpc';
/**
* @class JsonRpc
* @description json rpc instance
* @return {JsonRpc} Json RPC instance
*/
class JsonRpc {
messageId: number;
constructor() {
/**
* @var {Number} messageId
* @memberof JsonRpc.prototype
* @description message id, default 0
*/
this.messageId = 0;
}
/**
* @function toPayload
* @memberof JsonRpc.prototype
* @description convert method and params to payload object
* @param {String} method - RPC method
* @param {Array<object>} params - params that send to RPC
* @return {Object} payload object
*/
toPayload = (
method: RPCMethod,
params: string,
): RPCRequestPayload<object> => {
// FIXME: error to be done by shared/errors
if (!method) throw new Error('jsonrpc method should be specified!');
// advance message ID
this.messageId += 1;
return {
jsonrpc: '2.0',
id: this.messageId,
method,
params: params !== undefined ? [params] : [],
};
};
}
export { JsonRpc };

@ -0,0 +1,15 @@
/**
* @function getResultForData
* @description get result for data by default
* @param {any} data - object get from provider
* @return {any} data result or data
*/
export function getResultForData(data: any): any {
if (data.result) {
return data.getResult;
}
if (data.error) {
return data.getError;
}
return data.getRaw;
}

@ -1,7 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "lib",
"outDir": "dist",
"rootDir": "src"
},
"include": ["src", "../../typings/**/*.d.ts"]

@ -2,15 +2,19 @@
"name": "@harmony/utils",
"version": "0.0.1",
"description": "utils for harmony",
"main": "lib/index.js",
"node": "lib/index.js",
"main": "dist/index.js",
"node": "dist/index.js",
"browser": "dist/index.js",
"module": "dist/index.js",
"jsnext:main": "dist/index.js",
"typings":"lib/index.d.ts",
"module": "dist/index.esm.js",
"jsnext:main": "dist/index.esm.js",
"typings": "dist/index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "neeboo@firestack.one",
"license": "ISC"
"license": "ISC",
"dependencies": {
"@types/bn.js": "^4.11.3",
"bn.js": "^4.11.8"
}
}

@ -1 +1,2 @@
export * from './validators';
export * from './transformers';

@ -0,0 +1,67 @@
import BN from 'bn.js';
import { isString, isNumber, isHex } from './validators';
export const enum Units {
wei = 'wei',
kwei = 'kwei',
Mwei = 'Mwei',
Gwei = 'Gwei',
szabo = 'szabo',
finney = 'finney',
ether = 'ether',
}
export const numberToString = (
obj: BN | number | string,
radix: number = 10,
): string => {
if (BN.isBN(obj)) {
return obj.toString(radix);
} else if (isNumber(obj)) {
return new BN(obj).toString(radix);
} else if (isString(obj) && isNumber(Number(obj))) {
return new BN(obj).toString(radix);
} else {
throw new Error(`cannot parse number:${obj} to string`);
}
};
export const add0xToString = (obj: string): string => {
if (isString(obj) && !obj.startsWith('-')) {
return '0x' + obj.replace('0x', '');
} else if (isString(obj) && obj.startsWith('-')) {
return '-0x' + obj.replace('-', '');
} else {
throw new Error(`${obj} is not String`);
}
};
export const strip0x = (obj: string): string => {
return obj.toLowerCase().replace('0x', '');
};
export const numberToHex = (obj: any): string => {
try {
return add0xToString(numberToString(obj, 16));
} catch (error) {
throw error;
}
};
export const hexToNumber = (hex: string): string => {
if (isHex(hex)) {
return new BN(strip0x(hex), 'hex').toString();
} else {
throw new Error(`${hex} is not hex number`);
}
};
export const toWei = (obj: any): string => {
return '';
};
export const fromWei = (obj: any): string => {
return '';
};
export class Unit {}

@ -13,3 +13,95 @@ export const isPrivateKey = (privateKey: string): boolean => {
export const isPublicKey = (publicKey: string): boolean => {
return isKeyString(publicKey, 66);
};
/**
* [isNumber verify param is a Number]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isNumber = (obj: any): boolean => {
return obj === +obj;
};
/**
* [isNumber verify param is a Number]
* @param {any} obj [value]
* @return {boolean} [boolean]
*/
export const isInt = (obj: any): boolean => {
return isNumber(obj) && Number.isInteger(obj);
};
/**
* [isString verify param is a String]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isString = (obj: any): boolean => {
return obj === `${obj}`;
};
/**
* [isBoolean verify param is a Boolean]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isBoolean = (obj: any): boolean => {
return obj === !!obj;
};
/**
* [isArray verify param input is an Array]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isArray = (obj: any): boolean => {
return Array.isArray(obj);
};
/**
* [isJson verify param input is a Json]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isJsonString = (obj: any): boolean => {
try {
return !!JSON.parse(obj) && isObject(JSON.parse(obj));
} catch (e) {
return false;
}
};
/**
* [isObject verify param is an Object]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isObject = (obj: any): boolean => {
return obj !== null && !Array.isArray(obj) && typeof obj === 'object';
};
/**
* [isFunction verify param is a Function]
* @param {any} obj [value]
* @return {Boolean} [description]
*/
export const isFunction = (obj: any): boolean => {
return typeof obj === 'function';
};
export const isHex = (obj: string): boolean => {
if (!isString(obj)) {
throw new Error(`${obj} is not string`);
} else {
try {
return (
(obj.startsWith('0x') || obj.startsWith('-0x')) &&
isNumber(Number.parseInt(obj.toLowerCase().replace('0x', ''), 16))
);
} catch (error) {
throw error;
}
}
};

@ -1,7 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "lib",
"outDir": "dist",
"rootDir": "src"
},
"include": ["src", "../../typings/**/*.d.ts"]

@ -0,0 +1,103 @@
import * as path from 'path';
// tslint:disable-next-line: no-implicit-dependencies
import * as rollup from 'rollup';
// tslint:disable-next-line: no-implicit-dependencies
import alias from 'rollup-plugin-alias';
// tslint:disable-next-line: no-implicit-dependencies
import builtins from 'rollup-plugin-node-builtins';
// tslint:disable-next-line: no-implicit-dependencies
import commonjs from 'rollup-plugin-commonjs';
// tslint:disable-next-line: no-implicit-dependencies
import license from 'rollup-plugin-license';
// tslint:disable-next-line: no-implicit-dependencies
import json from 'rollup-plugin-json';
// tslint:disable-next-line: no-implicit-dependencies
import globals from 'rollup-plugin-node-globals';
// tslint:disable-next-line: no-implicit-dependencies
import resolve from 'rollup-plugin-node-resolve';
// tslint:disable-next-line: no-implicit-dependencies
import typescript2 from 'rollup-plugin-typescript2';
// tslint:disable-next-line: no-implicit-dependencies
import ts from 'typescript';
import { projects, preProcessFunc, preProcessProjects } from './projects';
async function bundles() {
await preProcessFunc(preProcessProjects);
for (const pkg of projects) {
const base = {
input: path.join(pkg.src, 'index.ts'),
plugins: [
alias({
elliptic: path.resolve(
__dirname,
'../',
'includes/elliptic/elliptic.js',
),
}),
resolve({
browser: true,
jsnext: true,
preferBuiltins: true,
}),
// babel(browserConfig),
globals(),
builtins(),
commonjs(),
json(),
typescript2({
typescript: ts, // ensure we're using the same typescript (3.x) for rollup as for regular builds etc
tsconfig: path.join(pkg.path, 'tsconfig.json'),
tsconfigOverride: {
module: 'esnext',
stripInternal: true,
emitDeclarationOnly: false,
composite: false,
declaration: false,
declarationMap: false,
sourceMap: true,
},
}),
license({
banner: `Test Banner`,
}),
],
external: projects
.filter((p) => p.name !== pkg.name)
.map((p) => p.scopedName)
.concat(['cross-fetch']),
};
const pkgBundler = await rollup.rollup(base);
await pkgBundler.write({
file: pkg.esm,
name: pkg.globalName,
format: 'esm',
sourcemap: true,
});
await pkgBundler.write({
file: pkg.umd,
exports: 'named',
name: pkg.globalName,
globals: {
...projects.reduce((g, pkg) => {
g[pkg.scopedName] = pkg.globalName;
return g;
}, {}),
tslib: 'tslib',
},
format: 'umd',
sourcemap: true,
});
await pkgBundler.write({
file: pkg.cjs,
name: pkg.globalName,
format: 'cjs',
sourcemap: true,
});
}
}
bundles();

@ -0,0 +1,91 @@
import * as path from 'path';
import * as fs from 'fs';
// tslint:disable-next-line: no-implicit-dependencies
import webpack from 'webpack';
// tslint:disable-next-line: no-implicit-dependencies
import camelCase from 'camelcase';
export const rootPath = path.resolve(__dirname, '../');
export const includesPath = path.join(rootPath, 'includes');
export const packagesPath = path.join(rootPath, 'packages');
export const preProcessProjects = {
preprocess: [
{
name: 'elliptic',
path: path.resolve(__dirname, '../node_modules/elliptic'),
entry: 'lib/elliptic.js',
outDir: path.join(includesPath, 'elliptic'),
},
],
};
export function preProcessFunc(project) {
const modules = project.preprocess.map((mod) => {
return new Promise((resolve, reject) => {
const compiler = webpack({
entry: {
[mod.name]: path.join(mod.path, mod.entry),
},
output: {
filename: '[name].js',
library: mod.name,
libraryTarget: 'commonjs2',
path: mod.outDir,
},
mode: 'production',
optimization: {
minimize: false,
},
});
compiler.run((err, stats) => {
if (err) {
reject(err);
} else {
// logPreProcess(
// `Successfully preprocessed ${Object.keys(
// stats.compilation.assets,
// ).join(' ,')}`,
// );
resolve(stats);
}
});
});
});
return Promise.all(modules);
}
export const projects = fs
.readdirSync(packagesPath)
.filter((p) => fs.lstatSync(path.join(packagesPath, p)).isDirectory())
.map((p) => {
const pkgName = path.basename(p);
const pkgGlobalName = camelCase(pkgName);
const pkgPath = path.join(packagesPath, p);
const pkgSrc = path.join(pkgPath, 'src');
const pkgScopedName = `@harmony/${p.replace('harmony-', '')}`;
const pkgDist = path.join(pkgPath, 'dist');
const pkgUmd = path.join(pkgDist, 'index.umd.js');
const pkgEsm = path.join(pkgDist, 'index.esm.js');
const pkgSystem = path.join(pkgDist, 'index.system.js');
const pkgAmd = path.join(pkgDist, 'index.amd.js');
const pkgCjs = path.join(pkgDist, 'index.cjs.js');
const pkgIife = path.join(pkgDist, 'index.js');
return {
name: pkgName,
globalName: pkgGlobalName,
scopedName: pkgScopedName,
path: pkgPath,
src: pkgSrc,
dist: pkgDist,
umd: pkgUmd,
esm: pkgEsm,
cjs: pkgCjs,
amd: pkgAmd,
iife: pkgIife,
system: pkgSystem,
};
});

@ -1,5 +1,6 @@
import * as path from 'path';
import camelCase from 'camelcase';
import * as fs from 'fs';
import * as rollup from 'rollup';
import alias from 'rollup-plugin-alias';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
@ -8,75 +9,31 @@ import json from 'rollup-plugin-json';
import globals from 'rollup-plugin-node-globals';
import resolve from 'rollup-plugin-node-resolve';
import typescript2 from 'rollup-plugin-typescript2';
import webpack from 'webpack';
import camelCase from 'camelcase';
import ts from 'typescript';
import packages from '../packages';
import browserConfig from '../babel/babel.browser.config.js';
import { getKeys } from './getDependencies';
const rootPath = path.resolve(__dirname, '../..');
const includesPath = path.join(rootPath, 'includes');
const packagesPath = path.join(rootPath, 'packages');
const project = {
preprocess: [
{
name: 'elliptic',
path: path.resolve(__dirname, '../node_modules/elliptic'),
entry: 'lib/elliptic.js',
outDir: path.join(includesPath, 'elliptic'),
},
],
};
function preProcess(project) {
const modules = project.preprocess.map((mod) => {
return new Promise((resolve, reject) => {
const compiler = webpack({
entry: {
[mod.name]: path.join(mod.path, mod.entry),
},
output: {
filename: '[name].js',
library: mod.name,
libraryTarget: 'commonjs2',
path: mod.outDir,
},
mode: 'production',
optimization: {
minimize: false,
},
});
compiler.run((err, stats) => {
if (err) {
reject(err);
} else {
// logPreProcess(
// `Successfully preprocessed ${Object.keys(
// stats.compilation.assets,
// ).join(' ,')}`,
// );
resolve(stats);
}
});
});
});
return Promise.all(modules);
}
import {
rootPath,
includesPath,
packagesPath,
projects,
preProcessFunc,
preProcessProjects,
} from '../projects';
async function bundles() {
await preProcess(project);
await preProcessFunc(preProcessProjects);
return packages.map((p) => {
const external = getKeys(p);
const externalSetting = getKeys(p).length > 0 ? { external } : {};
const externalObject = external.reduce((g, pkg) => {
g[`${pkg}`] = pkg.startsWith('@harmony') ? pkg : camelCase(pkg);
return g;
}, {});
const normal = {
input: `packages/${p}/src/index.ts`,
for (const pkg of projects) {
const externals = projects
.filter((p) => p.name !== pkg.name)
.map((p) => p.scopedName);
const base = {
input: path.join(pkg.src, 'index.ts'),
plugins: [
alias({
elliptic: path.resolve(
@ -90,12 +47,13 @@ async function bundles() {
jsnext: true,
preferBuiltins: true,
}),
babel(browserConfig),
// babel(browserConfig),
globals(),
commonjs(),
json(),
typescript2({
typescript: ts, // ensure we're using the same typescript (3.x) for rollup as for regular builds etc
tsconfig: `${packagesPath}/${p.name}/tsconfig.json`,
tsconfigOverride: {
module: 'esnext',
stripInternal: true,
@ -110,21 +68,99 @@ async function bundles() {
banner: `Test Banner`,
}),
],
output: {
file: `packages/${p}/dist/index.js`,
exports: 'named',
format: 'umd',
sourcemap: true,
name: camelCase(p),
globals: {
...externalObject,
tslib: 'tslib',
},
},
external: projects
.filter((p) => p.name !== pkg.name)
.map((p) => p.scopedName)
.concat(['cross-fetch']),
};
// return normal;
return Object.assign(normal, externalSetting);
});
const pkgBundler = await rollup.rollup(base);
await pkgBundler.write({
file: pkg.esm,
name: pkg.globalName,
format: 'esm',
sourcemap: true,
});
await bundle.write({
file: pkg.umd,
exports: 'named',
name: pkg.globalName,
globals: {
...projects.reduce((g, pkg) => {
g[pkg.scopedName] = pkg.globalName;
return g;
}, {}),
tslib: 'tslib',
},
format: 'umd',
sourcemap: true,
});
}
// return projects.map((p) => {
// const external = getKeys(p.name).filter(
// (pkg) => !pkg.startsWith('@harmony'),
// );
// const externalSetting = getKeys(p.name).length > 0 ? { external } : {};
// const externalObject = external.reduce((g, pkg) => {
// g[`${pkg}`] = !pkg.startsWith('@harmony')
// ? pkg
// : `@harmony/${p.name.replace('harmony-', '')}`;
// return g;
// }, {});
// const normal = {
// input: `packages/${p.name}/src/index.ts`,
// plugins: [
// alias({
// elliptic: path.resolve(
// __dirname,
// '../',
// 'includes/elliptic/elliptic.js',
// ),
// }),
// resolve({
// browser: true,
// jsnext: true,
// preferBuiltins: true,
// }),
// // babel(browserConfig),
// globals(),
// commonjs(),
// json(),
// typescript2({
// typescript: ts, // ensure we're using the same typescript (3.x) for rollup as for regular builds etc
// tsconfig: `${packagesPath}/${p.name}/tsconfig.json`,
// tsconfigOverride: {
// module: 'esnext',
// stripInternal: true,
// emitDeclarationOnly: false,
// composite: false,
// declaration: false,
// declarationMap: false,
// sourceMap: true,
// },
// }),
// license({
// banner: `Test Banner`,
// }),
// ],
// output: {
// file: `packages/${p.name}/dist/index.js`,
// exports: 'named',
// format: 'umd',
// sourcemap: true,
// name: camelCase(p.name),
// globals: {
// ...externalObject,
// tslib: 'tslib',
// },
// },
// };
// // return normal;
// return Object.assign(normal, externalSetting);
// });
}
export default bundles();

@ -1,26 +1,26 @@
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"composite": true,
"declaration": true,
"declarationMap": true,
"downlevelIteration": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"preserveConstEnums": true,
"importHelpers": true,
"lib": ["esnext", "dom"],
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"paths": {
"*": ["typings/*", "includes/*"]
},
"resolveJsonModule": true,
"noUnusedLocals": true,
"strict": true,
"target": "es5"
}
}
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"composite": true,
"declaration": true,
"declarationMap": true,
"downlevelIteration": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"preserveConstEnums": true,
"importHelpers": true,
"lib": ["esnext", "dom"],
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"paths": {
"*": ["typings/*", "includes/*"]
},
"resolveJsonModule": true,
"noUnusedLocals": true,
"strict": true,
"target": "es5"
}
}

@ -14,9 +14,9 @@ function createBatchConfig(list) {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
},
// use: {
// loader: 'babel-loader',
// },
},
],
},

Loading…
Cancel
Save