UI for Zipcoin Blue

http.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const tslib_1 = require("tslib");
  4. const util = require("util");
  5. const chalk_1 = require("chalk");
  6. const lodash = require("lodash");
  7. const guards_1 = require("../guards");
  8. const http_1 = require("./utils/http");
  9. const fs_1 = require("@ionic/cli-framework/utils/fs");
  10. const errors_1 = require("./errors");
  11. const FORMAT_ERROR_BODY_MAX_LENGTH = 1000;
  12. exports.CONTENT_TYPE_JSON = 'application/json';
  13. exports.ERROR_UNKNOWN_CONTENT_TYPE = 'UNKNOWN_CONTENT_TYPE';
  14. exports.ERROR_UNKNOWN_RESPONSE_FORMAT = 'UNKNOWN_RESPONSE_FORMAT';
  15. let CAS;
  16. let CERTS;
  17. let KEYS;
  18. function createRawRequest(method, url) {
  19. return tslib_1.__awaiter(this, void 0, void 0, function* () {
  20. const superagent = yield Promise.resolve().then(() => require('superagent'));
  21. const req = superagent(method, url);
  22. return { req };
  23. });
  24. }
  25. exports.createRawRequest = createRawRequest;
  26. class ResourceClient {
  27. applyModifiers(req, modifiers) {
  28. if (!modifiers) {
  29. return;
  30. }
  31. if (modifiers.fields) {
  32. req.query({ fields: modifiers.fields });
  33. }
  34. }
  35. applyAuthentication(req, token) {
  36. req.set('Authorization', `Bearer ${token}`);
  37. }
  38. }
  39. exports.ResourceClient = ResourceClient;
  40. function createRequest(config, method, url) {
  41. return tslib_1.__awaiter(this, void 0, void 0, function* () {
  42. const c = yield config.load();
  43. const [proxy,] = http_1.getGlobalProxy();
  44. const { req } = yield createRawRequest(method, url);
  45. if (proxy && req.proxy) {
  46. req.proxy(proxy);
  47. }
  48. if (c.ssl) {
  49. const conform = (p) => {
  50. if (!p) {
  51. return [];
  52. }
  53. if (typeof p === 'string') {
  54. return [p];
  55. }
  56. return p;
  57. };
  58. if (!CAS) {
  59. CAS = yield Promise.all(conform(c.ssl.cafile).map(p => fs_1.fsReadFile(p, { encoding: 'utf8' })));
  60. }
  61. if (!CERTS) {
  62. CERTS = yield Promise.all(conform(c.ssl.certfile).map(p => fs_1.fsReadFile(p, { encoding: 'utf8' })));
  63. }
  64. if (!KEYS) {
  65. KEYS = yield Promise.all(conform(c.ssl.keyfile).map(p => fs_1.fsReadFile(p, { encoding: 'utf8' })));
  66. }
  67. if (CAS.length > 0) {
  68. req.ca(CAS);
  69. }
  70. if (CERTS.length > 0) {
  71. req.cert(CERTS);
  72. }
  73. if (KEYS.length > 0) {
  74. req.key(KEYS);
  75. }
  76. }
  77. return { req };
  78. });
  79. }
  80. exports.createRequest = createRequest;
  81. function download(config, url, ws, opts) {
  82. return tslib_1.__awaiter(this, void 0, void 0, function* () {
  83. const { req } = yield createRequest(config, 'get', url);
  84. const progressFn = opts ? opts.progress : undefined;
  85. return new Promise((resolve, reject) => {
  86. req
  87. .on('response', res => {
  88. if (res.statusCode !== 200) {
  89. reject(new Error(`Encountered bad status code (${res.statusCode}) for ${url}\n` +
  90. `This could mean the server is experiencing difficulties right now--please try again later.`));
  91. }
  92. if (progressFn) {
  93. let loaded = 0;
  94. const total = Number(res.headers['content-length']);
  95. res.on('data', chunk => {
  96. loaded += chunk.length;
  97. progressFn(loaded, total);
  98. });
  99. }
  100. })
  101. .on('error', err => {
  102. if (err.code === 'ECONNABORTED') {
  103. reject(new Error(`Timeout of ${err.timeout}ms reached for ${url}`));
  104. }
  105. else {
  106. reject(err);
  107. }
  108. })
  109. .on('end', resolve);
  110. req.pipe(ws);
  111. });
  112. });
  113. }
  114. exports.download = download;
  115. class Client {
  116. constructor(config) {
  117. this.config = config;
  118. }
  119. make(method, path) {
  120. return tslib_1.__awaiter(this, void 0, void 0, function* () {
  121. const url = path.startsWith('http://') || path.startsWith('https://') ? path : `${yield this.config.getAPIUrl()}${path}`;
  122. const { req } = yield createRequest(this.config, method, url);
  123. req
  124. .set('Content-Type', exports.CONTENT_TYPE_JSON)
  125. .set('Accept', exports.CONTENT_TYPE_JSON);
  126. return { req };
  127. });
  128. }
  129. do(req) {
  130. return tslib_1.__awaiter(this, void 0, void 0, function* () {
  131. const res = yield req;
  132. const r = transformAPIResponse(res);
  133. if (guards_1.isAPIResponseError(r)) {
  134. throw new errors_1.FatalException('API request was successful, but the response output format was that of an error.\n'
  135. + formatAPIError(req, r));
  136. }
  137. return r;
  138. });
  139. }
  140. paginate(args) {
  141. return new Paginator(Object.assign({ client: this }, args));
  142. }
  143. }
  144. exports.Client = Client;
  145. class Paginator {
  146. constructor({ client, reqgen, guard, state, max }) {
  147. const defaultState = { page: 1, done: false, loaded: 0 };
  148. this.client = client;
  149. this.reqgen = reqgen;
  150. this.guard = guard;
  151. this.max = max;
  152. if (!state) {
  153. state = Object.assign({}, defaultState);
  154. }
  155. this.state = lodash.assign({}, state, defaultState);
  156. }
  157. next() {
  158. if (this.state.done) {
  159. return { done: true }; // TODO: why can't I exclude value?
  160. }
  161. return {
  162. done: false,
  163. value: (() => tslib_1.__awaiter(this, void 0, void 0, function* () {
  164. const { req } = yield this.reqgen();
  165. req.query(lodash.pick(this.state, ['page', 'page_size']));
  166. const res = yield this.client.do(req);
  167. if (!this.guard(res)) {
  168. throw createFatalAPIFormat(req, res);
  169. }
  170. this.state.loaded += res.data.length;
  171. if (res.data.length === 0 || // no resources in this page, we're done
  172. (typeof this.max === 'number' && this.state.loaded >= this.max) || // met or exceeded maximum requested
  173. (typeof this.state.page_size === 'number' && res.data.length < this.state.page_size) // number of resources less than page size, so nothing on next page
  174. ) {
  175. this.state.done = true;
  176. }
  177. this.state.page++;
  178. return res;
  179. }))(),
  180. };
  181. }
  182. [Symbol.iterator]() {
  183. return this;
  184. }
  185. }
  186. exports.Paginator = Paginator;
  187. class TokenPaginator {
  188. constructor({ client, reqgen, guard, state, max }) {
  189. const defaultState = { done: false, loaded: 0 };
  190. this.client = client;
  191. this.reqgen = reqgen;
  192. this.guard = guard;
  193. this.max = max;
  194. if (!state) {
  195. state = Object.assign({}, defaultState);
  196. }
  197. this.state = lodash.assign({}, state, defaultState);
  198. }
  199. next() {
  200. if (this.state.done) {
  201. return { done: true }; // TODO: why can't I exclude value?
  202. }
  203. return {
  204. done: false,
  205. value: (() => tslib_1.__awaiter(this, void 0, void 0, function* () {
  206. const { req } = yield this.reqgen();
  207. if (this.state.page_token) {
  208. req.query({ page_token: this.state.page_token });
  209. }
  210. const res = yield this.client.do(req);
  211. if (!this.isPageTokenResponseMeta(res.meta)) {
  212. throw createFatalAPIFormat(req, res);
  213. }
  214. const nextPageToken = res.meta.next_page_token;
  215. if (!this.guard(res)) {
  216. throw createFatalAPIFormat(req, res);
  217. }
  218. this.state.loaded += res.data.length;
  219. if (res.data.length === 0 || // no resources in this page, we're done
  220. (typeof this.max === 'number' && this.state.loaded >= this.max) || // met or exceeded maximum requested
  221. !nextPageToken // no next page token, must be done
  222. ) {
  223. this.state.done = true;
  224. }
  225. this.state.page_token = nextPageToken;
  226. return res;
  227. }))(),
  228. };
  229. }
  230. isPageTokenResponseMeta(m) {
  231. const meta = m;
  232. return meta
  233. && (!meta.prev_page_token || typeof meta.prev_page_token === 'string')
  234. && (!meta.next_page_token || typeof meta.next_page_token === 'string');
  235. }
  236. [Symbol.iterator]() {
  237. return this;
  238. }
  239. }
  240. exports.TokenPaginator = TokenPaginator;
  241. function transformAPIResponse(r) {
  242. if (r.status === 204) {
  243. r.body = { data: null, meta: { status: 204, version: '', request_id: '' } };
  244. }
  245. if (r.status !== 204 && r.type !== exports.CONTENT_TYPE_JSON) {
  246. throw exports.ERROR_UNKNOWN_CONTENT_TYPE;
  247. }
  248. let j = r.body;
  249. if (!j.meta) {
  250. throw exports.ERROR_UNKNOWN_RESPONSE_FORMAT;
  251. }
  252. return j;
  253. }
  254. exports.transformAPIResponse = transformAPIResponse;
  255. function createFatalAPIFormat(req, res) {
  256. return new errors_1.FatalException('API request was successful, but the response format was unrecognized.\n'
  257. + formatAPIResponse(req, res));
  258. }
  259. exports.createFatalAPIFormat = createFatalAPIFormat;
  260. function formatSuperAgentError(e) {
  261. const res = e.response;
  262. const req = res.request;
  263. const statusCode = e.response.status;
  264. let f = '';
  265. try {
  266. const r = transformAPIResponse(res);
  267. f += formatAPIResponse(req, r);
  268. }
  269. catch (e) {
  270. f += `HTTP Error ${statusCode}: ${req.method.toUpperCase()} ${req.url}\n`;
  271. // TODO: do this only if verbose?
  272. f += '\n' + (res.text ? res.text.substring(0, FORMAT_ERROR_BODY_MAX_LENGTH) : '<no buffered body>');
  273. if (res.text && res.text.length > FORMAT_ERROR_BODY_MAX_LENGTH) {
  274. f += ` ...\n\n[ truncated ${res.text.length - FORMAT_ERROR_BODY_MAX_LENGTH} characters ]`;
  275. }
  276. }
  277. return chalk_1.default.bold(chalk_1.default.red(f));
  278. }
  279. exports.formatSuperAgentError = formatSuperAgentError;
  280. function formatAPIResponse(req, r) {
  281. if (guards_1.isAPIResponseSuccess(r)) {
  282. return formatAPISuccess(req, r);
  283. }
  284. else {
  285. return formatAPIError(req, r);
  286. }
  287. }
  288. exports.formatAPIResponse = formatAPIResponse;
  289. function formatAPISuccess(req, r) {
  290. return `Request: ${req.method} ${req.url}\n`
  291. + `Response: ${r.meta.status}\n`
  292. + `Body: \n${util.inspect(r.data, { colors: chalk_1.default.enabled })}`;
  293. }
  294. exports.formatAPISuccess = formatAPISuccess;
  295. function formatAPIError(req, r) {
  296. return `Request: ${req.method} ${req.url}\n`
  297. + `Response: ${r.meta.status}\n`
  298. + `Body: \n${util.inspect(r.error, { colors: chalk_1.default.enabled })}`;
  299. }
  300. exports.formatAPIError = formatAPIError;