@globalfishingwatch/api-client
Advanced tools
Comparing version 1.0.2 to 1.1.0
@@ -1,430 +0,16 @@ | ||
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var file_saver_1 = require("file-saver"); | ||
var url_1 = require("./utils/url"); | ||
var API_GATEWAY = process.env.API_GATEWAY || | ||
process.env.REACT_APP_API_GATEWAY || | ||
'https://gateway.api.dev.globalfishingwatch.org'; | ||
exports.USER_TOKEN_STORAGE_KEY = 'GFW_API_USER_TOKEN'; | ||
exports.USER_REFRESH_TOKEN_STORAGE_KEY = 'GFW_API_USER_REFRESH_TOKEN'; | ||
var AUTH_PATH = 'auth'; | ||
var processStatus = function (response) { | ||
return response.status >= 200 && response.status < 300 | ||
? Promise.resolve(response) | ||
: Promise.reject({ status: response.status, message: response.statusText }); | ||
}; | ||
var parseJSON = function (response) { return response.json(); }; | ||
var isUnauthorizedError = function (error) { | ||
return error && error.status > 400 && error.status < 403; | ||
}; | ||
var GFWAPI = /** @class */ (function () { | ||
function GFWAPI(_a) { | ||
var _b = _a === void 0 ? {} : _a, _c = _b.debug, debug = _c === void 0 ? false : _c, _d = _b.baseUrl, baseUrl = _d === void 0 ? API_GATEWAY : _d, _e = _b.tokenStorageKey, tokenStorageKey = _e === void 0 ? exports.USER_TOKEN_STORAGE_KEY : _e, _f = _b.refreshTokenStorageKey, refreshTokenStorageKey = _f === void 0 ? exports.USER_REFRESH_TOKEN_STORAGE_KEY : _f; | ||
this.token = ''; | ||
this.refreshToken = ''; | ||
this.dataset = ''; | ||
this.maxRefreshRetries = 1; | ||
this.debug = debug; | ||
this.baseUrl = baseUrl; | ||
this.storageKeys = { token: tokenStorageKey, refreshToken: refreshTokenStorageKey }; | ||
this.setToken(localStorage.getItem(tokenStorageKey) || ''); | ||
this.setRefreshToken(localStorage.getItem(refreshTokenStorageKey) || ''); | ||
this.logging = null; | ||
if (debug) { | ||
console.log('GFWAPI: GFW API Client initialized with the following config', this.getConfig()); | ||
} | ||
} | ||
GFWAPI.prototype.getBaseUrl = function () { | ||
return this.baseUrl; | ||
}; | ||
GFWAPI.prototype.getLoginUrl = function (callbackUrl, client) { | ||
if (client === void 0) { client = 'gfw'; } | ||
return this.baseUrl + "/" + AUTH_PATH + "?client=" + client + "&callback=" + callbackUrl; | ||
}; | ||
GFWAPI.prototype.getConfig = function () { | ||
return { | ||
debug: this.debug, | ||
baseUrl: this.baseUrl, | ||
storageKeys: this.storageKeys, | ||
token: this.getToken(), | ||
refreshToken: this.getRefreshToken(), | ||
}; | ||
}; | ||
GFWAPI.prototype.setConfig = function (config) { | ||
var _a = config.debug, debug = _a === void 0 ? this.debug : _a, _b = config.baseUrl, baseUrl = _b === void 0 ? this.baseUrl : _b, _c = config.dataset, dataset = _c === void 0 ? this.dataset : _c; | ||
this.debug = debug; | ||
this.baseUrl = baseUrl; | ||
this.dataset = dataset; | ||
}; | ||
GFWAPI.prototype.getToken = function () { | ||
return this.token; | ||
}; | ||
GFWAPI.prototype.setToken = function (token) { | ||
this.token = token; | ||
if (token) { | ||
localStorage.setItem(this.storageKeys.token, token); | ||
} | ||
else { | ||
localStorage.removeItem(this.storageKeys.token); | ||
} | ||
if (this.debug) { | ||
console.log('GFWAPI: updated token with', token); | ||
} | ||
}; | ||
GFWAPI.prototype.getRefreshToken = function () { | ||
return this.refreshToken; | ||
}; | ||
GFWAPI.prototype.setRefreshToken = function (refreshToken) { | ||
this.refreshToken = refreshToken; | ||
if (refreshToken) { | ||
localStorage.setItem(this.storageKeys.refreshToken, refreshToken); | ||
} | ||
else { | ||
localStorage.removeItem(this.storageKeys.refreshToken); | ||
} | ||
if (this.debug) { | ||
console.log('GFWAPI: updated refreshToken with', refreshToken); | ||
} | ||
}; | ||
GFWAPI.prototype.getTokensWithAccessToken = function (accessToken) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, fetch(this.baseUrl + "/" + AUTH_PATH + "/token?access-token=" + accessToken) | ||
.then(processStatus) | ||
.then(parseJSON)]; | ||
}); | ||
}); | ||
}; | ||
GFWAPI.prototype.getTokenWithRefreshToken = function (refreshToken) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, fetch(this.baseUrl + "/" + AUTH_PATH + "/token/reload", { | ||
headers: { | ||
'refresh-token': refreshToken, | ||
}, | ||
}) | ||
.then(processStatus) | ||
.then(parseJSON)]; | ||
}); | ||
}); | ||
}; | ||
GFWAPI.prototype.fetch = function (url, options) { | ||
if (options === void 0) { options = {}; } | ||
return this._internalFetch(url, options); | ||
}; | ||
GFWAPI.prototype.download = function (downloadUrl, fileName) { | ||
if (fileName === void 0) { fileName = 'download'; } | ||
return this._internalFetch(downloadUrl, { json: false }) | ||
.then(function (res) { return res.blob(); }) | ||
.then(function (blob) { | ||
file_saver_1.saveAs(blob, fileName); | ||
return true; | ||
}) | ||
.catch(function (e) { | ||
return false; | ||
}); | ||
}; | ||
GFWAPI.prototype._internalFetch = function (url, options, refreshRetries, waitLogin) { | ||
if (options === void 0) { options = {}; } | ||
if (refreshRetries === void 0) { refreshRetries = 0; } | ||
if (waitLogin === void 0) { waitLogin = true; } | ||
return __awaiter(this, void 0, void 0, function () { | ||
var e_1, _a, method, _b, body, _c, headers, _d, json_1, signal, _e, dataset, prefix, fetchUrl, data, e_2, token, e_3, e_4; | ||
return __generator(this, function (_f) { | ||
switch (_f.label) { | ||
case 0: | ||
_f.trys.push([0, 14, , 15]); | ||
if (!(this.logging && waitLogin)) return [3 /*break*/, 4]; | ||
_f.label = 1; | ||
case 1: | ||
_f.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, this.logging]; | ||
case 2: | ||
_f.sent(); | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
e_1 = _f.sent(); | ||
if (this.debug) { | ||
console.log("Fetch resource executed without login headers in url: " + url); | ||
} | ||
return [3 /*break*/, 4]; | ||
case 4: | ||
_f.trys.push([4, 6, , 13]); | ||
_a = options.method, method = _a === void 0 ? 'GET' : _a, _b = options.body, body = _b === void 0 ? null : _b, _c = options.headers, headers = _c === void 0 ? {} : _c, _d = options.json, json_1 = _d === void 0 ? true : _d, signal = options.signal, _e = options.dataset, dataset = _e === void 0 ? this.dataset : _e; | ||
if (this.debug) { | ||
console.log("GFWAPI: Fetching url: " + url); | ||
} | ||
prefix = "" + (url_1.isUrlAbsolute(url) ? '' : this.baseUrl); | ||
fetchUrl = prefix + (dataset ? "/datasets/" + this.dataset : '') + url; | ||
return [4 /*yield*/, fetch(fetchUrl, __assign(__assign({ method: method, | ||
signal: signal }, (body && { body: JSON.stringify(body) })), { headers: __assign(__assign({}, headers), { Authorization: "Bearer " + this.getToken() }) })) | ||
.then(processStatus) | ||
.then(function (res) { return (json_1 ? parseJSON(res) : res); })]; | ||
case 5: | ||
data = _f.sent(); | ||
return [2 /*return*/, data]; | ||
case 6: | ||
e_2 = _f.sent(); | ||
if (!(refreshRetries <= this.maxRefreshRetries)) return [3 /*break*/, 11]; | ||
if (!(e_2.status === 401 || e_2.status === 403)) return [3 /*break*/, 10]; | ||
if (this.debug) { | ||
console.log("GFWAPI: Trying to refresh the token attempt: " + refreshRetries); | ||
} | ||
_f.label = 7; | ||
case 7: | ||
_f.trys.push([7, 9, , 10]); | ||
return [4 /*yield*/, this.getTokenWithRefreshToken(this.getRefreshToken())]; | ||
case 8: | ||
token = (_f.sent()).token; | ||
this.setToken(token); | ||
if (this.debug) { | ||
console.log("GFWAPI: Token refresh worked! trying to fetch again " + url); | ||
} | ||
return [3 /*break*/, 10]; | ||
case 9: | ||
e_3 = _f.sent(); | ||
if (this.debug) { | ||
console.warn("GFWAPI: Error fetching " + url, e_3); | ||
} | ||
localStorage.removeItem(this.storageKeys.token); | ||
localStorage.removeItem(this.storageKeys.refreshToken); | ||
e_3.refreshError = true; | ||
throw e_3; | ||
case 10: return [2 /*return*/, this._internalFetch(url, options, ++refreshRetries, waitLogin)]; | ||
case 11: | ||
if (this.debug) { | ||
if (refreshRetries >= this.maxRefreshRetries) { | ||
console.log("GFWAPI: Attemps to retry the request excedeed"); | ||
} | ||
console.warn("GFWAPI: Error fetching " + url, e_2); | ||
} | ||
throw e_2; | ||
case 12: return [3 /*break*/, 13]; | ||
case 13: return [3 /*break*/, 15]; | ||
case 14: | ||
e_4 = _f.sent(); | ||
if (this.debug) { | ||
console.warn("GFWAPI: Error fetching " + url, e_4); | ||
} | ||
throw e_4; | ||
case 15: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
GFWAPI.prototype.fetchUser = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var user, e_5; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
_a.trys.push([0, 2, , 3]); | ||
return [4 /*yield*/, this._internalFetch("/" + AUTH_PATH + "/me", { dataset: false }, 0, false)]; | ||
case 1: | ||
user = _a.sent(); | ||
return [2 /*return*/, user]; | ||
case 2: | ||
e_5 = _a.sent(); | ||
console.warn(e_5); | ||
throw new Error('Error trying to get user data'); | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
GFWAPI.prototype.login = function (params) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var _a, accessToken, _b, refreshToken; | ||
var _this = this; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
_a = params.accessToken, accessToken = _a === void 0 ? null : _a, _b = params.refreshToken, refreshToken = _b === void 0 ? this.getRefreshToken() : _b; | ||
this.logging = new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { | ||
var tokens, e_6, msg, user, e_7, token, user, e_8, msg; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!accessToken) return [3 /*break*/, 4]; | ||
if (this.debug) { | ||
console.log("GFWAPI: Trying to get tokens using access-token"); | ||
} | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, this.getTokensWithAccessToken(accessToken)]; | ||
case 2: | ||
tokens = _a.sent(); | ||
this.setToken(tokens.token); | ||
this.setRefreshToken(tokens.refreshToken); | ||
if (this.debug) { | ||
console.log("GFWAPI: access-token valid, tokens ready"); | ||
} | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
e_6 = _a.sent(); | ||
if (!this.getToken() && !this.getRefreshToken()) { | ||
msg = isUnauthorizedError(e_6) | ||
? 'Invalid access token' | ||
: 'Error trying to generate tokens'; | ||
if (this.debug) { | ||
console.warn("GFWAPI: " + msg); | ||
} | ||
reject(new Error(msg)); | ||
return [2 /*return*/, null]; | ||
} | ||
return [3 /*break*/, 4]; | ||
case 4: | ||
if (!this.getToken()) return [3 /*break*/, 8]; | ||
if (this.debug) { | ||
console.log("GFWAPI: Trying to get user with current token"); | ||
} | ||
_a.label = 5; | ||
case 5: | ||
_a.trys.push([5, 7, , 8]); | ||
return [4 /*yield*/, this.fetchUser()]; | ||
case 6: | ||
user = _a.sent(); | ||
if (this.debug) { | ||
console.log("GFWAPI: Token valid, user data ready:", user); | ||
} | ||
resolve(user); | ||
return [2 /*return*/, user]; | ||
case 7: | ||
e_7 = _a.sent(); | ||
if (this.debug) { | ||
console.warn('GFWAPI: Token expired, trying to refresh', e_7); | ||
} | ||
return [3 /*break*/, 8]; | ||
case 8: | ||
if (!refreshToken) return [3 /*break*/, 13]; | ||
if (this.debug) { | ||
console.log("GFWAPI: Token wasn't valid, trying to refresh"); | ||
} | ||
_a.label = 9; | ||
case 9: | ||
_a.trys.push([9, 12, , 13]); | ||
return [4 /*yield*/, this.getTokenWithRefreshToken(refreshToken)]; | ||
case 10: | ||
token = (_a.sent()).token; | ||
this.setToken(token); | ||
if (this.debug) { | ||
console.log("GFWAPI: Refresh token OK, fetching user"); | ||
} | ||
return [4 /*yield*/, this.fetchUser()]; | ||
case 11: | ||
user = _a.sent(); | ||
if (this.debug) { | ||
console.log("GFWAPI: Login finished, user data ready:", user); | ||
} | ||
resolve(user); | ||
return [2 /*return*/, user]; | ||
case 12: | ||
e_8 = _a.sent(); | ||
msg = isUnauthorizedError(e_8) | ||
? 'Invalid refresh token' | ||
: 'Error trying to refreshing the token'; | ||
console.warn(e_8); | ||
if (this.debug) { | ||
console.warn("GFWAPI: " + msg); | ||
} | ||
reject(new Error(msg)); | ||
return [2 /*return*/, null]; | ||
case 13: | ||
reject(new Error('No login token provided')); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
return [4 /*yield*/, this.logging]; | ||
case 1: return [2 /*return*/, _c.sent()]; | ||
} | ||
}); | ||
}); | ||
}; | ||
GFWAPI.prototype.logout = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var e_9; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
_a.trys.push([0, 2, , 3]); | ||
if (this.debug) { | ||
console.log("GFWAPI: Logout - tokens cleaned"); | ||
} | ||
return [4 /*yield*/, fetch(this.baseUrl + "/" + AUTH_PATH + "/logout", { | ||
headers: { | ||
'refresh-token': this.refreshToken, | ||
}, | ||
}).then(processStatus)]; | ||
case 1: | ||
_a.sent(); | ||
this.setToken(''); | ||
this.setRefreshToken(''); | ||
if (this.debug) { | ||
console.log("GFWAPI: Logout invalid session api OK"); | ||
} | ||
return [2 /*return*/, true]; | ||
case 2: | ||
e_9 = _a.sent(); | ||
if (this.debug) { | ||
console.warn("GFWAPI: Logout invalid session fail"); | ||
} | ||
throw new Error('Error on the logout proccess'); | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
return GFWAPI; | ||
}()); | ||
exports.GFWAPI = GFWAPI; | ||
exports.default = new GFWAPI(); | ||
//# sourceMappingURL=api-client.js.map | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
var e=function(){return(e=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};function t(e,t,n,o){return new(n||(n=Promise))((function(r,s){function i(e){try{u(o.next(e))}catch(e){s(e)}}function a(e){try{u(o.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((o=o.apply(e,t||[])).next())}))}function n(e,t){var n,o,r,s,i={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,o&&(r=2&s[0]?o.return:s[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,s[1])).done)return r;switch(o=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,o=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(r=i.trys,(r=r.length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){i.label=s[1];break}if(6===s[0]&&i.label<r[1]){i.label=r[1],r=s;break}if(r&&i.label<r[2]){i.label=r[2],i.ops.push(s);break}r[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],o=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}}var o="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var r=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e,t){!function(){function t(e,t,n){var o=new XMLHttpRequest;o.open("GET",e),o.responseType="blob",o.onload=function(){i(o.response,t,n)},o.onerror=function(){console.error("could not download file")},o.send()}function n(e){var t=new XMLHttpRequest;t.open("HEAD",e,!1);try{t.send()}catch(e){}return 200<=t.status&&299>=t.status}function r(e){try{e.dispatchEvent(new MouseEvent("click"))}catch(n){var t=document.createEvent("MouseEvents");t.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),e.dispatchEvent(t)}}var s="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof o&&o.global===o?o:void 0,i=s.saveAs||("object"!=typeof window||window!==s?function(){}:"download"in HTMLAnchorElement.prototype?function(e,o,i){var a=s.URL||s.webkitURL,u=document.createElement("a");o=o||e.name||"download",u.download=o,u.rel="noopener","string"==typeof e?(u.href=e,u.origin===location.origin?r(u):n(u.href)?t(e,o,i):r(u,u.target="_blank")):(u.href=a.createObjectURL(e),setTimeout((function(){a.revokeObjectURL(u.href)}),4e4),setTimeout((function(){r(u)}),0))}:"msSaveOrOpenBlob"in navigator?function(e,o,s){if(o=o||e.name||"download","string"!=typeof e)navigator.msSaveOrOpenBlob(function(e,t){return void 0===t?t={autoBom:!1}:"object"!=typeof t&&(console.warn("Deprecated: Expected third argument to be a object"),t={autoBom:!t}),t.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob(["\ufeff",e],{type:e.type}):e}(e,s),o);else if(n(e))t(e,o,s);else{var i=document.createElement("a");i.href=e,i.target="_blank",setTimeout((function(){r(i)}))}}:function(e,n,o,r){if((r=r||open("","_blank"))&&(r.document.title=r.document.body.innerText="downloading..."),"string"==typeof e)return t(e,n,o);var i="application/octet-stream"===e.type,a=/constructor/i.test(s.HTMLElement)||s.safari,u=/CriOS\/[\d]+/.test(navigator.userAgent);if((u||i&&a)&&"object"==typeof FileReader){var c=new FileReader;c.onloadend=function(){var e=c.result;e=u?e:e.replace(/^data:[^;]*;/,"data:attachment/file;"),r?r.location.href=e:location=e,r=null},c.readAsDataURL(e)}else{var h=s.URL||s.webkitURL,l=h.createObjectURL(e);r?r.location=l:location.href=l,r=null,setTimeout((function(){h.revokeObjectURL(l)}),4e4)}});s.saveAs=i.saveAs=i,e.exports=i}()})).saveAs;var s=process.env.API_GATEWAY||process.env.REACT_APP_API_GATEWAY||"https://gateway.api.dev.globalfishingwatch.org",i="GFW_API_USER_TOKEN",a="GFW_API_USER_REFRESH_TOKEN",u=function(e){return e.status>=200&&e.status<300?Promise.resolve(e):Promise.reject({status:e.status,message:e.statusText})},c=function(e){return e.json()},h=function(e){return e&&e.status>400&&e.status<403},l=function(){function o(e){var t=void 0===e?{}:e,n=t.debug,o=void 0!==n&&n,r=t.baseUrl,i=void 0===r?s:r,a=t.tokenStorageKey,u=void 0===a?"GFW_API_USER_TOKEN":a,c=t.refreshTokenStorageKey,h=void 0===c?"GFW_API_USER_REFRESH_TOKEN":c;this.token="",this.refreshToken="",this.dataset="",this.maxRefreshRetries=1,this.debug=o,this.baseUrl=i,this.storageKeys={token:u,refreshToken:h},this.setToken(localStorage.getItem(u)||""),this.setRefreshToken(localStorage.getItem(h)||""),this.logging=null,o&&console.log("GFWAPI: GFW API Client initialized with the following config",this.getConfig())}return o.prototype.getBaseUrl=function(){return this.baseUrl},o.prototype.getLoginUrl=function(e,t){return void 0===t&&(t="gfw"),this.baseUrl+"/auth?client="+t+"&callback="+e},o.prototype.getConfig=function(){return{debug:this.debug,baseUrl:this.baseUrl,storageKeys:this.storageKeys,token:this.getToken(),refreshToken:this.getRefreshToken()}},o.prototype.setConfig=function(e){var t=e.debug,n=void 0===t?this.debug:t,o=e.baseUrl,r=void 0===o?this.baseUrl:o,s=e.dataset,i=void 0===s?this.dataset:s;this.debug=n,this.baseUrl=r,this.dataset=i},o.prototype.getToken=function(){return this.token},o.prototype.setToken=function(e){this.token=e,e?localStorage.setItem(this.storageKeys.token,e):localStorage.removeItem(this.storageKeys.token),this.debug&&console.log("GFWAPI: updated token with",e)},o.prototype.getRefreshToken=function(){return this.refreshToken},o.prototype.setRefreshToken=function(e){this.refreshToken=e,e?localStorage.setItem(this.storageKeys.refreshToken,e):localStorage.removeItem(this.storageKeys.refreshToken),this.debug&&console.log("GFWAPI: updated refreshToken with",e)},o.prototype.getTokensWithAccessToken=function(e){return t(this,void 0,void 0,(function(){return n(this,(function(t){return[2,fetch(this.baseUrl+"/auth/token?access-token="+e).then(u).then(c)]}))}))},o.prototype.getTokenWithRefreshToken=function(e){return t(this,void 0,void 0,(function(){return n(this,(function(t){return[2,fetch(this.baseUrl+"/auth/token/reload",{headers:{"refresh-token":e}}).then(u).then(c)]}))}))},o.prototype.fetch=function(e,t){return void 0===t&&(t={}),this._internalFetch(e,t)},o.prototype.download=function(e,t){return void 0===t&&(t="download"),this._internalFetch(e,{json:!1}).then((function(e){return e.blob()})).then((function(e){return r(e,t),!0})).catch((function(e){return!1}))},o.prototype._internalFetch=function(o,r,s,i){return void 0===r&&(r={}),void 0===s&&(s=0),void 0===i&&(i=!0),t(this,void 0,void 0,(function(){var t,a,h,l,f,d,g,p,b,v,k,y,w,T,m,A,E;return n(this,(function(n){switch(n.label){case 0:if(n.trys.push([0,14,,15]),!this.logging||!i)return[3,4];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.logging];case 2:return n.sent(),[3,4];case 3:return n.sent(),this.debug&&console.log("Fetch resource executed without login headers in url: "+o),[3,4];case 4:return n.trys.push([4,6,,13]),t=r.method,a=void 0===t?"GET":t,h=r.body,l=void 0===h?null:h,f=r.headers,d=void 0===f?{}:f,g=r.json,p=void 0===g||g,b=r.signal,v=r.dataset,k=void 0===v?this.dataset:v,this.debug&&console.log("GFWAPI: Fetching url: "+o),y=""+(function(e){if(!e)throw new Error("Url absolute check needs a proper url");return 0===e.indexOf("//")||-1!==e.indexOf("://")&&(-1!==e.indexOf(".")&&(-1!==e.indexOf("/")&&(!(e.indexOf(":")>e.indexOf("/"))&&e.indexOf("://")<e.indexOf("."))))}(o)?"":this.baseUrl),w=y+(k?"/datasets/"+this.dataset:"")+o,[4,fetch(w,e(e({method:a,signal:b},l&&{body:JSON.stringify(l)}),{headers:e(e({},d),{Authorization:"Bearer "+this.getToken()})})).then(u).then((function(e){return p?c(e):e}))];case 5:return[2,n.sent()];case 6:if(T=n.sent(),!(s<=this.maxRefreshRetries))return[3,11];if(401!==T.status&&403!==T.status)return[3,10];this.debug&&console.log("GFWAPI: Trying to refresh the token attempt: "+s),n.label=7;case 7:return n.trys.push([7,9,,10]),[4,this.getTokenWithRefreshToken(this.getRefreshToken())];case 8:return m=n.sent().token,this.setToken(m),this.debug&&console.log("GFWAPI: Token refresh worked! trying to fetch again "+o),[3,10];case 9:throw A=n.sent(),this.debug&&console.warn("GFWAPI: Error fetching "+o,A),localStorage.removeItem(this.storageKeys.token),localStorage.removeItem(this.storageKeys.refreshToken),A.refreshError=!0,A;case 10:return[2,this._internalFetch(o,r,++s,i)];case 11:throw this.debug&&(s>=this.maxRefreshRetries&&console.log("GFWAPI: Attemps to retry the request excedeed"),console.warn("GFWAPI: Error fetching "+o,T)),T;case 12:return[3,13];case 13:return[3,15];case 14:throw E=n.sent(),this.debug&&console.warn("GFWAPI: Error fetching "+o,E),E;case 15:return[2]}}))}))},o.prototype.fetchUser=function(){return t(this,void 0,void 0,(function(){var e;return n(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this._internalFetch("/auth/me",{dataset:!1},0,!1)];case 1:return[2,t.sent()];case 2:throw e=t.sent(),console.warn(e),new Error("Error trying to get user data");case 3:return[2]}}))}))},o.prototype.login=function(e){return t(this,void 0,void 0,(function(){var o,r,s,i,a=this;return n(this,(function(u){switch(u.label){case 0:return o=e.accessToken,r=void 0===o?null:o,s=e.refreshToken,i=void 0===s?this.getRefreshToken():s,this.logging=new Promise((function(e,o){return t(a,void 0,void 0,(function(){var t,s,a,u,c,l,f;return n(this,(function(n){switch(n.label){case 0:if(!r)return[3,4];this.debug&&console.log("GFWAPI: Trying to get tokens using access-token"),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.getTokensWithAccessToken(r)];case 2:return t=n.sent(),this.setToken(t.token),this.setRefreshToken(t.refreshToken),this.debug&&console.log("GFWAPI: access-token valid, tokens ready"),[3,4];case 3:return s=n.sent(),this.getToken()||this.getRefreshToken()?[3,4]:(f=h(s)?"Invalid access token":"Error trying to generate tokens",this.debug&&console.warn("GFWAPI: "+f),o(new Error(f)),[2,null]);case 4:if(!this.getToken())return[3,8];this.debug&&console.log("GFWAPI: Trying to get user with current token"),n.label=5;case 5:return n.trys.push([5,7,,8]),[4,this.fetchUser()];case 6:return c=n.sent(),this.debug&&console.log("GFWAPI: Token valid, user data ready:",c),e(c),[2,c];case 7:return a=n.sent(),this.debug&&console.warn("GFWAPI: Token expired, trying to refresh",a),[3,8];case 8:if(!i)return[3,13];this.debug&&console.log("GFWAPI: Token wasn't valid, trying to refresh"),n.label=9;case 9:return n.trys.push([9,12,,13]),[4,this.getTokenWithRefreshToken(i)];case 10:return u=n.sent().token,this.setToken(u),this.debug&&console.log("GFWAPI: Refresh token OK, fetching user"),[4,this.fetchUser()];case 11:return c=n.sent(),this.debug&&console.log("GFWAPI: Login finished, user data ready:",c),e(c),[2,c];case 12:return l=n.sent(),f=h(l)?"Invalid refresh token":"Error trying to refreshing the token",console.warn(l),this.debug&&console.warn("GFWAPI: "+f),o(new Error(f)),[2,null];case 13:return o(new Error("No login token provided")),[2]}}))}))})),[4,this.logging];case 1:return[2,u.sent()]}}))}))},o.prototype.logout=function(){return t(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),this.debug&&console.log("GFWAPI: Logout - tokens cleaned"),[4,fetch(this.baseUrl+"/auth/logout",{headers:{"refresh-token":this.refreshToken}}).then(u)];case 1:return e.sent(),this.setToken(""),this.setRefreshToken(""),this.debug&&console.log("GFWAPI: Logout invalid session api OK"),[2,!0];case 2:throw e.sent(),this.debug&&console.warn("GFWAPI: Logout invalid session fail"),new Error("Error on the logout proccess");case 3:return[2]}}))}))},o}(),f=new l;export default f;export{l as GFWAPI,a as USER_REFRESH_TOKEN_STORAGE_KEY,i as USER_TOKEN_STORAGE_KEY}; | ||
//# sourceMappingURL=api-client.js.map |
@@ -1,483 +0,2 @@ | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
var __assign = function() { | ||
__assign = Object.assign || function __assign(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
function __generator(thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
} | ||
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; | ||
function createCommonjsModule(fn, module) { | ||
return module = { exports: {} }, fn(module, module.exports), module.exports; | ||
} | ||
var FileSaver_min = createCommonjsModule(function (module, exports) { | ||
(function(a,b){b();})(commonjsGlobal,function(){function b(a,b){return "undefined"==typeof b?b={autoBom:!1}:"object"!=typeof b&&(console.warn("Deprecated: Expected third argument to be a object"),b={autoBom:!b}),b.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a}function c(b,c,d){var e=new XMLHttpRequest;e.open("GET",b),e.responseType="blob",e.onload=function(){a(e.response,c,d);},e.onerror=function(){console.error("could not download file");},e.send();}function d(a){var b=new XMLHttpRequest;b.open("HEAD",a,!1);try{b.send();}catch(a){}return 200<=b.status&&299>=b.status}function e(a){try{a.dispatchEvent(new MouseEvent("click"));}catch(c){var b=document.createEvent("MouseEvents");b.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),a.dispatchEvent(b);}}var f="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof commonjsGlobal&&commonjsGlobal.global===commonjsGlobal?commonjsGlobal:void 0,a=f.saveAs||("object"!=typeof window||window!==f?function(){}:"download"in HTMLAnchorElement.prototype?function(b,g,h){var i=f.URL||f.webkitURL,j=document.createElement("a");g=g||b.name||"download",j.download=g,j.rel="noopener","string"==typeof b?(j.href=b,j.origin===location.origin?e(j):d(j.href)?c(b,g,h):e(j,j.target="_blank")):(j.href=i.createObjectURL(b),setTimeout(function(){i.revokeObjectURL(j.href);},4E4),setTimeout(function(){e(j);},0));}:"msSaveOrOpenBlob"in navigator?function(f,g,h){if(g=g||f.name||"download","string"!=typeof f)navigator.msSaveOrOpenBlob(b(f,h),g);else if(d(f))c(f,g,h);else {var i=document.createElement("a");i.href=f,i.target="_blank",setTimeout(function(){e(i);});}}:function(a,b,d,e){if(e=e||open("","_blank"),e&&(e.document.title=e.document.body.innerText="downloading..."),"string"==typeof a)return c(a,b,d);var g="application/octet-stream"===a.type,h=/constructor/i.test(f.HTMLElement)||f.safari,i=/CriOS\/[\d]+/.test(navigator.userAgent);if((i||g&&h)&&"object"==typeof FileReader){var j=new FileReader;j.onloadend=function(){var a=j.result;a=i?a:a.replace(/^data:[^;]*;/,"data:attachment/file;"),e?e.location.href=a:location=a,e=null;},j.readAsDataURL(a);}else {var k=f.URL||f.webkitURL,l=k.createObjectURL(a);e?e.location=l:location.href=l,e=null,setTimeout(function(){k.revokeObjectURL(l);},4E4);}});f.saveAs=a.saveAs=a,(module.exports=a);}); | ||
}); | ||
var FileSaver_min_1 = FileSaver_min.saveAs; | ||
function isUrlAbsolute(url) { | ||
if (!url) { | ||
throw new Error('Url absolute check needs a proper url'); | ||
} | ||
if (url.indexOf('//') === 0) { | ||
return true; | ||
} // URL is protocol-relative (= absolute) | ||
if (url.indexOf('://') === -1) { | ||
return false; | ||
} // URL has no protocol (= relative) | ||
if (url.indexOf('.') === -1) { | ||
return false; | ||
} // URL does not contain a dot, i.e. no TLD (= relative, possibly REST) | ||
if (url.indexOf('/') === -1) { | ||
return false; | ||
} // URL does not contain a single slash (= relative) | ||
if (url.indexOf(':') > url.indexOf('/')) { | ||
return false; | ||
} // The first colon comes after the first slash (= relative) | ||
if (url.indexOf('://') < url.indexOf('.')) { | ||
return true; | ||
} // Protocol is defined before first dot (= absolute) | ||
return false; // Anything else must be relative | ||
} | ||
var API_GATEWAY = process.env.API_GATEWAY || | ||
process.env.REACT_APP_API_GATEWAY || | ||
'https://gateway.api.dev.globalfishingwatch.org'; | ||
var USER_TOKEN_STORAGE_KEY = 'GFW_API_USER_TOKEN'; | ||
var USER_REFRESH_TOKEN_STORAGE_KEY = 'GFW_API_USER_REFRESH_TOKEN'; | ||
var AUTH_PATH = 'auth'; | ||
var processStatus = function (response) { | ||
return response.status >= 200 && response.status < 300 | ||
? Promise.resolve(response) | ||
: Promise.reject({ status: response.status, message: response.statusText }); | ||
}; | ||
var parseJSON = function (response) { return response.json(); }; | ||
var isUnauthorizedError = function (error) { | ||
return error && error.status > 400 && error.status < 403; | ||
}; | ||
var GFWAPI = /** @class */ (function () { | ||
function GFWAPI(_a) { | ||
var _b = _a === void 0 ? {} : _a, _c = _b.debug, debug = _c === void 0 ? false : _c, _d = _b.baseUrl, baseUrl = _d === void 0 ? API_GATEWAY : _d, _e = _b.tokenStorageKey, tokenStorageKey = _e === void 0 ? USER_TOKEN_STORAGE_KEY : _e, _f = _b.refreshTokenStorageKey, refreshTokenStorageKey = _f === void 0 ? USER_REFRESH_TOKEN_STORAGE_KEY : _f; | ||
this.token = ''; | ||
this.refreshToken = ''; | ||
this.dataset = ''; | ||
this.maxRefreshRetries = 1; | ||
this.debug = debug; | ||
this.baseUrl = baseUrl; | ||
this.storageKeys = { token: tokenStorageKey, refreshToken: refreshTokenStorageKey }; | ||
this.setToken(localStorage.getItem(tokenStorageKey) || ''); | ||
this.setRefreshToken(localStorage.getItem(refreshTokenStorageKey) || ''); | ||
this.logging = null; | ||
if (debug) { | ||
console.log('GFWAPI: GFW API Client initialized with the following config', this.getConfig()); | ||
} | ||
} | ||
GFWAPI.prototype.getBaseUrl = function () { | ||
return this.baseUrl; | ||
}; | ||
GFWAPI.prototype.getLoginUrl = function (callbackUrl, client) { | ||
if (client === void 0) { client = 'gfw'; } | ||
return this.baseUrl + "/" + AUTH_PATH + "?client=" + client + "&callback=" + callbackUrl; | ||
}; | ||
GFWAPI.prototype.getConfig = function () { | ||
return { | ||
debug: this.debug, | ||
baseUrl: this.baseUrl, | ||
storageKeys: this.storageKeys, | ||
token: this.getToken(), | ||
refreshToken: this.getRefreshToken(), | ||
}; | ||
}; | ||
GFWAPI.prototype.setConfig = function (config) { | ||
var _a = config.debug, debug = _a === void 0 ? this.debug : _a, _b = config.baseUrl, baseUrl = _b === void 0 ? this.baseUrl : _b, _c = config.dataset, dataset = _c === void 0 ? this.dataset : _c; | ||
this.debug = debug; | ||
this.baseUrl = baseUrl; | ||
this.dataset = dataset; | ||
}; | ||
GFWAPI.prototype.getToken = function () { | ||
return this.token; | ||
}; | ||
GFWAPI.prototype.setToken = function (token) { | ||
this.token = token; | ||
if (token) { | ||
localStorage.setItem(this.storageKeys.token, token); | ||
} | ||
else { | ||
localStorage.removeItem(this.storageKeys.token); | ||
} | ||
if (this.debug) { | ||
console.log('GFWAPI: updated token with', token); | ||
} | ||
}; | ||
GFWAPI.prototype.getRefreshToken = function () { | ||
return this.refreshToken; | ||
}; | ||
GFWAPI.prototype.setRefreshToken = function (refreshToken) { | ||
this.refreshToken = refreshToken; | ||
if (refreshToken) { | ||
localStorage.setItem(this.storageKeys.refreshToken, refreshToken); | ||
} | ||
else { | ||
localStorage.removeItem(this.storageKeys.refreshToken); | ||
} | ||
if (this.debug) { | ||
console.log('GFWAPI: updated refreshToken with', refreshToken); | ||
} | ||
}; | ||
GFWAPI.prototype.getTokensWithAccessToken = function (accessToken) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, fetch(this.baseUrl + "/" + AUTH_PATH + "/token?access-token=" + accessToken) | ||
.then(processStatus) | ||
.then(parseJSON)]; | ||
}); | ||
}); | ||
}; | ||
GFWAPI.prototype.getTokenWithRefreshToken = function (refreshToken) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, fetch(this.baseUrl + "/" + AUTH_PATH + "/token/reload", { | ||
headers: { | ||
'refresh-token': refreshToken, | ||
}, | ||
}) | ||
.then(processStatus) | ||
.then(parseJSON)]; | ||
}); | ||
}); | ||
}; | ||
GFWAPI.prototype.fetch = function (url, options) { | ||
if (options === void 0) { options = {}; } | ||
return this._internalFetch(url, options); | ||
}; | ||
GFWAPI.prototype.download = function (downloadUrl, fileName) { | ||
if (fileName === void 0) { fileName = 'download'; } | ||
return this._internalFetch(downloadUrl, { json: false }) | ||
.then(function (res) { return res.blob(); }) | ||
.then(function (blob) { | ||
FileSaver_min_1(blob, fileName); | ||
return true; | ||
}) | ||
.catch(function (e) { | ||
return false; | ||
}); | ||
}; | ||
GFWAPI.prototype._internalFetch = function (url, options, refreshRetries, waitLogin) { | ||
if (options === void 0) { options = {}; } | ||
if (refreshRetries === void 0) { refreshRetries = 0; } | ||
if (waitLogin === void 0) { waitLogin = true; } | ||
return __awaiter(this, void 0, void 0, function () { | ||
var e_1, _a, method, _b, body, _c, headers, _d, json_1, signal, _e, dataset, prefix, fetchUrl, data, e_2, token, e_3, e_4; | ||
return __generator(this, function (_f) { | ||
switch (_f.label) { | ||
case 0: | ||
_f.trys.push([0, 14, , 15]); | ||
if (!(this.logging && waitLogin)) return [3 /*break*/, 4]; | ||
_f.label = 1; | ||
case 1: | ||
_f.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, this.logging]; | ||
case 2: | ||
_f.sent(); | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
e_1 = _f.sent(); | ||
if (this.debug) { | ||
console.log("Fetch resource executed without login headers in url: " + url); | ||
} | ||
return [3 /*break*/, 4]; | ||
case 4: | ||
_f.trys.push([4, 6, , 13]); | ||
_a = options.method, method = _a === void 0 ? 'GET' : _a, _b = options.body, body = _b === void 0 ? null : _b, _c = options.headers, headers = _c === void 0 ? {} : _c, _d = options.json, json_1 = _d === void 0 ? true : _d, signal = options.signal, _e = options.dataset, dataset = _e === void 0 ? this.dataset : _e; | ||
if (this.debug) { | ||
console.log("GFWAPI: Fetching url: " + url); | ||
} | ||
prefix = "" + (isUrlAbsolute(url) ? '' : this.baseUrl); | ||
fetchUrl = prefix + (dataset ? "/datasets/" + this.dataset : '') + url; | ||
return [4 /*yield*/, fetch(fetchUrl, __assign(__assign({ method: method, | ||
signal: signal }, (body && { body: JSON.stringify(body) })), { headers: __assign(__assign({}, headers), { Authorization: "Bearer " + this.getToken() }) })) | ||
.then(processStatus) | ||
.then(function (res) { return (json_1 ? parseJSON(res) : res); })]; | ||
case 5: | ||
data = _f.sent(); | ||
return [2 /*return*/, data]; | ||
case 6: | ||
e_2 = _f.sent(); | ||
if (!(refreshRetries <= this.maxRefreshRetries)) return [3 /*break*/, 11]; | ||
if (!(e_2.status === 401 || e_2.status === 403)) return [3 /*break*/, 10]; | ||
if (this.debug) { | ||
console.log("GFWAPI: Trying to refresh the token attempt: " + refreshRetries); | ||
} | ||
_f.label = 7; | ||
case 7: | ||
_f.trys.push([7, 9, , 10]); | ||
return [4 /*yield*/, this.getTokenWithRefreshToken(this.getRefreshToken())]; | ||
case 8: | ||
token = (_f.sent()).token; | ||
this.setToken(token); | ||
if (this.debug) { | ||
console.log("GFWAPI: Token refresh worked! trying to fetch again " + url); | ||
} | ||
return [3 /*break*/, 10]; | ||
case 9: | ||
e_3 = _f.sent(); | ||
if (this.debug) { | ||
console.warn("GFWAPI: Error fetching " + url, e_3); | ||
} | ||
localStorage.removeItem(this.storageKeys.token); | ||
localStorage.removeItem(this.storageKeys.refreshToken); | ||
e_3.refreshError = true; | ||
throw e_3; | ||
case 10: return [2 /*return*/, this._internalFetch(url, options, ++refreshRetries, waitLogin)]; | ||
case 11: | ||
if (this.debug) { | ||
if (refreshRetries >= this.maxRefreshRetries) { | ||
console.log("GFWAPI: Attemps to retry the request excedeed"); | ||
} | ||
console.warn("GFWAPI: Error fetching " + url, e_2); | ||
} | ||
throw e_2; | ||
case 12: return [3 /*break*/, 13]; | ||
case 13: return [3 /*break*/, 15]; | ||
case 14: | ||
e_4 = _f.sent(); | ||
if (this.debug) { | ||
console.warn("GFWAPI: Error fetching " + url, e_4); | ||
} | ||
throw e_4; | ||
case 15: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
GFWAPI.prototype.fetchUser = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var user, e_5; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
_a.trys.push([0, 2, , 3]); | ||
return [4 /*yield*/, this._internalFetch("/" + AUTH_PATH + "/me", { dataset: false }, 0, false)]; | ||
case 1: | ||
user = _a.sent(); | ||
return [2 /*return*/, user]; | ||
case 2: | ||
e_5 = _a.sent(); | ||
console.warn(e_5); | ||
throw new Error('Error trying to get user data'); | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
GFWAPI.prototype.login = function (params) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var _a, accessToken, _b, refreshToken; | ||
var _this = this; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
_a = params.accessToken, accessToken = _a === void 0 ? null : _a, _b = params.refreshToken, refreshToken = _b === void 0 ? this.getRefreshToken() : _b; | ||
this.logging = new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { | ||
var tokens, e_6, msg, user, e_7, token, user, e_8, msg; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!accessToken) return [3 /*break*/, 4]; | ||
if (this.debug) { | ||
console.log("GFWAPI: Trying to get tokens using access-token"); | ||
} | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, this.getTokensWithAccessToken(accessToken)]; | ||
case 2: | ||
tokens = _a.sent(); | ||
this.setToken(tokens.token); | ||
this.setRefreshToken(tokens.refreshToken); | ||
if (this.debug) { | ||
console.log("GFWAPI: access-token valid, tokens ready"); | ||
} | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
e_6 = _a.sent(); | ||
if (!this.getToken() && !this.getRefreshToken()) { | ||
msg = isUnauthorizedError(e_6) | ||
? 'Invalid access token' | ||
: 'Error trying to generate tokens'; | ||
if (this.debug) { | ||
console.warn("GFWAPI: " + msg); | ||
} | ||
reject(new Error(msg)); | ||
return [2 /*return*/, null]; | ||
} | ||
return [3 /*break*/, 4]; | ||
case 4: | ||
if (!this.getToken()) return [3 /*break*/, 8]; | ||
if (this.debug) { | ||
console.log("GFWAPI: Trying to get user with current token"); | ||
} | ||
_a.label = 5; | ||
case 5: | ||
_a.trys.push([5, 7, , 8]); | ||
return [4 /*yield*/, this.fetchUser()]; | ||
case 6: | ||
user = _a.sent(); | ||
if (this.debug) { | ||
console.log("GFWAPI: Token valid, user data ready:", user); | ||
} | ||
resolve(user); | ||
return [2 /*return*/, user]; | ||
case 7: | ||
e_7 = _a.sent(); | ||
if (this.debug) { | ||
console.warn('GFWAPI: Token expired, trying to refresh', e_7); | ||
} | ||
return [3 /*break*/, 8]; | ||
case 8: | ||
if (!refreshToken) return [3 /*break*/, 13]; | ||
if (this.debug) { | ||
console.log("GFWAPI: Token wasn't valid, trying to refresh"); | ||
} | ||
_a.label = 9; | ||
case 9: | ||
_a.trys.push([9, 12, , 13]); | ||
return [4 /*yield*/, this.getTokenWithRefreshToken(refreshToken)]; | ||
case 10: | ||
token = (_a.sent()).token; | ||
this.setToken(token); | ||
if (this.debug) { | ||
console.log("GFWAPI: Refresh token OK, fetching user"); | ||
} | ||
return [4 /*yield*/, this.fetchUser()]; | ||
case 11: | ||
user = _a.sent(); | ||
if (this.debug) { | ||
console.log("GFWAPI: Login finished, user data ready:", user); | ||
} | ||
resolve(user); | ||
return [2 /*return*/, user]; | ||
case 12: | ||
e_8 = _a.sent(); | ||
msg = isUnauthorizedError(e_8) | ||
? 'Invalid refresh token' | ||
: 'Error trying to refreshing the token'; | ||
console.warn(e_8); | ||
if (this.debug) { | ||
console.warn("GFWAPI: " + msg); | ||
} | ||
reject(new Error(msg)); | ||
return [2 /*return*/, null]; | ||
case 13: | ||
reject(new Error('No login token provided')); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
return [4 /*yield*/, this.logging]; | ||
case 1: return [2 /*return*/, _c.sent()]; | ||
} | ||
}); | ||
}); | ||
}; | ||
GFWAPI.prototype.logout = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var e_9; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
_a.trys.push([0, 2, , 3]); | ||
if (this.debug) { | ||
console.log("GFWAPI: Logout - tokens cleaned"); | ||
} | ||
return [4 /*yield*/, fetch(this.baseUrl + "/" + AUTH_PATH + "/logout", { | ||
headers: { | ||
'refresh-token': this.refreshToken, | ||
}, | ||
}).then(processStatus)]; | ||
case 1: | ||
_a.sent(); | ||
this.setToken(''); | ||
this.setRefreshToken(''); | ||
if (this.debug) { | ||
console.log("GFWAPI: Logout invalid session api OK"); | ||
} | ||
return [2 /*return*/, true]; | ||
case 2: | ||
e_9 = _a.sent(); | ||
if (this.debug) { | ||
console.warn("GFWAPI: Logout invalid session fail"); | ||
} | ||
throw new Error('Error on the logout proccess'); | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
return GFWAPI; | ||
}()); | ||
var apiClient = new GFWAPI(); | ||
export default apiClient; | ||
export { USER_REFRESH_TOKEN_STORAGE_KEY, USER_TOKEN_STORAGE_KEY }; | ||
export{USER_REFRESH_TOKEN_STORAGE_KEY,USER_TOKEN_STORAGE_KEY,default}from"./api-client.js"; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@globalfishingwatch/api-client", | ||
"version": "1.0.2", | ||
"version": "1.1.0", | ||
"description": "", | ||
@@ -9,3 +9,3 @@ "author": "satellitestudio <contact@satellitestud.io>", | ||
"main": "dist/index.js", | ||
"typings": "dist/types/index.d.ts", | ||
"typings": "dist/index.d.ts", | ||
"directories": { | ||
@@ -24,4 +24,5 @@ "src": "src", | ||
"start": "rollup -c ./rollup.config.js -w", | ||
"build": "cross-env NODE_ENV=production tsc --module commonjs && rollup -c rollup.config.js", | ||
"prepublishOnly": "yarn build", | ||
"build": "cross-env NODE_ENV=production rollup -c rollup.config.js", | ||
"clean": "rimraf dist/*", | ||
"prepublishOnly": "yarn clean && yarn build", | ||
"test": "echo \"Error: run tests from root\" && exit 1" | ||
@@ -38,3 +39,3 @@ }, | ||
}, | ||
"gitHead": "8e1eeb803c294633adebb426ef6c4e128afa9427" | ||
"gitHead": "ab695c0e6d464f329330520935e63d5022f93a9f" | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
0
5
47290
14
146