@scaleflex/widget-companion-client 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 scaleflex
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # @scaleflex/widget-companion-client
2
+
3
+ [![Plugins][plugins-image]](#plugins)
4
+ [![Website][filerobot-image]][sfx-url]
5
+ [![Version][filerobot-version]][version-url]
6
+ [![Scaleflex team][made-by-image]][sfx-url]
7
+ [![License][license-image]][license-url]
8
+ [![CodeSandbox][codeSandbox-image]][codeSandbox-url]
9
+
10
+
11
+ <div align='center'>
12
+ <img title="Scaleflex Widget logo" alt="Scaleflex Widget logo" src="https://cdn.scaleflex.com/plugins/filerobot-widget/assets/filerobot_widget_logo_with_fire.png?vh=b2ff09" width="140"/>
13
+ </div>
14
+
15
+ The package used internally in [Scaleflex Media Asset Widget](https://www.npmjs.com/package/@scaleflex/widget-core) while communicating with companion of backend for handling 3rd parties uploading.
16
+
17
+
18
+ <!-- Variables -->
19
+
20
+ [npm-url]: https://www.npmjs.com/package/@scaleflex/widget-companion-client
21
+ [license-url]: https://opensource.org/licenses/MIT
22
+ [sfx-url]: https://www.scaleflex.com/
23
+ [version-url]: https://www.npmjs.com/package/@scaleflex/widget-companion-client
24
+ [codeSandbox-url]: https://codesandbox.io/s/filerobot-widget-v3-c5l9th
25
+
26
+
27
+ [npm-image]: https://img.shields.io/npm/v/@telus/remark-config.svg?style=for-the-badge&logo=npm
28
+ [license-image]: https://img.shields.io/badge/license-MIT-blue.svg?style=for-the-badge
29
+ [made-by-image]: https://img.shields.io/badge/%3C%2F%3E%20with%20%E2%99%A5%20by-the%20Scaleflex%20team-6986fa.svg?style=for-the-badge
30
+ [plugins-image]: https://img.shields.io/static/v1?label=Scaleflex&message=Plugins&color=yellow&style=for-the-badge
31
+ [filerobot-image]: https://img.shields.io/static/v1?label=Scaleflex&message=website&color=orange&style=for-the-badge
32
+ [filerobot-version]: https://img.shields.io/npm/v/@scaleflex/widget-companion-client?label=Version&style=for-the-badge&logo=npm
33
+ [codeSandbox-image]: https://img.shields.io/badge/CodeSandbox-black?style=for-the-badge&logo=CodeSandbox
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+
3
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
4
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
5
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
6
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
7
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
8
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
9
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
10
+ function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
11
+ function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
12
+ function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
13
+ function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); }
14
+ function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }
15
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
16
+ function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } }
17
+ function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
18
+ function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
19
+ var AuthError = /*#__PURE__*/function (_Error) {
20
+ function AuthError() {
21
+ var _this;
22
+ _classCallCheck(this, AuthError);
23
+ _this = _callSuper(this, AuthError, ['Authorization required']);
24
+ _this.name = 'AuthError';
25
+ _this.isAuthError = true;
26
+ return _this;
27
+ }
28
+ _inherits(AuthError, _Error);
29
+ return _createClass(AuthError);
30
+ }(/*#__PURE__*/_wrapNativeSuper(Error));
31
+ export default AuthError;
@@ -0,0 +1,117 @@
1
+ 'use strict';
2
+
3
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
4
+ function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
5
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
6
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
7
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
8
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
9
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
10
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
11
+ function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
12
+ function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
13
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
14
+ function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
15
+ function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); }
16
+ function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; }
17
+ function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
18
+ function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
19
+ function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
20
+ import RequestClient from './RequestClient';
21
+ import * as tokenStorage from './tokenStorage';
22
+ var _getName = function _getName(id) {
23
+ return id.split('-').map(function (s) {
24
+ return s.charAt(0).toUpperCase() + s.slice(1);
25
+ }).join(' ');
26
+ };
27
+ var Provider = /*#__PURE__*/function (_RequestClient) {
28
+ function Provider(filerobot) {
29
+ var _this;
30
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
31
+ _classCallCheck(this, Provider);
32
+ _this = _callSuper(this, Provider, [filerobot, opts]);
33
+ _this.provider = opts.provider;
34
+ _this.id = _this.provider;
35
+ _this.name = _this.opts.name || _getName(_this.id);
36
+ _this.pluginId = _this.opts.pluginId;
37
+ _this.tokenKey = "companion-".concat(_this.pluginId, "-auth-token");
38
+ return _this;
39
+ }
40
+ _inherits(Provider, _RequestClient);
41
+ return _createClass(Provider, [{
42
+ key: "headers",
43
+ value: function headers() {
44
+ var _this2 = this;
45
+ return new Promise(function (resolve, reject) {
46
+ _superPropGet(Provider, "headers", _this2, 3)([]).then(function (headers) {
47
+ _this2.getAuthToken().then(function (token) {
48
+ // TODO: change uppy-auth-token & all uppyTokens to filerobot-auth-token & filerobotTokens when BE do it.
49
+ resolve(_extends({}, headers, {
50
+ 'uppy-auth-token': token
51
+ }));
52
+ });
53
+ })["catch"](reject);
54
+ });
55
+ }
56
+ }, {
57
+ key: "onReceiveResponse",
58
+ value: function onReceiveResponse(response) {
59
+ response = _superPropGet(Provider, "onReceiveResponse", this, 3)([response]);
60
+ var plugin = this.filerobot.getPlugin(this.pluginId);
61
+ var oldAuthenticated = plugin.getPluginCommonState().authenticated;
62
+ var authenticated = oldAuthenticated ? response.status !== 401 : response.status < 400;
63
+ plugin.setPluginCommonState({
64
+ authenticated: authenticated
65
+ });
66
+ return response;
67
+ }
68
+ }, {
69
+ key: "setAuthToken",
70
+ value: function setAuthToken(token) {
71
+ return this.filerobot.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token);
72
+ }
73
+ }, {
74
+ key: "getAuthToken",
75
+ value: function getAuthToken() {
76
+ return this.filerobot.getPlugin(this.pluginId).storage.getItem(this.tokenKey);
77
+ }
78
+ }, {
79
+ key: "authUrl",
80
+ value: function authUrl() {
81
+ return "".concat(this.hostname, "/").concat(this.id, "/connect");
82
+ }
83
+ }, {
84
+ key: "fileUrl",
85
+ value: function fileUrl(id) {
86
+ return "".concat(this.hostname, "/").concat(this.id, "/get/").concat(id);
87
+ }
88
+ }, {
89
+ key: "list",
90
+ value: function list(directory) {
91
+ return this.get("".concat(this.id, "/list/").concat(directory || ''));
92
+ }
93
+ }, {
94
+ key: "logout",
95
+ value: function logout() {
96
+ var _this3 = this;
97
+ return new Promise(function (resolve, reject) {
98
+ _this3.get("".concat(_this3.id, "/logout")).then(function (res) {
99
+ _this3.filerobot.getPlugin(_this3.pluginId).storage.removeItem(_this3.tokenKey).then(function () {
100
+ return resolve(res);
101
+ })["catch"](reject);
102
+ })["catch"](reject);
103
+ });
104
+ }
105
+ }], [{
106
+ key: "initPlugin",
107
+ value: function initPlugin(plugin, opts, defaultOpts) {
108
+ plugin.type = 'acquirer';
109
+ plugin.files = [];
110
+ if (defaultOpts) {
111
+ plugin.opts = _extends({}, defaultOpts, opts);
112
+ }
113
+ plugin.storage = plugin.opts.storage || tokenStorage;
114
+ }
115
+ }]);
116
+ }(RequestClient);
117
+ export default Provider;
@@ -0,0 +1,271 @@
1
+ 'use strict';
2
+
3
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
4
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
5
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
6
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
7
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
8
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
9
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
10
+ function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
11
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
12
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
13
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
14
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
15
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
16
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
17
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
18
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
19
+ import { COMPANION_URLS } from '@scaleflex/widget-utils/lib/constants';
20
+ import fetchWithNetworkError from '@scaleflex/widget-utils/lib/fetchWithNetworkError';
21
+ import AuthError from './AuthError';
22
+ // TODO: find a way to show version of the current plugin
23
+ // why solution below isn't good?
24
+ // first import doesn't work with webpack 5 as it was deprecated
25
+ // second import fixes webpack 5 issue as it was mentioned in their docs
26
+ // but it exposes our package.json to the client and it is mentioned as security rist in mutiple places
27
+ // https://github.com/axelpale/genversion
28
+ // https://stackoverflow.com/questions/64993118/error-should-not-import-the-named-export-version-imported-as-version
29
+ // https://stackoverflow.com/questions/9153571/is-there-a-way-to-get-version-from-package-json-in-nodejs-code/10855054#10855054
30
+ // import { version } from '../package.json'
31
+ // import packageInfo from '../package.json'
32
+
33
+ // Remove the trailing slash so we can always safely append /xyz.
34
+ function stripSlash(url) {
35
+ return url.replace(/\/$/, '');
36
+ }
37
+ var RequestClient = /*#__PURE__*/function () {
38
+ // static VERSION = packageInfo.version
39
+
40
+ function RequestClient(filerobot) {
41
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
42
+ _classCallCheck(this, RequestClient);
43
+ this.filerobot = filerobot;
44
+ this.companionUrl = filerobot.opts.dev ? COMPANION_URLS.DEV : COMPANION_URLS.PROD;
45
+ this.opts = opts;
46
+ this.onReceiveResponse = this.onReceiveResponse.bind(this);
47
+ // TODO: change uppy-auth-token & all uppyTokens to filerobot-auth-token & filerobotTokens when BE do it.
48
+ this.allowedHeaders = ['accept', 'content-type', 'uppy-auth-token'];
49
+ this.preflightDone = false;
50
+ this._addCancelAbility();
51
+ this._increaseRequestsNumber = this._increaseRequestsNumber.bind(this);
52
+ this._decreaseRequestsNumber = this._decreaseRequestsNumber.bind(this);
53
+ this.checkIfTherePendingRequests = this.checkIfTherePendingRequests.bind(this);
54
+ }
55
+ return _createClass(RequestClient, [{
56
+ key: "hostname",
57
+ get: function get() {
58
+ var _this$filerobot$getCo = this.filerobot.getCoreCommonState(),
59
+ companion = _this$filerobot$getCo.companion;
60
+ var host = this.companionUrl;
61
+ return stripSlash(companion && companion[host] ? companion[host] : host);
62
+ }
63
+ }, {
64
+ key: "defaultHeaders",
65
+ get: function get() {
66
+ return {
67
+ Accept: 'application/json',
68
+ 'Content-Type': 'application/json',
69
+ 'Filerobot-Versions': "@filerobot/companion-client=".concat(RequestClient.VERSION)
70
+ };
71
+ }
72
+ }, {
73
+ key: "headers",
74
+ value: function headers() {
75
+ var userHeaders = this.opts.companionHeaders || {};
76
+ return Promise.resolve(_objectSpread(_objectSpread({}, this.defaultHeaders), userHeaders));
77
+ }
78
+ }, {
79
+ key: "_getPostResponseFunc",
80
+ value: function _getPostResponseFunc(skip) {
81
+ var _this = this;
82
+ return function (response) {
83
+ if (!skip) {
84
+ return _this.onReceiveResponse(response);
85
+ }
86
+ return response;
87
+ };
88
+ }
89
+ }, {
90
+ key: "onReceiveResponse",
91
+ value: function onReceiveResponse(response) {
92
+ var state = this.filerobot.getCoreCommonState();
93
+ var companion = state.companion || {};
94
+ var host = this.companionUrl;
95
+ var headers = response.headers;
96
+
97
+ // Store the self-identified domain name for the Companion instance we just hit.
98
+ if (headers.has('i-am') && headers.get('i-am') !== companion[host]) {
99
+ this.filerobot.setCoreCommonState({
100
+ companion: _extends({}, companion, _defineProperty({}, host, headers.get('i-am')))
101
+ });
102
+ }
103
+ return response;
104
+ }
105
+ }, {
106
+ key: "_getUrl",
107
+ value: function _getUrl(url) {
108
+ if (/^(https?:|)\/\//.test(url)) {
109
+ return url;
110
+ }
111
+ return "".concat(this.hostname, "/").concat(url);
112
+ }
113
+ }, {
114
+ key: "_json",
115
+ value: function _json(res) {
116
+ if (res.status === 401) {
117
+ throw new AuthError();
118
+ }
119
+ if (res.status < 200 || res.status > 300) {
120
+ var errMsg = "Failed request with status: ".concat(res.status, ". ").concat(res.statusText);
121
+ return res.json().then(function (errData) {
122
+ errMsg = errData.message ? "".concat(errMsg, " message: ").concat(errData.message) : errMsg;
123
+ errMsg = errData.requestId ? "".concat(errMsg, " request-Id: ").concat(errData.requestId) : errMsg;
124
+ throw new Error(errMsg);
125
+ })["catch"](function () {
126
+ throw new Error(errMsg);
127
+ });
128
+ }
129
+ return res.json();
130
+ }
131
+ }, {
132
+ key: "_increaseRequestsNumber",
133
+ value: function _increaseRequestsNumber() {
134
+ this._requestsNumber++;
135
+ }
136
+ }, {
137
+ key: "_decreaseRequestsNumber",
138
+ value: function _decreaseRequestsNumber() {
139
+ this._requestsNumber--;
140
+ }
141
+ }, {
142
+ key: "_addCancelAbility",
143
+ value: function _addCancelAbility() {
144
+ this._controller = new AbortController();
145
+ this._signal = this._controller.signal;
146
+ this._requestsNumber = 0;
147
+ }
148
+ }, {
149
+ key: "checkIfTherePendingRequests",
150
+ value: function checkIfTherePendingRequests() {
151
+ return this._requestsNumber > 0;
152
+ }
153
+ }, {
154
+ key: "preflight",
155
+ value: function preflight(path) {
156
+ var _this2 = this;
157
+ return new Promise(function (resolve, reject) {
158
+ if (_this2.preflightDone) {
159
+ return resolve(_this2.allowedHeaders.slice());
160
+ }
161
+ _this2._increaseRequestsNumber();
162
+ fetch(_this2._getUrl(path), {
163
+ method: 'OPTIONS',
164
+ signal: _this2._signal
165
+ }).then(function (response) {
166
+ if (response.headers.has('access-control-allow-headers')) {
167
+ _this2.allowedHeaders = response.headers.get('access-control-allow-headers').split(',').map(function (headerName) {
168
+ return headerName.trim().toLowerCase();
169
+ });
170
+ }
171
+ _this2.preflightDone = true;
172
+ resolve(_this2.allowedHeaders.slice());
173
+ })["catch"](function (err) {
174
+ _this2.filerobot.log("[CompanionClient] unable to make preflight request ".concat(err), 'warning');
175
+ _this2.preflightDone = true;
176
+ resolve(_this2.allowedHeaders.slice());
177
+ })["finally"](_this2._decreaseRequestsNumber);
178
+ });
179
+ }
180
+ }, {
181
+ key: "preflightAndHeaders",
182
+ value: function preflightAndHeaders(path) {
183
+ var _this3 = this;
184
+ return Promise.all([this.preflight(path), this.headers()]).then(function (_ref) {
185
+ var _ref2 = _slicedToArray(_ref, 2),
186
+ allowedHeaders = _ref2[0],
187
+ headers = _ref2[1];
188
+ // filter to keep only allowed Headers
189
+ Object.keys(headers).forEach(function (header) {
190
+ if (allowedHeaders.indexOf(header.toLowerCase()) === -1) {
191
+ _this3.filerobot.log("[CompanionClient] excluding unallowed header ".concat(header));
192
+ delete headers[header];
193
+ }
194
+ });
195
+ return headers;
196
+ });
197
+ }
198
+ }, {
199
+ key: "get",
200
+ value: function get(path, skipPostResponse) {
201
+ var _this4 = this;
202
+ return new Promise(function (resolve, reject) {
203
+ _this4.preflightAndHeaders(path).then(function (headers) {
204
+ _this4._increaseRequestsNumber();
205
+ fetchWithNetworkError(_this4._getUrl(path), {
206
+ method: 'get',
207
+ headers: headers,
208
+ credentials: 'same-origin',
209
+ signal: _this4._signal
210
+ }).then(_this4._getPostResponseFunc(skipPostResponse)).then(function (res) {
211
+ return _this4._json(res).then(resolve);
212
+ })["catch"](function (err) {
213
+ err = err.isAuthError ? err : new Error("Could not get ".concat(_this4._getUrl(path), ". ").concat(err));
214
+ reject(err);
215
+ })["finally"](_this4._decreaseRequestsNumber);
216
+ })["catch"](reject);
217
+ });
218
+ }
219
+ }, {
220
+ key: "post",
221
+ value: function post(path, data, skipPostResponse) {
222
+ var _this5 = this;
223
+ return new Promise(function (resolve, reject) {
224
+ _this5.preflightAndHeaders(path).then(function (headers) {
225
+ _this5._increaseRequestsNumber();
226
+ fetchWithNetworkError(_this5._getUrl(path), {
227
+ method: 'post',
228
+ headers: headers,
229
+ credentials: 'same-origin',
230
+ body: JSON.stringify(data),
231
+ signal: _this5._signal
232
+ }).then(_this5._getPostResponseFunc(skipPostResponse)).then(function (res) {
233
+ return _this5._json(res).then(resolve);
234
+ })["catch"](function (err) {
235
+ err = err.isAuthError ? err : new Error("Could not post ".concat(_this5._getUrl(path), ". ").concat(err));
236
+ reject(err);
237
+ })["finally"](_this5._decreaseRequestsNumber);
238
+ })["catch"](reject);
239
+ });
240
+ }
241
+ }, {
242
+ key: "delete",
243
+ value: function _delete(path, data, skipPostResponse) {
244
+ var _this6 = this;
245
+ return new Promise(function (resolve, reject) {
246
+ _this6.preflightAndHeaders(path).then(function (headers) {
247
+ _this6._increaseRequestsNumber();
248
+ fetchWithNetworkError("".concat(_this6.hostname, "/").concat(path), {
249
+ method: 'delete',
250
+ headers: headers,
251
+ credentials: 'same-origin',
252
+ body: data ? JSON.stringify(data) : null,
253
+ signal: _this6._signal
254
+ }).then(_this6._getPostResponseFunc(skipPostResponse)).then(function (res) {
255
+ return _this6._json(res).then(resolve);
256
+ })["catch"](function (err) {
257
+ err = err.isAuthError ? err : new Error("Could not delete ".concat(_this6._getUrl(path), ". ").concat(err));
258
+ reject(err);
259
+ })["finally"](_this6._decreaseRequestsNumber);
260
+ })["catch"](reject);
261
+ });
262
+ }
263
+ }, {
264
+ key: "cancel",
265
+ value: function cancel() {
266
+ this._controller.abort();
267
+ this._addCancelAbility();
268
+ }
269
+ }]);
270
+ }();
271
+ export default RequestClient;
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
4
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
5
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
6
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
7
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
8
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
9
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
10
+ function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
11
+ function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
12
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
13
+ function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
14
+ function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
15
+ function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
16
+ import RequestClient from './RequestClient';
17
+ var getName = function getName(id) {
18
+ return id.split('-').map(function (s) {
19
+ return s.charAt(0).toUpperCase() + s.slice(1);
20
+ }).join(' ');
21
+ };
22
+ var SearchProvider = /*#__PURE__*/function (_RequestClient) {
23
+ function SearchProvider(filerobot, opts) {
24
+ var _this;
25
+ _classCallCheck(this, SearchProvider);
26
+ _this = _callSuper(this, SearchProvider, [filerobot, opts]);
27
+ _this.provider = opts.provider;
28
+ _this.id = _this.provider;
29
+ _this.name = _this.opts.name || getName(_this.id);
30
+ _this.pluginId = _this.opts.pluginId;
31
+ return _this;
32
+ }
33
+ _inherits(SearchProvider, _RequestClient);
34
+ return _createClass(SearchProvider, [{
35
+ key: "fileUrl",
36
+ value: function fileUrl(id) {
37
+ return "".concat(this.hostname, "/search/").concat(this.id, "/get/").concat(id);
38
+ }
39
+ }, {
40
+ key: "search",
41
+ value: function search(text, queries) {
42
+ return this.get("search/".concat(this.id, "/list?q=").concat(encodeURIComponent(text)).concat(queries ? "&".concat(queries) : ''));
43
+ }
44
+ }]);
45
+ }(RequestClient);
46
+ export { SearchProvider as default };
package/lib/Socket.js ADDED
@@ -0,0 +1,102 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
3
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
4
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
5
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
6
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
7
+ import ee from 'namespace-emitter';
8
+ var FilerobotSocket = /*#__PURE__*/function () {
9
+ function FilerobotSocket(opts) {
10
+ _classCallCheck(this, FilerobotSocket);
11
+ this.opts = opts;
12
+ this._queued = [];
13
+ this.isOpen = false;
14
+ this.emitter = ee();
15
+ this._handleMessage = this._handleMessage.bind(this);
16
+ this.close = this.close.bind(this);
17
+ this.emit = this.emit.bind(this);
18
+ this.on = this.on.bind(this);
19
+ this.once = this.once.bind(this);
20
+ this.send = this.send.bind(this);
21
+ if (!opts || opts.autoOpen !== false) {
22
+ this.open();
23
+ }
24
+ }
25
+ return _createClass(FilerobotSocket, [{
26
+ key: "open",
27
+ value: function open() {
28
+ var _this = this;
29
+ this.socket = new WebSocket(this.opts.target);
30
+ this.socket.onopen = function (e) {
31
+ _this.isOpen = true;
32
+ while (_this._queued.length > 0 && _this.isOpen) {
33
+ var first = _this._queued[0];
34
+ _this.send(first.action, first.payload);
35
+ _this._queued = _this._queued.slice(1);
36
+ }
37
+ };
38
+ this.socket.onclose = function (e) {
39
+ _this.isOpen = false;
40
+ };
41
+ this.socket.onmessage = this._handleMessage;
42
+ }
43
+ }, {
44
+ key: "close",
45
+ value: function close() {
46
+ if (this.socket) {
47
+ this.socket.close();
48
+ }
49
+ }
50
+ }, {
51
+ key: "send",
52
+ value: function send(action, payload) {
53
+ // attach uuid
54
+
55
+ if (!this.socket || this.socket.readyState === WebSocket.CONNECTING) {
56
+ // If socket is still connecting
57
+ this._queued.push({
58
+ action: action,
59
+ payload: payload
60
+ });
61
+ return;
62
+ }
63
+ if (!this.isOpen) {
64
+ this._queued.push({
65
+ action: action,
66
+ payload: payload
67
+ });
68
+ return;
69
+ }
70
+ this.socket.send(JSON.stringify({
71
+ action: action,
72
+ payload: payload
73
+ }));
74
+ }
75
+ }, {
76
+ key: "on",
77
+ value: function on(action, handler) {
78
+ this.emitter.on(action, handler);
79
+ }
80
+ }, {
81
+ key: "emit",
82
+ value: function emit(action, payload) {
83
+ this.emitter.emit(action, payload);
84
+ }
85
+ }, {
86
+ key: "once",
87
+ value: function once(action, handler) {
88
+ this.emitter.once(action, handler);
89
+ }
90
+ }, {
91
+ key: "_handleMessage",
92
+ value: function _handleMessage(e) {
93
+ try {
94
+ var message = JSON.parse(e.data);
95
+ this.emit(message.action, message.payload);
96
+ } catch (err) {
97
+ console.log(err);
98
+ }
99
+ }
100
+ }]);
101
+ }();
102
+ export default FilerobotSocket;
package/lib/index.js ADDED
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Manages communications with Companion
5
+ */
6
+ import RequestClient from './RequestClient';
7
+ import Provider from './Provider';
8
+ import Socket from './Socket';
9
+ import SearchProvider from './SearchProvider';
10
+ export { RequestClient, Provider, Socket, SearchProvider };
11
+ export default {
12
+ RequestClient: RequestClient,
13
+ Provider: Provider,
14
+ Socket: Socket,
15
+ SearchProvider: SearchProvider
16
+ };