@paydock/client-sdk
Version:
Paydock client sdk
1,490 lines (1,455 loc) • 2.11 MB
JavaScript
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;
}
function _arrayWithHoles(r) {
if (Array.isArray(r)) return r;
}
function _arrayWithoutHoles(r) {
if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function _assertThisInitialized(e) {
if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return e;
}
function _callSuper(t, o, e) {
return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
}
function _classCallCheck(a, n) {
if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
}
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;
}
function _defineProperties(e, r) {
for (var t = 0; t < r.length; t++) {
var o = r[t];
o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
}
}
function _createClass(e, r, t) {
return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
writable: false
}), e;
}
function _createForOfIteratorHelper(r, e) {
var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (!t) {
if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
t && (r = t);
var n = 0,
F = function () {};
return {
s: F,
n: function () {
return n >= r.length ? {
done: true
} : {
done: false,
value: r[n++]
};
},
e: function (r) {
throw r;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var o,
a = true,
u = false;
return {
s: function () {
t = t.call(r);
},
n: function () {
var r = t.next();
return a = r.done, r;
},
e: function (r) {
u = true, o = r;
},
f: function () {
try {
a || null == t.return || t.return();
} finally {
if (u) throw o;
}
}
};
}
function _defineProperty(e, r, t) {
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: true,
configurable: true,
writable: true
}) : e[r] = t, e;
}
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);
}
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);
}
function _getPrototypeOf(t) {
return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
return t.__proto__ || Object.getPrototypeOf(t);
}, _getPrototypeOf(t);
}
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: true,
configurable: true
}
}), Object.defineProperty(t, "prototype", {
writable: false
}), e && _setPrototypeOf(t, e);
}
function _isNativeFunction(t) {
try {
return -1 !== Function.toString.call(t).indexOf("[native code]");
} catch (n) {
return "function" == typeof t;
}
}
function _isNativeReflectConstruct() {
try {
var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
} catch (t) {}
return (_isNativeReflectConstruct = function () {
return !!t;
})();
}
function _iterableToArray(r) {
if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
}
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 = true,
o = false;
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 = true, n = r;
} finally {
try {
if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
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.");
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
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);
}
function _regenerator() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
var e,
t,
r = "function" == typeof Symbol ? Symbol : {},
n = r.iterator || "@@iterator",
o = r.toStringTag || "@@toStringTag";
function i(r, n, o, i) {
var c = n && n.prototype instanceof Generator ? n : Generator,
u = Object.create(c.prototype);
return _regeneratorDefine(u, "_invoke", function (r, n, o) {
var i,
c,
u,
f = 0,
p = o || [],
y = false,
G = {
p: 0,
n: 0,
v: e,
a: d,
f: d.bind(e, 4),
d: function (t, r) {
return i = t, c = 0, u = e, G.n = r, a;
}
};
function d(r, n) {
for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
var o,
i = p[t],
d = G.p,
l = i[2];
r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
}
if (o || r > 1) return a;
throw y = true, n;
}
return function (o, p, l) {
if (f > 1) throw TypeError("Generator is already running");
for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
try {
if (f = 2, i) {
if (c || (o = "next"), t = i[o]) {
if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
if (!t.done) return t;
u = t.value, c < 2 && (c = 0);
} else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
i = e;
} else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
} catch (t) {
i = e, c = 1, u = t;
} finally {
f = 1;
}
}
return {
value: t,
done: y
};
};
}(r, o, i), true), u;
}
var a = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
t = Object.getPrototypeOf;
var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
return this;
}), t),
u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
function f(e) {
return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
return this;
}), _regeneratorDefine(u, "toString", function () {
return "[object Generator]";
}), (_regenerator = function () {
return {
w: i,
m: f
};
})();
}
function _regeneratorDefine(e, r, n, t) {
var i = Object.defineProperty;
try {
i({}, "", {});
} catch (e) {
i = 0;
}
_regeneratorDefine = function (e, r, n, t) {
function o(r, n) {
_regeneratorDefine(e, r, function (e) {
return this._invoke(r, n, e);
});
}
r ? i ? i(e, r, {
value: n,
enumerable: !t,
configurable: !t,
writable: !t
}) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
}, _regeneratorDefine(e, r, n, t);
}
function _regeneratorKeys(e) {
var n = Object(e),
r = [];
for (var t in n) r.unshift(t);
return function e() {
for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = false, e;
return e.done = true, e;
};
}
function _setPrototypeOf(t, e) {
return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
return t.__proto__ = e, t;
}, _setPrototypeOf(t, e);
}
function _slicedToArray(r, e) {
return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _superPropBase(t, o) {
for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t)););
return t;
}
function _superPropGet(t, o, e, r) {
var p = _get(_getPrototypeOf(t.prototype ), o, e);
return 2 & r && "function" == typeof p ? function (t) {
return p.apply(e, t);
} : p;
}
function _toConsumableArray(r) {
return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
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);
if ("object" != typeof i) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (String )(t);
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string");
return "symbol" == typeof i ? i : i + "";
}
function _typeof$1(o) {
"@babel/helpers - typeof";
return _typeof$1 = "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$1(o);
}
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;
}
}
function _wrapNativeSuper(t) {
var r = "function" == typeof Map ? new Map() : void 0;
return _wrapNativeSuper = function (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: false,
writable: true,
configurable: true
}
}), _setPrototypeOf(Wrapper, t);
}, _wrapNativeSuper(t);
}
var Event$1 = /*#__PURE__*/function () {
function Event() {
_classCallCheck(this, Event);
}
return _createClass(Event, null, [{
key: "insertToInput",
value: function insertToInput(selector, dataType, eventData) {
if (typeof eventData[dataType] === "undefined") return;
var input = document.querySelector(selector);
if (!input) return;
input.value = eventData[dataType];
}
}, {
key: "subscribe",
value: function subscribe(name, subject, listener) {
if (subject.addEventListener) {
subject.addEventListener(name, listener);
} else {
subject.attachEvent("on".concat(name), listener);
}
}
}]);
}();
var Container = /*#__PURE__*/function () {
function Container(selector) {
_classCallCheck(this, Container);
this.selector = selector;
}
return _createClass(Container, [{
key: "isExist",
value: function isExist() {
return !!this.getElement();
}
}, {
key: "getStyles",
value: function getStyles(allowValue) {
if (!this.isExist()) return;
var container = this.getElement();
var styles = container.getAttribute("widget-style");
if (!styles) return {};
var containerStyleCollection = styles.split(';');
if (typeof containerStyleCollection !== 'undefined' && !containerStyleCollection.length) return {};
return this.convertConfigs(containerStyleCollection, allowValue);
}
}, {
key: "on",
value: function on(name, cb) {
if (!this.isExist()) return;
Event$1.subscribe(name, this.getElement(), cb);
}
}, {
key: "getAttr",
value: function getAttr(allowValue) {
if (!this.isExist()) return;
var container = this.getElement();
var containerTextCollection = [];
for (var index in allowValue) {
if (!allowValue.hasOwnProperty(index)) continue;
var item = allowValue[index].replace(/_/g, "-");
var currentConfig = container.getAttribute(item);
if (currentConfig) {
containerTextCollection.push("".concat(allowValue[index], ":").concat(currentConfig));
}
}
if (typeof containerTextCollection !== 'undefined' && !containerTextCollection.length) return {};
return this.convertConfigs(containerTextCollection, allowValue);
}
}, {
key: "getElement",
value: function getElement() {
return document.querySelector(this.selector);
}
}, {
key: "getSelector",
value: function getSelector() {
return this.selector;
}
}, {
key: "convertConfigs",
value: function convertConfigs(params, allowValue) {
var config = {};
for (var index in params) {
if (!params.hasOwnProperty(index)) continue;
var style = params[index].split(':');
var collectionKey = style[0].replace(/-/g, "_").trim();
if (allowValue.indexOf(collectionKey) !== -1) config[collectionKey] = style[1].trim();
}
return config;
}
}]);
}();
/******************************************************************************
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.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
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 __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var EventEmitter = /*#__PURE__*/function () {
function EventEmitter() {
_classCallCheck(this, EventEmitter);
this.events = {};
}
return _createClass(EventEmitter, [{
key: "emit",
value: function emit(eventName, data) {
var event = this.events[eventName];
if (event) {
event.forEach(function (fn) {
fn.call(null, data);
});
}
}
}, {
key: "emitWithResult",
value: function emitWithResult(eventName, data) {
var _this = this;
var event = this.events[eventName];
if (event) {
var results = event.map(function (fn) {
return __awaiter(_this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee() {
return _regenerator().w(function (_context) {
while (1) switch (_context.n) {
case 0:
return _context.a(2, fn.call(null, data));
}
}, _callee);
}));
});
return Promise.all(results);
}
return Promise.resolve([]);
}
}, {
key: "subscribe",
value: function subscribe(eventName, handler) {
var _this2 = this;
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(handler);
return function () {
_this2.events[eventName] = _this2.events[eventName].filter(function (storedHandler) {
return handler !== storedHandler;
});
};
}
}]);
}();
var PageType;
(function (PageType) {
PageType["CART"] = "cart";
PageType["PRODUCT"] = "product";
})(PageType || (PageType = {}));
var AFTERPAY_ON_SITE_MESSAGING_EVENTS = {
ON_SUCCESS: 'ON_SUCCESS',
ON_ERROR: 'ON_ERROR'
};
var ErrorCodes$2;
(function (ErrorCodes) {
ErrorCodes["UNAVAILABLE"] = "unavailable";
ErrorCodes["SCRIPT_ERROR"] = "script_error";
ErrorCodes["VALIDATION_ERROR"] = "validation_error";
})(ErrorCodes$2 || (ErrorCodes$2 = {}));
var AfterpayOnSiteMessagingService = /*#__PURE__*/function () {
function AfterpayOnSiteMessagingService(eventEmitter, config) {
_classCallCheck(this, AfterpayOnSiteMessagingService);
this.eventEmitter = eventEmitter;
this.config = config;
}
return _createClass(AfterpayOnSiteMessagingService, [{
key: "load",
value: function load(container) {
this.renderAfterpayOnSiteMessagingComponent(container);
}
}, {
key: "renderAfterpayOnSiteMessagingComponent",
value: function renderAfterpayOnSiteMessagingComponent(container) {
var _this = this;
var isValid = this.isValidConfig(this.config);
if (!isValid) {
return;
}
var containerElement = container.getElement();
var afterpayScript = document.createElement('script');
afterpayScript.src = 'https://js-sandbox.squarecdn.com/square-marketplace.js';
afterpayScript.async = true;
afterpayScript.onload = function () {
var squarePlacement = document.createElement('square-placement');
squarePlacement.setAttribute('data-mpid', _this.config.mpid);
squarePlacement.setAttribute('data-placement-id', _this.config.placement_id);
squarePlacement.setAttribute('data-page-type', _this.config.page_type);
squarePlacement.setAttribute('data-currency', _this.config.currency);
if (_this.config.amount) {
squarePlacement.setAttribute('data-amount', _this.config.amount);
}
if (_this.config.consumer_locale) {
squarePlacement.setAttribute('data-consumer-locale', _this.config.consumer_locale);
}
if (_this.config.item_skus) {
squarePlacement.setAttribute('data-item-skus', _this.config.item_skus);
}
if (_this.config.item_categories) {
squarePlacement.setAttribute('data-item-categories', _this.config.item_categories);
}
if (_this.config.is_eligible !== undefined) {
squarePlacement.setAttribute('data-is-eligible', _this.config.is_eligible ? 'true' : 'false');
}
if (containerElement) {
containerElement.appendChild(squarePlacement);
_this.eventEmitter.emit(AFTERPAY_ON_SITE_MESSAGING_EVENTS.ON_SUCCESS);
} else {
_this.eventEmitter.emit(AFTERPAY_ON_SITE_MESSAGING_EVENTS.ON_ERROR, {
error_code: ErrorCodes$2.UNAVAILABLE
});
}
};
document.head.appendChild(afterpayScript);
}
}, {
key: "isValidConfig",
value: function isValidConfig(config) {
if (!config) {
this.onError('Config is required', ErrorCodes$2.VALIDATION_ERROR);
return false;
}
if (!config.mpid) {
this.onError('MPID is required', ErrorCodes$2.VALIDATION_ERROR);
return false;
}
if (!config.placement_id) {
this.onError('Placement ID is required', ErrorCodes$2.VALIDATION_ERROR);
return false;
}
if (!config.page_type) {
this.onError('Page type is required', ErrorCodes$2.VALIDATION_ERROR);
return false;
}
if (!config.currency) {
this.onError('Currency is required', ErrorCodes$2.VALIDATION_ERROR);
return false;
}
if (!Object.values(PageType).includes(config.page_type)) {
this.onError("Invalid page type: ".concat(config.page_type, ". Allowed values are: ").concat(Object.values(PageType).join(', ')), ErrorCodes$2.VALIDATION_ERROR);
return false;
}
return true;
}
}, {
key: "onError",
value: function onError(message, error_code) {
this.eventEmitter.emit(AFTERPAY_ON_SITE_MESSAGING_EVENTS.ON_ERROR, {
error_code: error_code !== null && error_code !== void 0 ? error_code : ErrorCodes$2.SCRIPT_ERROR,
message: message
});
}
}], [{
key: "fromConfig",
value: function fromConfig(eventEmitter, config) {
return new AfterpayOnSiteMessagingService(eventEmitter, config);
}
}]);
}();
/**
* Afterpay On Site Messaging constructor
*
* @param {string} selector - Selector of html element. Container for Afterpay On Site Messaging.
* @param {IAfterpayOnSiteMessagingConfig} config - Required configuration for the Afterpay On Site Messaging.
*
* @example
* var afterpayOnSiteMessaging = new AfterpayOnSiteMessaging('#afterpayButton', config);
*/
var AfterpayOnSiteMessaging = /*#__PURE__*/function () {
/** @constructs */ // constructs added for correct parse classes jsdoc2md
function AfterpayOnSiteMessaging(selector, config) {
_classCallCheck(this, AfterpayOnSiteMessaging);
this.eventEmitter = new EventEmitter();
this.container = new Container(selector);
this.service = AfterpayOnSiteMessagingService.fromConfig(this.eventEmitter, config);
}
/**
* The final method after configuring the AfterpayOnSiteMessaging to
* start the load process.
*/
return _createClass(AfterpayOnSiteMessaging, [{
key: "load",
value: function load() {
try {
this.service.load(this.container);
} catch (err) {
this.eventEmitter.emit(AFTERPAY_ON_SITE_MESSAGING_EVENTS.ON_ERROR, null);
throw err;
}
}
/**
* Callback for onError method.
*
* @callback OnErrorCallback
* @param {unknown|null} data
*/
/**
* If the process fails, the function passed as parameter will be called.
* Important: Do not perform thread blocking operations in callback such as window.alert() calls.
*
* @example
* AfterpayOnSiteMessaging.onError((eventData) => console.log('Some error occur'));
*
* @param {OnErrorCallback} [callback] - Function to be called when there is an error in the flow.
*/
}, {
key: "onError",
value: function onError(callback) {
return this.eventEmitter.subscribe(AFTERPAY_ON_SITE_MESSAGING_EVENTS.ON_ERROR, callback);
}
}]);
}();
var Browser = /*#__PURE__*/function () {
function Browser() {
_classCallCheck(this, Browser);
}
return _createClass(Browser, null, [{
key: "isFacebook",
value: function isFacebook() {
return navigator.userAgent.indexOf('FBSN/iOS') !== -1 && navigator.userAgent.indexOf('AppleWebKit') !== -1 && navigator.userAgent.indexOf('(KHTML, like Gecko)') !== -1;
}
}, {
key: "isInstagram",
value: function isInstagram() {
return navigator.userAgent.indexOf('iOS') !== -1 && navigator.userAgent.indexOf('Instagram') !== -1 && navigator.userAgent.indexOf('(KHTML, like Gecko)') !== -1;
}
}, {
key: "isSupportPopUp",
value: function isSupportPopUp() {
return !Browser.isFacebook() && !Browser.isInstagram();
}
}, {
key: "getLanguage",
value: function getLanguage() {
return window.navigator.language || '';
}
}, {
key: "getTimezoneOffset",
value: function getTimezoneOffset() {
return new Date().getTimezoneOffset();
}
}, {
key: "getBrowserName",
value: function getBrowserName() {
var sUsrAg = navigator.userAgent;
// "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0"
if (sUsrAg.indexOf('Firefox') > -1) return 'Mozilla Firefox';
if (sUsrAg.indexOf('Opera') > -1) return 'Opera';
// "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Zoom 3.6.0; wbx 1.0.0; rv:11.0) like Gecko"
if (sUsrAg.indexOf('Trident') > -1) return 'Microsoft Internet Explorer';
// "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"
if (sUsrAg.indexOf('Edge') > -1) return 'Microsoft Edge';
// "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/66.0.3359.181 Chrome/66.0.3359.181 Safari/537.36"
if (sUsrAg.indexOf('Chrome') > -1) return 'Google Chrome or Chromium';
// "Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1 980x1306"
if (sUsrAg.indexOf('Safari') > -1) return 'Apple Safari';
return 'unknown';
}
}, {
key: "isJavaEnabled",
value: function isJavaEnabled() {
return navigator.javaEnabled();
}
}, {
key: "getAgentUser",
value: function getAgentUser() {
return navigator.userAgent;
}
}, {
key: "getColorDepth",
value: function getColorDepth() {
return screen.colorDepth;
}
}, {
key: "getScreenHeight",
value: function getScreenHeight() {
return screen.height;
}
}, {
key: "getScreenWidth",
value: function getScreenWidth() {
return screen.width;
}
}, {
key: "getBrowserInfo",
value: function getBrowserInfo() {
var ua = navigator.userAgent;
var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
var tem;
if (/trident/i.test(M[1])) {
tem = /\brv[ :](\d+)/.exec(ua) || [];
return {
name: 'IE',
version: tem[1] || ''
};
}
if (M[1] === 'Chrome') {
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
if (tem != null) {
return {
name: tem[1] === 'OPR' ? 'Opera' : 'Edge',
version: tem[2]
};
}
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
// tslint:disable-next-line:no-conditional-assignment
if ((tem = ua.match(/version\/(\d+)/i)) != null) {
M.splice(1, 1, tem[1]);
}
return {
name: M[0],
version: M[1]
};
}
}]);
}();
var PRE_AUTH_CHARGE_LINK = '/v1/charges/3ds';
var ApiCharge = /*#__PURE__*/function () {
function ApiCharge(api) {
_classCallCheck(this, ApiCharge);
this.api = api;
}
/**
* Current method allows to work with charge related endpoints
*
* @example
* api.charge().preAuth('payload', cb);
*
* @param {object} payload - Payload for pre authorization.
* @param {number} payload.amount - Charge amount.
* @param {string} payload.currency - Charge currency.
* @param {string} payload.token - Payment source token.
* @param {string} [payload._3ds.redirect_url] - Redirect url after 3d secure processing.
* @param {listener} [cb]
*/
return _createClass(ApiCharge, [{
key: "preAuth",
value: function preAuth(payload, cb) {
if (typeof cb === 'function') return this.api.getClient('POST', PRE_AUTH_CHARGE_LINK).send(_extends(_extends({}, payload), {
_3ds: _extends(_extends({}, payload._3ds), {
browser_details: {
name: Browser.getBrowserName(),
java_enabled: Browser.isJavaEnabled().toString(),
language: Browser.getLanguage(),
screen_height: Browser.getScreenHeight().toString(),
screen_width: Browser.getScreenWidth().toString(),
time_zone: Browser.getTimezoneOffset().toString(),
color_depth: Browser.getColorDepth().toString()
}
})
}), function (data) {
cb(data);
});
return this.api.getClientPromise('POST', PRE_AUTH_CHARGE_LINK).send(_extends(_extends({}, payload), {
_3ds: _extends(_extends({}, payload._3ds), {
browser_details: {
name: Browser.getBrowserName(),
java_enabled: Browser.isJavaEnabled().toString(),
language: Browser.getLanguage(),
screen_height: Browser.getScreenHeight().toString(),
screen_width: Browser.getScreenWidth().toString(),
time_zone: Browser.getTimezoneOffset().toString(),
color_depth: Browser.getColorDepth().toString()
}
})
}));
}
}]);
}();
var ENV = {
SANDBOX: 'sandbox',
SANDBOX_KOVENA: 'sandbox-kovena',
SANDBOX_DEMO: 'sandbox-demo',
SANDBOX_DEMO_KOVENA: 'sandbox-demo-kovena',
PROD: 'production',
STAGING: 'staging',
STAGING_1: 'staging_1',
STAGING_2: 'staging_2',
STAGING_3: 'staging_3',
STAGING_4: 'staging_4',
STAGING_5: 'staging_5',
STAGING_6: 'staging_6',
STAGING_7: 'staging_7',
STAGING_8: 'staging_8',
STAGING_9: 'staging_9',
STAGING_10: 'staging_10',
STAGING_11: 'staging_11',
STAGING_12: 'staging_12',
STAGING_13: 'staging_13',
STAGING_14: 'staging_14',
STAGING_15: 'staging_15'
};
var WIDGET_URL = [{
env: ENV.SANDBOX,
url: 'https://widget-sandbox.'
}, {
env: ENV.SANDBOX_KOVENA,
url: 'https://widget-sandbox.'
}, {
env: ENV.SANDBOX_DEMO,
url: 'https://widget-sandbox-demo.'
}, {
env: ENV.SANDBOX_DEMO_KOVENA,
url: 'https://widget-sandbox-demo.'
}, {
env: ENV.PROD,
url: 'https://widget.'
}, {
env: ENV.STAGING,
url: 'https://widsta.'
}, {
env: ENV.STAGING_1,
url: 'https://widsta-1.'
}, {
env: ENV.STAGING_2,
url: 'https://widsta-2.'
}, {
env: ENV.STAGING_3,
url: 'https://widsta-3.'
}, {
env: ENV.STAGING_4,
url: 'https://widsta-4.'
}, {
env: ENV.STAGING_5,
url: 'https://widsta-5.'
}, {
env: ENV.STAGING_6,
url: 'https://widsta-6.'
}, {
env: ENV.STAGING_7,
url: 'https://widsta-7.'
}, {
env: ENV.STAGING_8,
url: 'https://widsta-8.'
}, {
env: ENV.STAGING_9,
url: 'https://widsta-9.'
}, {
env: ENV.STAGING_10,
url: 'https://widsta-10.'
}, {
env: ENV.STAGING_11,
url: 'https://widsta-11.'
}, {
env: ENV.STAGING_12,
url: 'https://widsta-12.'
}, {
env: ENV.STAGING_13,
url: 'https://widsta-13.'
}, {
env: ENV.STAGING_14,
url: 'https://widsta-14.'
}, {
env: ENV.STAGING_15,
url: 'https://widsta-15.'
}];
var API_URL = [{
env: ENV.SANDBOX,
url: 'https://api-sandbox.'
}, {
env: ENV.PROD,
url: 'https://api.'
}, {
env: ENV.STAGING,
url: 'https://apista.'
}, {
env: ENV.STAGING_1,
url: 'https://apista-1.'
}, {
env: ENV.STAGING_2,
url: 'https://apista-2.'
}, {
env: ENV.STAGING_3,
url: 'https://apista-3.'
}, {
env: ENV.STAGING_4,
url: 'https://apista-4.'
}, {
env: ENV.STAGING_5,
url: 'https://apista-5.'
}, {
env: ENV.STAGING_6,
url: 'https://apista-6.'
}, {
env: ENV.STAGING_7,
url: 'https://apista-7.'
}, {
env: ENV.STAGING_8,
url: 'https://apista-8.'
}, {
env: ENV.STAGING_9,
url: 'https://apista-9.'
}, {
env: ENV.STAGING_10,
url: 'https://apista-10.'
}, {
env: ENV.STAGING_11,
url: 'https://apista-11.'
}, {
env: ENV.STAGING_12,
url: 'https://apista-12.'
}, {
env: ENV.STAGING_13,
url: 'https://apista-13.'
}, {
env: ENV.STAGING_14,
url: 'https://apista-14.'
}, {
env: ENV.STAGING_15,
url: 'https://apista-15.'
}];
var ADDITIONAL_ENV = [ENV.SANDBOX_KOVENA, ENV.SANDBOX_DEMO_KOVENA];
var REGEX_ALIAS = '^([a-zA-Z0-9](?:(?:[a-zA-Z0-9-.]*(?!-)\\.(?![-.]))*[a-zA-Z0-9]+)?)$';
var DEFAULT_ENV = ENV.SANDBOX;
var DEFAULT_ALIAS = {
PAYDOCK: 'paydock.com',
KOVENA: 'kovena.com'
};
// TODO @ingeniousraccoons we should take advantage of TypeScript mechanism for static environmentId checking and simplified runtime validation
// TODO @ingeniousraccoons unify `environment.paydock.ts` and `environment.cba.ts` making them configuration driven
var Env = /*#__PURE__*/function () {
function Env(configs) {
var defaultEnv = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ENV;
_classCallCheck(this, Env);
this.environmentConfigurations = configs;
this.setEnv(defaultEnv);
}
return _createClass(Env, [{
key: "setEnv",
value: function setEnv(environmentId, alias) {
this.validateAlias(alias);
this.validateEnvironmentId(environmentId);
this.environmentId = environmentId;
if (alias) {
this.alias = alias;
} else if (ADDITIONAL_ENV.includes(this.environmentId)) {
this.alias = DEFAULT_ALIAS.KOVENA;
} else {
this.alias = DEFAULT_ALIAS.PAYDOCK;
}
}
}, {
key: "getEnv",
value: function getEnv() {
return this.environmentId;
}
}, {
key: "getConf",
value: function getConf() {
for (var index in this.environmentConfigurations) {
if (!Object.hasOwn(this.environmentConfigurations, index)) {
continue;
}
if (this.environmentConfigurations[index].env === this.getEnv()) {
return {
url: this.environmentConfigurations[index].url.indexOf('localhost') !== -1 ? this.environmentConfigurations[index].url : this.environmentConfigurations[index].url + this.alias,
env: this.environmentConfigurations[index].env
};
}
}
throw new Error('Env could not obtain configuration. Unknown environmentId.');
}
}, {
key: "validateAlias",
value: function validateAlias(alias) {
if (typeof alias === 'undefined') {
return;
}
if (typeof alias !== 'string') {
throw new TypeError("Env expects parameter 'alias' to be of type 'string' or 'undefined'.");
}
if (!alias.match(REGEX_ALIAS)) {
throw new Error("Env received malformed alias: ".concat(alias, ". Ensure it satisfies the regex: '").concat(REGEX_ALIAS, "'."));
}
}
}, {
key: "validateEnvironmentId",
value: function validateEnvironmentId(environmentId) {
for (var index in this.environmentConfigurations) {
if (!Object.hasOwn(this.environmentConfigurations, index)) {
continue;
}
if (this.environmentConfigurations[index].env === environmentId) {
return;
}
}
throw new TypeError("Env received unknown environmentId: ".concat(environmentId));
}
}]);
}();
var SDK = /*#__PURE__*/function () {
function SDK() {
_classCallCheck(this, SDK);
}
return _createClass(SDK, null, [{
key: "version",
get: function get() {
return SDK._version.trim() || null;
}
}]);
}();
SDK.type = 'client';
SDK.headerKeys = Object.freeze({
version: 'x-sdk-version',
type: 'x-sdk-type'
});
SDK._version = 'v1.142.0';
function isFunction(value) {
return typeof value === 'function';
}
function createErrorClass(createImpl) {
var _super = function (instance) {
Error.call(instance);
instance.stack = new Error().stack;
};
var ctorFunc = createImpl(_super);
ctorFunc.prototype = Object.create(Error.prototype);
ctorFunc.prototype.constructor = ctorFunc;
return ctorFunc;
}
var UnsubscriptionError = createErrorClass(function (_super) {
return function UnsubscriptionErrorImpl(errors) {
_super(this);
this.message = errors
? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
: '';
this.name = 'UnsubscriptionError';
this.errors = errors;
};
});
function arrRemove(arr, item) {
if (arr) {
var index = arr.indexOf(item);
0 <= index && arr.splice(index, 1);
}
}
var Subscription = (function () {
function Subscription(initialTeardown) {
this.initialTeardown = initialTeardown;
this.closed = false;
this._parentage = null;
this._finalizers = null;
}
Subscription.prototype.unsubscribe = function () {
var e_1, _a, e_2, _b;
var errors;
if (!this.closed) {
this.closed = true;
var _parentage = this._parentage;
if (_parentage) {
this._parentage = null;
if (Array.isArray(_parentage)) {
try {
for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
var parent_1 = _parentage_1_1.value;
parent_1.remove(this);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
}
finally { if (e_1) throw e_1.error; }
}
}
else {
_parentage.remove(this);
}
}
var initialFinalizer = this.initialTeardown;
if (isFunction(initialFinalizer)) {
try {
initialFinalizer();
}
catch (e) {
errors = e instanceof UnsubscriptionError ? e.errors : [e];
}
}
var _finalizers = this._finalizers;
if (_finalizers) {
this._finalizers = null;
try {
for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
var finalizer = _finalizers_1_1.value;
try {
execFinalizer(finalizer);
}
catch (err) {
errors = errors !== null && errors !== void 0 ? errors : [];
if (err instanceof UnsubscriptionError) {
errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
}
else {
errors.push(err);
}
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
}
finally { if (e_2) throw e_2.error; }
}
}
if (errors) {
throw new UnsubscriptionError(errors);
}
}
};
Subscription.prototype.add = function (teardown) {
var _a;
if (teardown && teardown !== this) {
if (this.closed) {
execFinalizer(teardown);
}
else {
if (teardown instanceof Subscription) {
if (teardown.closed || teardown._hasParent(this)) {
return;
}
teardown._addParent(this);
}
(this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
}
}
};
Subscription.prototype._hasParent = function (parent) {
var _parentage = this._parentage;
return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
};
Subscription.prototype._addParent = function (parent) {
var _parentage = this._parentage;
this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
};
Subscription.prototype._removeParent = function (parent) {
var _parentage = this._parentage;
if (_parentage === parent) {
this._parentage = null;
}
else if (Array.isArray(_parentage)) {
arrRemove(_parentage, parent);
}
};
Subscription.prototype.remove = function (teardown) {
var _finalizers = this._finalizers;
_finalizers && arrRemove(_finalizers, teardown);
if (teardown instanceof Subscription) {
teardown._removeParent(this);
}
};
Subscription.EMPTY = (function () {
var empty = new Subscription();
empty.closed = true;
return empty;
})();
return Subscription;
}());
var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
function isSubscription(value) {
return (value instanceof Subscription ||
(value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));
}
function execFinalizer(finalizer) {
if (isFunction(finalizer)) {
finalizer();
}
else {
finalizer.unsubscribe();
}
}
var config = {
Promise: undefined};
var timeoutProvider = {
setTimeout: function (handler, timeout) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
},
clearTimeout: function (handle) {
return (clearTimeout)(handle);
},
delegate: undefined,
};
function reportUnhandledError(err) {
timeoutProvider.setTimeout(function () {
{
throw err;
}
});
}
function noop() { }
function errorContext(cb) {
{
cb();
}
}
var Subscriber = (function (_super) {
__extends(Subscriber, _super);
function Subscriber(destination) {
var _this = _super.call(this) || this;
_this.isStopped = false;
if (destination) {
_this.destination = destination;
if (isSubscription(destination)) {
destination.add(_this);
}
}
else {
_this.destination = EMPTY_OBSERVER;
}
return _this;
}
Subscriber.create = function (next, error, complete) {
return new SafeSubscriber(next, error, complete);
};
Subscriber.prototype.next = function (value) {
if (this.isStopped) ;
else {
this._next(value);
}
};
Subscriber.prototype.error = function (err) {
if (this.isStopped) ;
else {
this.isStopped = true;
this._error(err);
}
};
Subscriber.prototype.complete = function () {
if (this.isStopped) ;
else {
this.isStopped = true;
this._complete();
}
};
Subscriber.prototype.unsubscribe = function () {
if (!this.closed) {
this.isStopped = true;
_super.prototype.unsubscribe.call(this);
this.destination = null;
}
};
Subscriber.prototype._next = function (value) {
this.destination.next(value);
};
Subscriber.prototype._error = function (err) {
try {
this.destination.error(err);
}
finally {
this.unsubscribe();
}
};
Subscriber.prototype._complete = function () {
try {
this.destination.complete();
}
finally {
this.unsubscribe();
}
};
return Subscriber;
}(Subscription));
var ConsumerObserver = (function () {
function ConsumerObserver(partialObserver) {
this.partialObserver = partialObserver;
}
ConsumerObserver.prototype.next = function (value) {
var partialObserver = this.partialObserver;
if (partialObserver.next) {
try {
partialObserver.next(value);
}
catch (error) {
handleUnhandledError(error);
}
}
};
ConsumerObserver.prototype.error = function (err) {
var partialObserver = this.partialObserver;
if (partialObserver.error) {
try {
partialObserver.error(err);
}
catch (error) {