Skip to content

Commit

Permalink
Convert from Flow to Typescript (#816)
Browse files Browse the repository at this point in the history
* convert to typescript
* add docs for custom node typing
* update webpack, gulpfile
  • Loading branch information
FredKSchott authored and intelliot committed Dec 24, 2017
1 parent 5979ff6 commit 8204f6c
Show file tree
Hide file tree
Showing 86 changed files with 1,627 additions and 1,530 deletions.
73 changes: 38 additions & 35 deletions Gulpfile.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
/* eslint-disable no-var, no-param-reassign */
/* these eslint rules are disabled because gulp does not support babel yet */
'use strict';
var _ = require('lodash');
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var webpack = require('webpack');
var bump = require('gulp-bump');
var argv = require('yargs').argv;
var assert = require('assert');
var fs = require('fs');
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const gulp = require('gulp');
const rename = require('gulp-rename');
const webpack = require('webpack');
const bump = require('gulp-bump');
const argv = require('yargs').argv;
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

var pkg = require('./package.json');

var uglifyOptions = {
mangle: {
except: ['_', 'RippleError', 'RippledError', 'UnexpectedError',
reserved: ['_', 'RippleError', 'RippledError', 'UnexpectedError',
'LedgerVersionError', 'ConnectionError', 'NotConnectedError',
'DisconnectedError', 'TimeoutError', 'ResponseFormatError',
'ValidationError', 'NotFoundError', 'MissingLedgerHistoryError',
Expand All @@ -24,17 +25,17 @@ var uglifyOptions = {
}
};

function webpackConfig(extension, overrides) {
function getWebpackConfig(extension, overrides) {
overrides = overrides || {};
var defaults = {
let defaults = {
cache: true,
externals: [{
'lodash': '_'
}],
entry: './src/index.js',
entry: './src/index.ts',
output: {
library: 'ripple',
path: './build/',
path: path.join(__dirname, 'build/'),
filename: ['ripple-', extension].join(pkg.version)
},
plugins: [
Expand All @@ -44,18 +45,21 @@ function webpackConfig(extension, overrides) {
'./setup-api-web')
],
module: {
loaders: [{
rules: [{
test: /jayson/,
loader: 'null'
use: 'null',
}, {
test: /\.js$/,
exclude: [/node_modules/],
loader: 'babel-loader'
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
}, {
test: /\.json/,
loader: 'json-loader'
use: 'json-loader',
}]
}
},
resolve: {
extensions: [ '.ts', '.js' ]
},
};
return _.assign({}, defaults, overrides);
}
Expand All @@ -78,7 +82,7 @@ function webpackConfigForWebTest(testFileName, path) {
filename: match[1] + '-test.js'
}
};
return webpackConfig('.js', configOverrides);
return getWebpackConfig('.js', configOverrides);
}

gulp.task('build-tests', function(callback) {
Expand Down Expand Up @@ -112,30 +116,29 @@ function createBuildLink(callback) {
}

gulp.task('build', function(callback) {
webpack(webpackConfig('.js'), createBuildLink(callback));
webpack(getWebpackConfig('.js'), createBuildLink(callback));
});

gulp.task('build-min', ['build'], function() {
return gulp.src(['./build/ripple-', '.js'].join(pkg.version))
.pipe(uglify(uglifyOptions))
.pipe(rename(['ripple-', '-min.js'].join(pkg.version)))
.pipe(gulp.dest('./build/'))
.on('end', function() {
gulp.task('build-min', function(callback) {
const webpackConfig = getWebpackConfig('-min.js');
webpackConfig.plugins.push(new UglifyJsPlugin({uglifyOptions}));
webpack(webpackConfig, function() {
createLink('./build/ripple-' + pkg.version + '-min.js',
'./build/ripple-latest-min.js');
callback();
});
});

gulp.task('build-debug', function(callback) {
var configOverrides = {debug: true, devtool: 'eval'};
webpack(webpackConfig('-debug.js', configOverrides), callback);
const webpackConfig = getWebpackConfig('-debug.js', {devtool: 'eval'});
webpackConfig.plugins.unshift(new webpack.LoaderOptionsPlugin({debug: true}));
webpack(webpackConfig, callback);
});

/**
* Generate a WebPack external for a given unavailable module which replaces
* that module's constructor with an error-thrower
*/

function buildUseError(cons) {
return ('var {<CONS>:function(){throw new Error('
+ '"Class is unavailable in this build: <CONS>")}}')
Expand All @@ -145,18 +148,18 @@ function buildUseError(cons) {
gulp.task('build-core', function(callback) {
var configOverrides = {
cache: false,
entry: './src/remote.js',
entry: './src/remote.ts',
externals: [{
'./transaction': buildUseError('Transaction'),
'./orderbook': buildUseError('OrderBook'),
'./account': buildUseError('Account'),
'./serializedobject': buildUseError('SerializedObject')
}],
plugins: [
new webpack.optimize.UglifyJsPlugin()
new UglifyJsPlugin()
]
};
webpack(webpackConfig('-core.js', configOverrides), callback);
webpack(getWebpackConfig('-core.js', configOverrides), callback);
});

gulp.task('bower-build', ['build'], function() {
Expand Down
9 changes: 9 additions & 0 deletions custom_typings/node.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* This is an extension of Node's `process` object to include the browser
* property, which is added by webpack.
*/
interface AmbiguousProcess extends NodeJS.Process {
browser?: true
}

declare var process: AmbiguousProcess;
27 changes: 12 additions & 15 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
"test": "test"
},
"dependencies": {
"@types/lodash": "^4.14.85",
"@types/ws": "^3.2.0",
"bignumber.js": "^4.1.0",
"https-proxy-agent": "^1.0.0",
"jsonschema": "^1.1.1",
Expand All @@ -27,25 +29,16 @@
"ws": "^3.3.1"
},
"devDependencies": {
"@types/node": "^8.0.53",
"assert-diff": "^1.0.1",
"babel-cli": "^6.26.0",
"babel-core": "^6.4.0",
"babel-eslint": "^6.0.4",
"babel-loader": "^6.2.1",
"babel-preset-es2015": "^6.3.13",
"babel-preset-flow": "^6.23.0",
"babel-preset-stage-1": "^6.3.13",
"babel-register": "^6.3.13",
"coveralls": "^2.13.1",
"doctoc": "^0.15.0",
"ejs": "^2.3.4",
"eslint": "^2.9.0",
"eventemitter2": "^0.4.14",
"flow-bin": "^0.59.0",
"gulp": "^3.8.10",
"gulp-bump": "^0.1.13",
"gulp-rename": "^1.2.0",
"gulp-uglify": "^1.1.0",
"http-server": "^0.8.5",
"istanbul": "^1.1.0-alpha.1",
"jayson": "^1.2.2",
Expand All @@ -55,20 +48,24 @@
"mocha-in-sauce": "^0.0.1",
"mocha-junit-reporter": "^1.9.1",
"null-loader": "^0.1.1",
"webpack": "^1.5.3",
"yargs": "^1.3.1"
"ts-loader": "^3.2.0",
"ts-node": "^3.3.0",
"typescript": "^2.6.1",
"uglifyjs-webpack-plugin": "^1.1.4",
"webpack": "^3.10.0",
"yargs": "^8.0.2"
},
"scripts": {
"build": "gulp",
"doctoc": "doctoc docs/index.md --title '# RippleAPI Reference' --github --maxlevel 2",
"docgen": "node --harmony scripts/build_docs.js",
"clean": "rm -rf dist/npm",
"typecheck": "flow check",
"compile": "babel -D --optional runtime -d dist/npm/ src/",
"watch": "babel -w -D --optional runtime -d dist/npm/ src/",
"compile": "mkdir -p dist/npm/common && cp -r src/common/schemas dist/npm/common/ && tsc",
"watch": "tsc -w",
"compile-with-source-maps": "babel -D --optional runtime -s -t -d dist/npm/ src/",
"prepublish": "npm run clean && npm run compile",
"test": "babel-node ./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha",
"test": "istanbul cover _mocha",
"coveralls": "cat ./coverage/lcov.info | coveralls",
"lint": "if ! [ -f .eslintrc ]; then curl -o .eslintrc 'https://raw.githubusercontent.com/ripple/javascript-style-guide/es6/eslintrc'; echo 'parser: babel-eslint' >> .eslintrc; fi; eslint -c .eslintrc src/",
"perf": "./scripts/perf_test.sh",
Expand Down
90 changes: 43 additions & 47 deletions src/api.js → src/api.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
/* @flow */

import * as _ from 'lodash'
import events from 'events'
import {EventEmitter} from 'events'
import {Connection, errors, validate} from './common'
import * as server from './server/server'
const connect = server.connect
Expand Down Expand Up @@ -56,7 +54,7 @@ type APIOptions = {

// prevent access to non-validated ledger versions
class RestrictedConnection extends Connection {
request(request, timeout) {
request(request: any, timeout?: number) {
const ledger_index = request.ledger_index
if (ledger_index !== undefined && ledger_index !== 'validated') {
if (!_.isNumber(ledger_index) || ledger_index > this._ledgerVersion) {
Expand All @@ -69,7 +67,7 @@ class RestrictedConnection extends Connection {
}
}

class RippleAPI extends events.EventEmitter {
class RippleAPI extends EventEmitter {

_feeCushion: number
connection: RestrictedConnection
Expand All @@ -80,11 +78,11 @@ class RippleAPI extends events.EventEmitter {
RangeSet,
ledgerUtils,
schemaValidator
};
}

constructor(options: APIOptions = {}) {
validate.apiOptions(options)
super()
validate.apiOptions(options)
this._feeCushion = options.feeCushion || 1.2
const serverURL = options.server
if (serverURL !== undefined) {
Expand All @@ -107,50 +105,48 @@ class RippleAPI extends events.EventEmitter {
this.connection = new RestrictedConnection(null, options)
}
}
}

_.assign(RippleAPI.prototype, {
connect,
disconnect,
isConnected,
getServerInfo,
getFee,
getLedgerVersion,
connect = connect
disconnect = disconnect
isConnected = isConnected
getServerInfo = getServerInfo
getFee = getFee
getLedgerVersion = getLedgerVersion

getTransaction,
getTransactions,
getTrustlines,
getBalances,
getBalanceSheet,
getPaths,
getOrders,
getOrderbook,
getSettings,
getAccountInfo,
getPaymentChannel,
getLedger,
getTransaction = getTransaction
getTransactions = getTransactions
getTrustlines = getTrustlines
getBalances = getBalances
getBalanceSheet = getBalanceSheet
getPaths = getPaths
getOrders = getOrders
getOrderbook = getOrderbook
getSettings = getSettings
getAccountInfo = getAccountInfo
getPaymentChannel = getPaymentChannel
getLedger = getLedger

preparePayment,
prepareTrustline,
prepareOrder,
prepareOrderCancellation,
prepareEscrowCreation,
prepareEscrowExecution,
prepareEscrowCancellation,
preparePaymentChannelCreate,
preparePaymentChannelFund,
preparePaymentChannelClaim,
prepareSettings,
sign,
combine,
submit,
preparePayment = preparePayment
prepareTrustline = prepareTrustline
prepareOrder = prepareOrder
prepareOrderCancellation = prepareOrderCancellation
prepareEscrowCreation = prepareEscrowCreation
prepareEscrowExecution = prepareEscrowExecution
prepareEscrowCancellation = prepareEscrowCancellation
preparePaymentChannelCreate = preparePaymentChannelCreate
preparePaymentChannelFund = preparePaymentChannelFund
preparePaymentChannelClaim = preparePaymentChannelClaim
prepareSettings = prepareSettings
sign = sign
combine = combine
submit = submit

generateAddress: generateAddressAPI,
computeLedgerHash,
signPaymentChannelClaim,
verifyPaymentChannelClaim,
errors
})
generateAddress = generateAddressAPI
computeLedgerHash = computeLedgerHash
signPaymentChannelClaim = signPaymentChannelClaim
verifyPaymentChannelClaim = verifyPaymentChannelClaim
errors = errors
}

export {
RippleAPI
Expand Down
Loading

0 comments on commit 8204f6c

Please sign in to comment.