From 830040021d27cb2e8d30a53f4612af538597d6be Mon Sep 17 00:00:00 2001 From: emizzle Date: Tue, 11 Sep 2018 12:20:31 +1000 Subject: [PATCH] Constructor refactor, clean up Linting, remove swarmjs.min, format spaces Refactored constructor of SwarmJS to remove `mode` option. By default, if no `gateway` option is passed in, the default gateway will be `https://swarm-gateways.net`. Removed the `else if` and only list `swarm-gateways.net` once. --- .gitignore | 2 +- README.md | 5 ++--- bin/swarmjs | 26 ++++++++++++++------------ src/browser.js | 2 +- src/index.js | 7 ++++--- src/shared.js | 44 ++++++++++++++++++++++++-------------------- swarmjs.min.js | 1 - webpack.config.js | 40 +++++++++++++++++++--------------------- 8 files changed, 65 insertions(+), 62 deletions(-) delete mode 100644 swarmjs.min.js diff --git a/.gitignore b/.gitignore index df1263c..29120a7 100644 --- a/.gitignore +++ b/.gitignore @@ -33,7 +33,7 @@ package .vscode .eslintrc.json -swarm.min.js +swarmjs.min.js swarmjs-*.tgz NOTES npm-debug.log diff --git a/README.md b/README.md index 3fa31ba..2e76d0f 100644 --- a/README.md +++ b/README.md @@ -27,10 +27,9 @@ Available options: | Option | Description | Default | | -----| ------------| ------- | -| `gateway` | URL of the Swarm gateway, ie `http://localhost:8500`. | `swarm-gateways.net` | -| `mode` | Protocol of the default gateway URL. If `gateway` is provided, this has no effect. | `https` | +| `gateway` | URL of the Swarm gateway, ie `http://localhost:8500`. | `https://swarm-gateways.net` | -NOTE: If no options are provided, the default gateway URL will be `https://swarm-gateways.net`. This means you don't necessarily need to [run your own Swarm node](https://swarm-guide.readthedocs.io/en/latest/gettingstarted.html), however there is an upload limit of ~2.5MB and no guarantees about permanence. It is recommended to run your own Swarm node. +NOTE: If no options are provided, the default gateway URL will be `https://swarm-gateways.net`. This means you don't necessarily need to [run your own Swarm node](https://swarm-guide.readthedocs.io/en/latest/gettingstarted.html), however there is an upload limit of ~2.5MB and no guarantees regarding permanence. *It is recommended to run your own Swarm node.* ##### Check gateway availability ``` // Check gateway availability diff --git a/bin/swarmjs b/bin/swarmjs index 8e3c844..6794692 100755 --- a/bin/swarmjs +++ b/bin/swarmjs @@ -29,12 +29,12 @@ const yargs = require('yargs') .version() .showHelpOnFail(false, 'Specify --help for available options') .help() - .demand(1, 'Must provide a command') + .demand(1, 'Must provide a command'); const argv = yargs.argv; const gateway = argv.gateway; const command = argv._[0]; -const swarmjs = new SwarmJS({ gateway }); +const swarmjs = new SwarmJS({gateway}); function abort(msg) { console.log(msg || 'Error occured'); @@ -45,22 +45,24 @@ switch (command) { case 'get': swarmjs.downloadRaw(argv.hash, function (err, ret) { if (err) { - abort('Failed to download: ' + err) + abort('Failed to download: ' + err); } else { - console.log(ret) + console.log(ret); } - }) - break + }); + break; case 'put': swarmjs.uploadRaw(fs.readFileSync(argv.filename), function (err, ret) { if (err) { - console.log('Failed to upload: ' + err) + console.log('Failed to upload: ' + err); } else { - console.log('Swarm hash: ' + ret) + console.log('Swarm hash: ' + ret); } - }) - break + }); + break; case 'calculate': - console.log('Swarm hash: ' + swarmhash(fs.readFileSync(argv.filename)).toString('hex')) - break + console.log('Swarm hash: ' + swarmhash(fs.readFileSync(argv.filename)).toString('hex')); + break; + default: + console.log('Invalid arguments. Type \'swarmjs --help\' for valid options'); } diff --git a/src/browser.js b/src/browser.js index d13ab21..925bf62 100644 --- a/src/browser.js +++ b/src/browser.js @@ -1 +1 @@ -export {default} from './shared'; \ No newline at end of file +export {default} from './shared'; diff --git a/src/index.js b/src/index.js index 17e9ae1..30c6b0b 100644 --- a/src/index.js +++ b/src/index.js @@ -1,3 +1,4 @@ +/* eslint no-useless-constructor: "off" */ const resolve = require('path').resolve; import _SwarmJS from './shared'; import fs from 'fs'; @@ -15,9 +16,9 @@ class SwarmJS extends _SwarmJS { let errors = []; const excludeDirFilter = through2.obj(function (item, enc, next) { - if (!item.stats.isDirectory()) this.push(item) - next() - }) + if (!item.stats.isDirectory()) this.push(item); + next(); + }); klaw(directory) .pipe(excludeDirFilter) diff --git a/src/shared.js b/src/shared.js index c601d2e..d5e4877 100644 --- a/src/shared.js +++ b/src/shared.js @@ -4,39 +4,43 @@ class _SwarmJS { constructor(opts) { this.opts = opts || {}; + this.gateway = 'https://swarm-gateways.net'; if (this.opts.gateway) { - this.gateway = opts.gateway - } else if (this.opts.mode === 'http') { - this.gateway = 'http://swarm-gateways.net' - } else { - this.gateway = 'https://swarm-gateways.net' + this.gateway = opts.gateway; } } _isValidHash(hash) { - return /^[0-9a-f]{64}$/.test(hash) + return (/^[0-9a-f]{64}$/).test(hash); + } + + _contentResponse(error, response, body, cb) { + if (error) { + cb(error); + } else if (response.statusCode !== 200) { + cb(body); + } else { + cb(null, body); + } + } _hashResponse(error, response, body, cb) { - if (error) { - cb(error) - } else if (response.statusCode !== 200) { - cb(body) - } else if (!this._isValidHash(body)) { - cb('Invalid hash') - } else { - cb(null, body) - } + this._contentResponse(error, response, body, (err, body) => { + if (err) return cb(err); + if (!this._isValidHash(body)) return cb('Invalid hash'); + return cb(null, body); + }); } download(url, cb) { request(`${this.gateway}/${url}`, (error, response, body) => { if (error) { - cb(error) + cb(error); } else if (response.statusCode !== 200) { - cb(body) + cb(body); } else { - cb(null, body) + cb(null, body); } }); } @@ -49,7 +53,7 @@ class _SwarmJS { request.post({ url: `${this.gateway}/${url}`, body: content - }, (error, response, body) => this._hashResponse(error, response, body, cb)) + }, (error, response, body) => this._hashResponse(error, response, body, cb)); } uploadRaw(content, cb) { @@ -60,7 +64,7 @@ class _SwarmJS { let postObj = { url: `${this.gateway}/bzz:/`, formData: formData, - qs: { defaultpath: defaultPath } + qs: {defaultpath: defaultPath} }; request.post(postObj, (error, response, body) => this._hashResponse(error, response, body, cb)); diff --git a/swarmjs.min.js b/swarmjs.min.js deleted file mode 100644 index 91fb2c8..0000000 --- a/swarmjs.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("SwarmJS",[],e):"object"==typeof exports?exports.SwarmJS=e():t.SwarmJS=e()}("undefined"!=typeof self?self:this,function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=28)}([function(t,e,n){t.exports=!n(5)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e){var n=t.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n)},function(t,e,n){var r=n(13),o=n(14),u=n(16),i=Object.defineProperty;e.f=n(0)?Object.defineProperty:function(t,e,n){if(r(t),e=u(e,!0),r(n),o)try{return i(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e,n){t.exports=n(7)},function(t,e,n){n(8);var r=n(3).Object;t.exports=function(t,e,n){return r.defineProperty(t,e,n)}},function(t,e,n){var r=n(9);r(r.S+r.F*!n(0),"Object",{defineProperty:n(4).f})},function(t,e,n){var r=n(2),o=n(3),u=n(10),i=n(12),a=n(18),c=function(t,e,n){var f,s,l,p=t&c.F,d=t&c.G,y=t&c.S,h=t&c.P,v=t&c.B,w=t&c.W,b=d?o:o[e]||(o[e]={}),m=b.prototype,g=d?r:y?r[e]:(r[e]||{}).prototype;for(f in d&&(n=e),n)(s=!p&&g&&void 0!==g[f])&&a(b,f)||(l=s?g[f]:n[f],b[f]=d&&"function"!=typeof g[f]?n[f]:v&&s?u(l,r):w&&g[f]==l?function(t){var e=function(e,n,r){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,n)}return new t(e,n,r)}return t.apply(this,arguments)};return e.prototype=t.prototype,e}(l):h&&"function"==typeof l?u(Function.call,l):l,h&&((b.virtual||(b.virtual={}))[f]=l,t&c.R&&m&&!m[f]&&i(m,f,l)))};c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,t.exports=c},function(t,e,n){var r=n(11);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,o){return t.call(e,n,r,o)}}return function(){return t.apply(e,arguments)}}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e,n){var r=n(4),o=n(17);t.exports=n(0)?function(t,e,n){return r.f(t,e,o(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){var r=n(1);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e,n){t.exports=!n(0)&&!n(5)(function(){return 7!=Object.defineProperty(n(15)("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(1),o=n(2).document,u=r(o)&&r(o.createElement);t.exports=function(t){return u?o.createElement(t):{}}},function(t,e,n){var r=n(1);t.exports=function(t,e){if(!r(t))return t;var n,o;if(e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;if("function"==typeof(n=t.valueOf)&&!r(o=n.call(t)))return o;if(!e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){"use strict";var r=n(20),o=n(22),u=n(23),i=n(27);function a(t,e,n){var r=t;return o(e)?(n=e,"string"==typeof t&&(r={uri:t})):r=i(e,{uri:t}),r.callback=n,r}function c(t,e,n){return f(e=a(t,e,n))}function f(t){if(void 0===t.callback)throw new Error("callback argument missing");var e=!1,n=function(n,r,o){e||(e=!0,t.callback(n,r,o))};function r(t){return clearTimeout(s),t instanceof Error||(t=new Error(""+(t||"Unknown XMLHttpRequest Error"))),t.statusCode=0,n(t,w)}function o(){if(!a){var e;clearTimeout(s),e=t.useXDR&&void 0===f.status?200:1223===f.status?204:f.status;var r=w,o=null;return 0!==e?(r={body:function(){var t=void 0;if(t=f.response?f.response:f.responseText||function(t){try{if("document"===t.responseType)return t.responseXML;var e=t.responseXML&&"parsererror"===t.responseXML.documentElement.nodeName;if(""===t.responseType&&!e)return t.responseXML}catch(t){}return null}(f),v)try{t=JSON.parse(t)}catch(t){}return t}(),statusCode:e,method:p,headers:{},url:l,rawRequest:f},f.getAllResponseHeaders&&(r.headers=u(f.getAllResponseHeaders()))):o=new Error("Internal XMLHttpRequest Error"),n(o,r,r.body)}}var i,a,f=t.xhr||null;f||(f=t.cors||t.useXDR?new c.XDomainRequest:new c.XMLHttpRequest);var s,l=f.url=t.uri||t.url,p=f.method=t.method||"GET",d=t.body||t.data,y=f.headers=t.headers||{},h=!!t.sync,v=!1,w={body:void 0,headers:{},statusCode:0,method:p,url:l,rawRequest:f};if("json"in t&&!1!==t.json&&(v=!0,y.accept||y.Accept||(y.Accept="application/json"),"GET"!==p&&"HEAD"!==p&&(y["content-type"]||y["Content-Type"]||(y["Content-Type"]="application/json"),d=JSON.stringify(!0===t.json?d:t.json))),f.onreadystatechange=function(){4===f.readyState&&setTimeout(o,0)},f.onload=o,f.onerror=r,f.onprogress=function(){},f.onabort=function(){a=!0},f.ontimeout=r,f.open(p,l,!h,t.username,t.password),h||(f.withCredentials=!!t.withCredentials),!h&&t.timeout>0&&(s=setTimeout(function(){if(!a){a=!0,f.abort("timeout");var t=new Error("XMLHttpRequest timeout");t.code="ETIMEDOUT",r(t)}},t.timeout)),f.setRequestHeader)for(i in y)y.hasOwnProperty(i)&&f.setRequestHeader(i,y[i]);else if(t.headers&&!function(t){for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}(t.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in t&&(f.responseType=t.responseType),"beforeSend"in t&&"function"==typeof t.beforeSend&&t.beforeSend(f),f.send(d||null),f}t.exports=c,t.exports.default=c,c.XMLHttpRequest=r.XMLHttpRequest||function(){},c.XDomainRequest="withCredentials"in new c.XMLHttpRequest?c.XMLHttpRequest:r.XDomainRequest,function(t,e){for(var n=0;n=3&&(i=n),"[object Array]"===o.call(t)?function(t,e,n){for(var r=0,o=t.length;r1&&void 0!==arguments[1]?arguments[1]:"index.html",r=arguments.length>2?arguments[2]:void 0,o={url:"".concat(this.gateway,"/bzz:/"),formData:t,qs:{defaultpath:n}};i.post(o,function(t,n,o){return e._hashResponse(t,n,o,r)})}},{key:"isAvailable",value:function(t){try{this.uploadRaw("test",function(e,n){if(e)return t(e);t(null,"6de1faa7d29b1931b4ba3d44befcf7a5e43e947cd0bf2db154172bac5ecac3a6"===n)})}catch(e){t(e)}}}]),t}();n.d(e,"default",function(){return a})}]).default}); \ No newline at end of file diff --git a/webpack.config.js b/webpack.config.js index 33913af..50a9144 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,26 +1,24 @@ const path = require('path'); const standalone = { - entry: path.join(__dirname, 'dist/browser', 'browser.js'), - mode: 'production', - // optimization: { - // minimize: false - // }, - output: { - filename: 'swarmjs.min.js', - globalObject: 'typeof self !== \'undefined\' ? self : this', - library: 'SwarmJS', - libraryTarget: 'umd', - libraryExport: 'default', - path: __dirname, - umdNamedDefine: true, - }, - target: 'web', - node: { - fs: 'empty' - } + entry: path.join(__dirname, 'dist/browser', 'browser.js'), + mode: 'production', + // optimization: { + // minimize: false + // }, + output: { + filename: 'swarmjs.min.js', + globalObject: 'typeof self !== \'undefined\' ? self : this', + library: 'SwarmJS', + libraryTarget: 'umd', + libraryExport: 'default', + path: __dirname, + umdNamedDefine: true + }, + target: 'web', + node: { + fs: 'empty' + } }; -module.exports = [ - standalone -]; +module.exports = [standalone];