2025-04-09 18:55:14 +08:00

1441 lines
77 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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); }
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; }
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; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
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); }
/**
* Copyright (c) 2022 International Business Group, Ant Group. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, and/or distribute the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* 1. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE; and
* 2. If applicable, the use of the Software is also subject to the terms and conditions of any non-disclosure agreement signed by you and the relevant Ant Group entity.
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import { COMPONENTPLUGINID, COMPONENT_CLOSE_BLOCK_ID, COMPONENT_CONTAINER_ID, COMPONENT_RETENTION_ID, COMPONENT_SECTION_ID, ERRORMESSAGE, EVENT, LISTENER_PREFIX, LOADING_ID, LOADTIME_LIMIT, MOCKUP_ID, POPUP_LOADTIME_LOG_LIMIT, TIMEOUT_WEB_APP_HEART_BEAT, TIME_DELAY_SEND_HEART_BEAT } from "../../constant";
import { queryPaymentInfo, submitPayInfo } from "../../service";
import { componentSignEnum, eventCodeEnum, messageName, platformEnum, productSceneEnum, RedirectType, renderDisplayTypeEnum, targetEnum } from "../../types";
import { getType, isJsonString, isPC } from "../../util";
import { isLocalMock } from "../../util/mock";
import { createIframe, getAppDomain, getIframeUrl } from "./cashierApp";
import { addInlineLoading, createInlineBaseElement } from "./component.inline.style";
import { addPopupLoading, createBaseElement, createMockup, createRetentionPopup, handleDeclareInfo as _handleDeclareInfo, hideRetentionPopup, removeRetentionPopup as _removeRetentionPopup } from "./component.popup.style";
import { createModal, destroyModal, insertStyleSheet } from "./popupWindow.style";
window.changingPageHeight = window.innerHeight;
var ComponentApp = /*#__PURE__*/function () {
function ComponentApp() {
_classCallCheck(this, ComponentApp);
_defineProperty(this, "app", void 0);
_defineProperty(this, "AMSSDK", void 0);
_defineProperty(this, "platform", void 0);
_defineProperty(this, "_performanceData", []);
_defineProperty(this, "_loadAppPromiseResolve", null);
_defineProperty(this, "_isInitComponent", void 0);
_defineProperty(this, "_globalData", void 0);
_defineProperty(this, "popupApp", void 0);
_defineProperty(this, "appDomain", void 0);
_defineProperty(this, "createIframeNode", void 0);
_defineProperty(this, "_selector", void 0);
_defineProperty(this, "_appVersion", void 0);
_defineProperty(this, "_isRetention", void 0);
_defineProperty(this, "_actionQueryPromise", null);
_defineProperty(this, "_actionSubmitPromise", null);
_defineProperty(this, "_renderParams", null);
_defineProperty(this, "_componentSign", componentSignEnum.NONE);
_defineProperty(this, "_appLocationSearch", void 0);
_defineProperty(this, "_renderDisplayType", renderDisplayTypeEnum.popup);
_defineProperty(this, "_multipleCallbackEvents", void 0);
_defineProperty(this, "_merchantAppointParam", void 0);
_defineProperty(this, "_webAppHeartBeatTimeoutId", void 0);
_defineProperty(this, "_webAppHeartBeatTimeoutFn", void 0);
this._appVersion = '1.9.0';
this._isInitComponent = false;
this._selector = "#".concat(COMPONENT_SECTION_ID);
this.createIframeNode = function () {
return Promise.resolve();
};
this.platform = isPC() ? platformEnum.desktop : platformEnum.mobile;
this._isRetention = true;
this._appLocationSearch = '';
this._performanceData.push({
key: 'sdk_init',
value: Date.now()
});
this._globalData = new Map();
}
/**
* @description Cancel listening and destroy the dom
*/
_createClass(ComponentApp, [{
key: "logoutPlugin",
value: function logoutPlugin() {
this.cleanContainer(true);
}
/**
* @description When SDK registers plug-ins, it is a required function to receive SDK instances
*/
}, {
key: "applyPlugin",
value: function applyPlugin(AMSSDK) {
this.AMSSDK = AMSSDK;
this.subscribeFromSDK();
}
}, {
key: "initLoggerMeta",
value: function initLoggerMeta() {
var _this$_renderParams, _paymentSessionMetaDa, _this$_renderParams2;
var paymentSessionMetaData = (_this$_renderParams = this._renderParams) === null || _this$_renderParams === void 0 ? void 0 : _this$_renderParams.paymentSessionMetaData;
var paymentSessionConfig = paymentSessionMetaData.paymentSessionConfig;
this.AMSSDK.logger.setMedta({
platform: this.platform === platformEnum.desktop ? 'PC' : 'WAP',
// PC/WAP,
sdkVersion: this._appVersion,
instanceId: this.AMSSDK._instanceId,
storageId: this.AMSSDK._storageId,
// the better way to use md5 paymentSesionID
renderDisplayType: paymentSessionMetaData === null || paymentSessionMetaData === void 0 ? void 0 : paymentSessionMetaData.renderDisplayType,
merchantId: paymentSessionMetaData === null || paymentSessionMetaData === void 0 ? void 0 : paymentSessionMetaData.clientId,
productScene: paymentSessionConfig === null || paymentSessionConfig === void 0 ? void 0 : paymentSessionConfig.productScene,
productSceneVersion: paymentSessionConfig === null || paymentSessionConfig === void 0 ? void 0 : paymentSessionConfig.productSceneVersion,
paymentMethodType: paymentSessionMetaData === null || paymentSessionMetaData === void 0 || (_paymentSessionMetaDa = paymentSessionMetaData.paymentMethodInfoView) === null || _paymentSessionMetaDa === void 0 ? void 0 : _paymentSessionMetaDa.paymentMethodType,
paymentMethodCategoryType: paymentSessionConfig === null || paymentSessionConfig === void 0 ? void 0 : paymentSessionConfig.paymentMethodCategoryType,
requestSeq: (_this$_renderParams2 = this._renderParams) === null || _this$_renderParams2 === void 0 ? void 0 : _this$_renderParams2.paymentSessionData
});
this.AMSSDK.logger.setComponentStartTime(Date.now());
}
/**
* @description Set the rendering capability of the cashier plug-in. Different technology stacks have some differences in the packaging and use of rendering functions
*/
}, {
key: "setRender",
value: function setRender(renderFunc) {
this.createIframeNode = renderFunc;
}
}, {
key: "initSecurity",
value: function initSecurity() {
var _this$_renderParams3,
_this = this;
var product = (_this$_renderParams3 = this._renderParams) === null || _this$_renderParams3 === void 0 || (_this$_renderParams3 = _this$_renderParams3.paymentSessionMetaData) === null || _this$_renderParams3 === void 0 || (_this$_renderParams3 = _this$_renderParams3.paymentSessionConfig) === null || _this$_renderParams3 === void 0 ? void 0 : _this$_renderParams3.productScene;
if (componentSignEnum.CASHIER_PAYMENT_APM === this._componentSign) return;
if (componentSignEnum.CASHIER_PAYMENT_BANK === this._componentSign) {
this.AMSSDK.logger.logInfo({
title: 'sdk_event_security_unneeded_scenarios'
}, {
product: product
});
}
var securitySDK = this.AMSSDK._getSecuritySDKByProductScene({
product: product
});
if (!securitySDK) {
this.AMSSDK.logger.logInfo({
title: 'sdk_event_securitySdkInit'
});
this.AMSSDK._newSecuritySDKByScene({
product: product
}, function () {
_this.AMSSDK.logger.logInfo({
title: 'sdk_event_securitySdkInitSuccess'
});
}, function () {
_this.AMSSDK.logger.logError({
title: 'sdk_error_securitySdkInitFailed'
}, {
sign: 'SDK internal initialization'
});
});
}
}
}, {
key: "logDeviceId",
value: function logDeviceId(deviceId, getDeviceIdStartTime) {
var time = "".concat(Date.now() - getDeviceIdStartTime);
if (deviceId) {
this.AMSSDK.logger.logInfo({
title: 'sdk_event_securitySdkGetTokenSuccess'
}, {
deviceId: deviceId,
time: time
}).send();
} else {
this.AMSSDK.logger.logInfo({
title: 'sdk_error_securitySdkGetTokenFailed'
}, {
deviceId: deviceId,
time: time
}).send();
}
}
}, {
key: "getDeviceIdAndLog",
value: function getDeviceIdAndLog() {
var _this2 = this;
var deviceIdParameter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var isPolling = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return new Promise(function (resolve) {
// To avoid rendering being blocked, move the logic to the next event loop for processing
setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var _this2$_renderParams;
var productScene, getDeviceIdStartTime, securitySDK, deviceId;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
productScene = (_this2$_renderParams = _this2._renderParams) === null || _this2$_renderParams === void 0 || (_this2$_renderParams = _this2$_renderParams.paymentSessionMetaData) === null || _this2$_renderParams === void 0 || (_this2$_renderParams = _this2$_renderParams.paymentSessionConfig) === null || _this2$_renderParams === void 0 ? void 0 : _this2$_renderParams.productScene;
getDeviceIdStartTime = Date.now();
securitySDK = _this2.AMSSDK._getSecuritySDKByProductScene({
product: (deviceIdParameter === null || deviceIdParameter === void 0 ? void 0 : deviceIdParameter.productScene) || productScene
});
deviceId = '';
if (!securitySDK) {
_context.next = 16;
break;
}
if (!(isPolling && parseInt(deviceIdParameter === null || deviceIdParameter === void 0 ? void 0 : deviceIdParameter.tokenCollectTime) > 0)) {
_context.next = 11;
break;
}
_context.next = 8;
return securitySDK.pollingGetApdidToken(deviceIdParameter);
case 8:
_context.t0 = _context.sent;
_context.next = 14;
break;
case 11:
_context.next = 13;
return securitySDK.getApdidToken();
case 13:
_context.t0 = _context.sent;
case 14:
deviceId = _context.t0;
_this2.logDeviceId(deviceId, getDeviceIdStartTime);
case 16:
resolve(deviceId);
case 17:
case "end":
return _context.stop();
}
}, _callee);
})), 0);
});
}
/**
* @description render iframe content
*/
}, {
key: "appendIframeNodes",
value: function appendIframeNodes(componentSign, renderParams) {
var _renderParams,
_this3 = this;
if (this._isInitComponent) {
this.dispatchToSDK(EVENT.error.name, ERRORMESSAGE.CREATECOMPONENT_ERROR.SINGLETON_COMPONENT_ERROR);
return Promise.reject(ERRORMESSAGE.CREATECOMPONENT_ERROR.SINGLETON_COMPONENT_ERROR);
}
renderParams = this.setParameterDefaultValues(componentSign, renderParams);
this._isInitComponent = true;
this._renderParams = renderParams;
this._componentSign = componentSign;
if ((_renderParams = renderParams) !== null && _renderParams !== void 0 && _renderParams.selector) this._selector = renderParams.selector;
this._renderDisplayType = renderParams.renderDisplayType;
this._merchantAppointParam = renderParams.merchantAppointParam;
var insertedNode = this._renderDisplayType === renderDisplayTypeEnum.inline ? "#".concat(COMPONENT_CONTAINER_ID) : this._selector;
this.initLoggerMeta();
this.initSecurity();
this._performanceData.push({
key: 'sdk_create_component',
value: Date.now()
});
this.dispatchToSDK(EVENT.eventCallback.name, {
code: eventCodeEnum.SDK_START_OF_LOADING
});
if (this._renderDisplayType === renderDisplayTypeEnum.inline) {
var container = createInlineBaseElement(this._selector);
if (container) this.renderInlineLoading(renderParams, container);
insertStyleSheet();
}
if (this._renderDisplayType === renderDisplayTypeEnum.popup) {
createBaseElement(this.platform, this.closeBtnFunc.bind(this));
createRetentionPopup(this.platform, this.hideRetentionPopupFunc.bind(this), this.retentionPopupLeaveFunc.bind(this));
createMockup();
this.renderPopupLoading(renderParams);
}
this.createApp(renderParams);
return Promise.all([this.createActionQueryPromise(), this.createSubmitPromise(), this.createIframeNode(this, insertedNode, this._renderDisplayType), this._createLoadAppPromise()]).then(function () {
return Promise.resolve();
}).catch(function (error) {
_this3.AMSSDK.logger.logError({
title: 'sdk_error_created_app_process_failed'
}).send();
_this3._isInitComponent = false;
_this3.cleanContainer();
return Promise.reject(error);
});
}
}, {
key: "setParameterDefaultValues",
value: function setParameterDefaultValues(componentSign, renderParams) {
var newParams = Object.assign({}, renderParams);
if (componentSign === componentSignEnum.VAULTING_CARD) {
var _newParams$notRedirec;
newParams.notRedirectAfterComplete = (_newParams$notRedirec = newParams === null || newParams === void 0 ? void 0 : newParams.notRedirectAfterComplete) !== null && _newParams$notRedirec !== void 0 ? _newParams$notRedirec : true;
}
return newParams;
}
}, {
key: "renderInlineLoading",
value: function renderInlineLoading(renderParams, selector) {
var _renderParams$appeara;
var showLoading = renderParams === null || renderParams === void 0 || (_renderParams$appeara = renderParams.appearance) === null || _renderParams$appeara === void 0 ? void 0 : _renderParams$appeara.showLoading;
showLoading = typeof showLoading === 'boolean' ? showLoading : true;
if (showLoading) addInlineLoading(selector, this.platform);
}
}, {
key: "renderPopupLoading",
value: function renderPopupLoading(renderParams) {
var _renderParams$appeara2;
var showLoading = renderParams === null || renderParams === void 0 || (_renderParams$appeara2 = renderParams.appearance) === null || _renderParams$appeara2 === void 0 ? void 0 : _renderParams$appeara2.showLoading;
showLoading = typeof showLoading === 'boolean' ? showLoading : true;
if (!showLoading) return;
var mockup = document.getElementById(MOCKUP_ID);
if (mockup) mockup.style.display = 'block';
addPopupLoading();
}
}, {
key: "_createLoadAppPromise",
value: function _createLoadAppPromise(loadTimeLimit) {
var _this4 = this;
return new Promise(function (resolve, reject) {
_this4._loadAppPromiseResolve = resolve;
setTimeout(function () {
reject(ERRORMESSAGE.CREATECOMPONENT_ERROR.LOAD_APP_TIMEOUT);
}, loadTimeLimit !== null && loadTimeLimit !== void 0 ? loadTimeLimit : LOADTIME_LIMIT);
}).catch(function (error) {
_this4.dispatchToSDK(EVENT.error.name, ERRORMESSAGE.CREATECOMPONENT_ERROR.LOAD_APP_TIMEOUT);
_this4.AMSSDK.logger.logError({
title: 'sdk_error_web_app_timeout'
}).send();
return Promise.reject(error);
});
}
/**
* @description Interface request
*/
}, {
key: "createActionQueryPromise",
value: function createActionQueryPromise() {
var _this5 = this;
this._performanceData.push({
key: 'sdk_action_query_start',
value: Date.now()
});
// eslint-disable-next-line no-async-promise-executor
this._actionQueryPromise = new Promise( /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(resolve, reject) {
var _this5$_renderParams, _this5$_renderParams2, _this5$_renderParams3, _this5$_renderParams4;
var envInfo, params, _this5$_renderParams5, _ref3, _ref3$productSceneVer, productSceneVersion, _ref3$productScene, productScene, _ref4, _ref4$action, _ref4$action2, _ref4$action2$autoDeb, autoDebitWithToken, _this5$_renderParams6, _action$web, _action$wap, action, signType;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
envInfo = {
locale: _this5.AMSSDK.options.locale
};
params = {
paymentSessionData: _this5._renderParams && ((_this5$_renderParams = _this5._renderParams) === null || _this5$_renderParams === void 0 ? void 0 : _this5$_renderParams.sessionData) || '',
paymentSessionConfig: (_this5$_renderParams2 = _this5._renderParams) === null || _this5$_renderParams2 === void 0 || (_this5$_renderParams2 = _this5$_renderParams2.paymentSessionMetaData) === null || _this5$_renderParams2 === void 0 ? void 0 : _this5$_renderParams2.paymentSessionConfig,
notRedirectAfterComplete: ((_this5$_renderParams3 = _this5._renderParams) === null || _this5$_renderParams3 === void 0 ? void 0 : _this5$_renderParams3.notRedirectAfterComplete) === true,
merchantAppointParam: _this5._merchantAppointParam
};
/**
* @description Simulated or unnecessary scenarios
*/
if (!(isLocalMock() || (_this5$_renderParams4 = _this5._renderParams) !== null && _this5$_renderParams4 !== void 0 && (_this5$_renderParams4 = _this5$_renderParams4.paymentSessionMetaData) !== null && _this5$_renderParams4 !== void 0 && (_this5$_renderParams4 = _this5$_renderParams4.action) !== null && _this5$_renderParams4 !== void 0 && _this5$_renderParams4.skipSdkQuery)) {
_context2.next = 4;
break;
}
return _context2.abrupt("return", resolve({
message: 'sdk no need to make query request',
success: true
}));
case 4:
if (!(componentSignEnum.CASHIER_PAYMENT_CARD === _this5._componentSign || componentSignEnum.VAULTING_CARD === _this5._componentSign)) {
_context2.next = 10;
break;
}
params.paymentMethodType = 'CARD';
_context2.next = 8;
return _this5.getDeviceIdAndLog();
case 8:
envInfo.deviceId = _context2.sent;
if (window.navigator.userAgent.indexOf('miniProgram') > -1) {
envInfo.extendInfo = {
WAP_SUB_TYPE: 'WECHAT_MINI_PROGRAM'
};
}
case 10:
if (!(componentSignEnum.EASY_PAY_WALLET === _this5._componentSign)) {
_context2.next = 18;
break;
}
_ref3 = params.paymentSessionConfig || {}, _ref3$productSceneVer = _ref3.productSceneVersion, productSceneVersion = _ref3$productSceneVer === void 0 ? '' : _ref3$productSceneVer, _ref3$productScene = _ref3.productScene, productScene = _ref3$productScene === void 0 ? '' : _ref3$productScene;
_ref4 = ((_this5$_renderParams5 = _this5._renderParams) === null || _this5$_renderParams5 === void 0 ? void 0 : _this5$_renderParams5.paymentSessionMetaData) || {}, _ref4$action = _ref4.action, _ref4$action2 = _ref4$action === void 0 ? {} : _ref4$action, _ref4$action2$autoDeb = _ref4$action2.autoDebitWithToken, autoDebitWithToken = _ref4$action2$autoDeb === void 0 ? false : _ref4$action2$autoDeb;
if (!(productScene === productSceneEnum.EASY_PAY && productSceneVersion === '2.0' && !autoDebitWithToken)) {
_context2.next = 15;
break;
}
return _context2.abrupt("return", resolve({
message: 'sdk no need to make query request',
success: true
}));
case 15:
_context2.next = 17;
return _this5.getDeviceIdAndLog();
case 17:
envInfo.deviceId = _context2.sent;
case 18:
if (!(componentSignEnum.AUTO_DEBIT_WALLET === _this5._componentSign)) {
_context2.next = 28;
break;
}
action = ((_this5$_renderParams6 = _this5._renderParams) === null || _this5$_renderParams6 === void 0 || (_this5$_renderParams6 = _this5$_renderParams6.paymentSessionMetaData) === null || _this5$_renderParams6 === void 0 ? void 0 : _this5$_renderParams6.action) || {};
signType = isPC() ? action === null || action === void 0 || (_action$web = action.web) === null || _action$web === void 0 ? void 0 : _action$web.signType : action === null || action === void 0 || (_action$wap = action.wap) === null || _action$wap === void 0 ? void 0 : _action$wap.signType;
if (!(signType === 'SMS')) {
_context2.next = 23;
break;
}
return _context2.abrupt("return", resolve({
message: 'sdk no need to make query request',
success: true
}));
case 23:
if (!(!signType || signType !== 'REDIRECT')) {
_context2.next = 25;
break;
}
return _context2.abrupt("return", resolve({
success: false
}));
case 25:
_context2.next = 27;
return _this5.getDeviceIdAndLog();
case 27:
envInfo.deviceId = _context2.sent;
case 28:
_this5.AMSSDK.logger.logInfo({
title: 'sdk_event_sdkQuery'
}, {
paymentSessionConfig: JSON.stringify(params.paymentSessionConfig)
}).send();
queryPaymentInfo(params, {
env: _this5.AMSSDK.options.env.environment,
envInfo: envInfo
}, _this5.AMSSDK.logger).then(function (res) {
_this5._performanceData.push({
key: 'sdk_action_query_end',
value: Date.now()
});
if (res !== null && res !== void 0 && res.success) {
resolve(res);
} else {
resolve(res);
}
}).catch(function (err) {
if ([componentSignEnum.CASHIER_PAYMENT_CARD, componentSignEnum.VAULTING_CARD, componentSignEnum.CASHIER_PAYMENT_APM].includes(_this5._componentSign)) {
return resolve({
success: false
});
}
_this5.dispatchToSDK(EVENT.error.name, {
code: ERRORMESSAGE.CREATECOMPONENT_ERROR.code
});
reject(err);
}).finally(function () {
_this5.AMSSDK.logger.logInfo({
title: 'sdk_event_sdkQueryEnd'
}, {
paymentSessionConfig: JSON.stringify(params.paymentSessionConfig)
}).send();
});
case 30:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return function (_x, _x2) {
return _ref2.apply(this, arguments);
};
}());
return this._actionQueryPromise;
}
}, {
key: "createSubmitPromise",
value: function createSubmitPromise() {
var _this$_renderParams4,
_this$_renderParams5,
_this6 = this;
this._performanceData.push({
key: 'sdk_submit_start',
value: Date.now()
});
var params = {
paymentSessionData: this._renderParams && ((_this$_renderParams4 = this._renderParams) === null || _this$_renderParams4 === void 0 ? void 0 : _this$_renderParams4.sessionData) || '',
paymentSessionConfig: (_this$_renderParams5 = this._renderParams) === null || _this$_renderParams5 === void 0 || (_this$_renderParams5 = _this$_renderParams5.paymentSessionMetaData) === null || _this$_renderParams5 === void 0 ? void 0 : _this$_renderParams5.paymentSessionConfig
};
// eslint-disable-next-line no-async-promise-executor
this._actionSubmitPromise = new Promise( /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(resolve) {
var _this6$_renderParams;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
if (!(!((_this6$_renderParams = _this6._renderParams) !== null && _this6$_renderParams !== void 0 && (_this6$_renderParams = _this6$_renderParams.paymentSessionMetaData) !== null && _this6$_renderParams !== void 0 && (_this6$_renderParams = _this6$_renderParams.action) !== null && _this6$_renderParams !== void 0 && _this6$_renderParams.skipSdkQuery) || componentSignEnum.EASY_PAY_WALLET !== _this6._componentSign)) {
_context3.next = 2;
break;
}
return _context3.abrupt("return", resolve({
message: 'sdk no need to make submitPay request',
success: true
}));
case 2:
_this6.AMSSDK.logger.logInfo({
title: 'sdk_event_submitPay'
}, {
paymentSessionConfig: JSON.stringify(params.paymentSessionConfig)
}).send();
_context3.t0 = submitPayInfo;
_context3.t1 = params;
_context3.t2 = _this6.AMSSDK.options.env.environment;
_context3.next = 8;
return _this6.getDeviceIdAndLog();
case 8:
_context3.t3 = _context3.sent;
_context3.t4 = {
deviceId: _context3.t3
};
_context3.t5 = {
env: _context3.t2,
timeout: 15000,
envInfo: _context3.t4
};
_context3.t6 = _this6.AMSSDK.logger;
(0, _context3.t0)(_context3.t1, _context3.t5, _context3.t6).then(function (res) {
_this6._performanceData.push({
key: 'sdk_submit_end',
value: Date.now()
});
if (res !== null && res !== void 0 && res.success) {
resolve(res);
} else {
resolve(res);
}
}).catch(function () {
resolve({
success: false
});
}).finally(function () {
_this6.AMSSDK.logger.logInfo({
title: 'sdk_event_submitPayEnd'
}, {
paymentSessionConfig: JSON.stringify(params.paymentSessionConfig)
}).send();
});
case 13:
case "end":
return _context3.stop();
}
}, _callee3);
}));
return function (_x3) {
return _ref5.apply(this, arguments);
};
}());
}
}, {
key: "cleanElement",
value: function cleanElement() {
try {
var _document$getElementB;
// selector and container
if (getType(this._selector) === 'string') {
var selectorDom = document.querySelector(this._selector);
if (selectorDom) selectorDom.innerHTML = '';
}
var container = document.getElementById(COMPONENT_CONTAINER_ID);
if (container) container === null || container === void 0 || container.remove();
// animation
(_document$getElementB = document.getElementById("".concat(COMPONENT_CONTAINER_ID, "-").concat(this.platform, "-animation-style"))) === null || _document$getElementB === void 0 || _document$getElementB.remove();
// mockup
var body = document.getElementsByTagName('body')[0];
body.style.overflow = 'auto';
var mockup = document.getElementById(MOCKUP_ID);
mockup === null || mockup === void 0 || mockup.remove();
// retentionPopup
this.removeRetentionPopup(this.platform);
// listener
this.removeEventListener();
} catch (error) {
console.error(error);
}
}
/**
* @description Create app
*/
}, {
key: "createApp",
value: function createApp(renderParams) {
if (!!window.postMessage !== true) {
this.dispatchToSDK(EVENT.error.name, ERRORMESSAGE.SDK_COMPATIBILITY_ISSUES.BROWSER_NOT_SUPPORT_POSTMESSAGE);
return;
}
this._performanceData.push({
key: 'sdk_popup_start',
value: Date.now()
});
try {
var _renderParams$payment, _renderParams$payment2;
var productSceneVersion = (renderParams === null || renderParams === void 0 || (_renderParams$payment = renderParams.paymentSessionMetaData) === null || _renderParams$payment === void 0 || (_renderParams$payment = _renderParams$payment.paymentSessionConfig) === null || _renderParams$payment === void 0 ? void 0 : _renderParams$payment.productSceneVersion) || '';
var extendInfo = (renderParams === null || renderParams === void 0 || (_renderParams$payment2 = renderParams.paymentSessionMetaData) === null || _renderParams$payment2 === void 0 ? void 0 : _renderParams$payment2.extendInfo) || '';
var environment = this.AMSSDK.options.env.environment;
this.appDomain = getAppDomain({
environment: environment,
appVersion: this._appVersion,
componentSign: this._componentSign,
productSceneVersion: productSceneVersion,
extendInfo: extendInfo
});
this.app = createIframe(this.AMSSDK.options.mode, this.platform);
var _getIframeUrl = getIframeUrl({
renderDisplayType: renderParams.renderDisplayType,
componentSign: this._componentSign,
analytics: this.AMSSDK.options.analytics,
productSceneVersion: productSceneVersion,
environment: environment,
appVersion: this._appVersion,
extendInfo: extendInfo,
locale: this.AMSSDK.options.locale,
instanceId: this.AMSSDK._instanceId
}),
path = _getIframeUrl.path,
locationSearch = _getIframeUrl.locationSearch;
this._appLocationSearch = locationSearch;
this.app.src = "".concat(path, "?").concat(locationSearch);
// Subscribe to messages from iframe
this.addEventListener();
} catch (error) {
this.AMSSDK.logger.logError({
title: 'sdk_error_created_app_failed'
}).send();
this.dispatchToSDK(EVENT.error.name, Object.assign({}, ERRORMESSAGE.SDK_COMPATIBILITY_ISSUES.FAILED_TO_CREATE_IFRAME, {
stack: error
}));
}
}
}, {
key: "listener",
value: function listener(e) {
if (e.origin !== this.appDomain) return;
var isJson = isJsonString(e.data);
if (isJson) {
var data = JSON.parse(e.data);
if (data.name !== messageName.APP_TO_SDK && data.name !== messageName.APP_TO_APP || data.instanceId !== this.AMSSDK._instanceId) return;
this._handleAppMessage(data);
} else {
console.warn(ERRORMESSAGE.NOT_JSON_FORMAT);
this.dispatchToSDK(EVENT.error.name, ERRORMESSAGE.NOT_JSON_FORMAT);
}
}
}, {
key: "resizeListener",
value: function resizeListener(e) {
var _e$target, _e$target2;
var cashier = document.getElementById(COMPONENT_CONTAINER_ID);
cashier.style.transition = 'none';
this.dispatchToApp({
context: {
event: 'renderResize',
data: {
heightOfVisible: (e === null || e === void 0 || (_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.innerHeight) || window.innerHeight,
widthOfVisible: (e === null || e === void 0 || (_e$target2 = e.target) === null || _e$target2 === void 0 ? void 0 : _e$target2.innerWidth) || window.innerWidth
}
}
});
}
}, {
key: "createDialog",
value: function () {
var _createDialog = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(data) {
var pageUrl, isLoad, timeout, logTimeout;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
pageUrl = data.url.includes('?') ? "".concat(data.url, "&").concat(this._appLocationSearch) : "".concat(data.url, "?").concat(this._appLocationSearch);
_context4.prev = 1;
isLoad = false;
_context4.next = 5;
return createModal({
widthPadding: data === null || data === void 0 ? void 0 : data.widthPadding,
heightPadding: data === null || data === void 0 ? void 0 : data.heightPadding,
device: this.platform,
url: pageUrl
});
case 5:
this.popupApp = _context4.sent;
timeout = setTimeout(function () {
if (isLoad) return;
throw {
title: 'sdk_error_create_pop_up'
};
}, LOADTIME_LIMIT);
logTimeout = setTimeout(function () {
if (isLoad) return;
throw {
title: 'sdk_error_pop_up_time_out'
};
}, POPUP_LOADTIME_LOG_LIMIT);
this.popupApp.onload = function () {
isLoad = true;
clearTimeout(timeout);
clearTimeout(logTimeout);
};
_context4.next = 15;
break;
case 11:
_context4.prev = 11;
_context4.t0 = _context4["catch"](1);
this.AMSSDK.logger.logError({
title: (_context4.t0 === null || _context4.t0 === void 0 ? void 0 : _context4.t0.title) || 'sdk_error_create_pop_up'
}, {
message: _context4.t0 === null || _context4.t0 === void 0 ? void 0 : _context4.t0.message,
url: pageUrl
});
this.dispatchToSDK(EVENT.error.name, ERRORMESSAGE.CREATECOMPONENT_ERROR.LOAD_APP_TIMEOUT);
case 15:
case "end":
return _context4.stop();
}
}, _callee4, this, [[1, 11]]);
}));
function createDialog(_x4) {
return _createDialog.apply(this, arguments);
}
return createDialog;
}()
}, {
key: "getDeviceIdAndCallback",
value: function () {
var _getDeviceIdAndCallback = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(eventContext) {
var deviceId;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
if (!(eventContext !== null && eventContext !== void 0 && eventContext.eventCallbackId)) {
_context5.next = 5;
break;
}
_context5.next = 3;
return this.getDeviceIdAndLog(eventContext === null || eventContext === void 0 ? void 0 : eventContext.data, true);
case 3:
deviceId = _context5.sent;
this.dispatchToApp({
context: {
event: 'appEventCallback',
eventCallbackId: eventContext === null || eventContext === void 0 ? void 0 : eventContext.eventCallbackId,
data: {
deviceId: deviceId
}
}
});
case 5:
case "end":
return _context5.stop();
}
}, _callee5, this);
}));
function getDeviceIdAndCallback(_x5) {
return _getDeviceIdAndCallback.apply(this, arguments);
}
return getDeviceIdAndCallback;
}()
}, {
key: "getUserAgentAndCallback",
value: function () {
var _getUserAgentAndCallback = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(eventContext) {
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
if (eventContext !== null && eventContext !== void 0 && eventContext.eventCallbackId) {
try {
this.dispatchToApp({
context: {
event: 'appEventCallback',
eventCallbackId: eventContext === null || eventContext === void 0 ? void 0 : eventContext.eventCallbackId,
data: {
userAgent: window.navigator.userAgent
}
}
});
} catch (error) {
/* empty */
}
}
case 1:
case "end":
return _context6.stop();
}
}, _callee6, this);
}));
function getUserAgentAndCallback(_x6) {
return _getUserAgentAndCallback.apply(this, arguments);
}
return getUserAgentAndCallback;
}()
}, {
key: "returnDataAndCallback",
value: function () {
var _returnDataAndCallback = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(eventContext) {
var _eventContext$data, targetData;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
if (eventContext !== null && eventContext !== void 0 && eventContext.eventCallbackId) {
targetData = this._globalData.get((_eventContext$data = eventContext.data) === null || _eventContext$data === void 0 ? void 0 : _eventContext$data.dataKey);
this.dispatchToApp({
context: {
event: 'appEventCallback',
eventCallbackId: eventContext === null || eventContext === void 0 ? void 0 : eventContext.eventCallbackId,
data: targetData
}
});
}
case 1:
case "end":
return _context7.stop();
}
}, _callee7, this);
}));
function returnDataAndCallback(_x7) {
return _returnDataAndCallback.apply(this, arguments);
}
return returnDataAndCallback;
}()
/**
* @description Initialize subscription iframe message
*/
}, {
key: "addEventListener",
value: function addEventListener() {
this.removeEventListener();
window["".concat(LISTENER_PREFIX, "_").concat(this.AMSSDK._instanceId)] = this.listener.bind(this);
window["".concat(LISTENER_PREFIX, "_").concat(this.AMSSDK._instanceId, "_resize")] = this.resizeListener.bind(this);
window.addEventListener('message', window["".concat(LISTENER_PREFIX, "_").concat(this.AMSSDK._instanceId)]);
window.addEventListener('resize', window["".concat(LISTENER_PREFIX, "_").concat(this.AMSSDK._instanceId, "_resize")]);
}
}, {
key: "removeEventListener",
value: function removeEventListener() {
window.removeEventListener('message', window["".concat(LISTENER_PREFIX, "_").concat(this.AMSSDK._instanceId)]);
window.removeEventListener('resize', window["".concat(LISTENER_PREFIX, "_").concat(this.AMSSDK._instanceId, "_resize")]);
}
/**
* @description Processing messages from iframe
*/
}, {
key: "_handleAppMessage",
value: function _handleAppMessage(data) {
var eventKeyMap = Object.keys(EVENT).map(function (key) {
return EVENT[key].name;
});
if (!eventKeyMap.includes(data.context.event)) {
return;
}
if (data.context.event === EVENT.getDeviceId.name) {
this.getDeviceIdAndCallback(data.context);
return;
}
if (data.context.event === EVENT.getUserAgentFromSdk.name) {
this.getUserAgentAndCallback(data.context);
return;
}
if (data.context.event === EVENT.popWindow.name) {
destroyModal();
return;
}
if (data.context.event === EVENT.getGlobalData.name) {
this.returnDataAndCallback(data.context);
return;
}
if (data.context.event === EVENT.setGlobalData.name) {
var _data$context$data, _data$context$data2;
this._globalData.set((_data$context$data = data.context.data) === null || _data$context$data === void 0 ? void 0 : _data$context$data.dataKey, (_data$context$data2 = data.context.data) === null || _data$context$data2 === void 0 ? void 0 : _data$context$data2.data);
return;
}
if (data.context.event === EVENT.popupWindow.name) {
var _data$context;
this.createDialog((_data$context = data.context) === null || _data$context === void 0 ? void 0 : _data$context.data);
return;
}
if (data.context.event === EVENT.sendMuitiAppEventToSdk.name) {
this.dispatchToApp({
context: {
event: 'receiveMuitiAppFromSdk',
data: data.context.data
}
});
return;
}
if (data.context.event === EVENT.dismissLoading.name) {
var _data$context$data3;
this.dismissLoadingFunc(false);
this.dispatchToSDK(EVENT.eventCallback.name, {
code: 'SDK_END_OF_LOADING',
message: ((_data$context$data3 = data.context.data) === null || _data$context$data3 === void 0 ? void 0 : _data$context$data3.message) || ''
});
return;
}
if (data.context.event === EVENT.launch.name) {
this._performanceData.push({
key: 'sdk_onLaunch',
value: Date.now()
});
this.AMSSDK.logger.logInfo({
title: 'sdk_event_webAppOnLaunch'
}).send();
this._loadAppPromiseResolve && this._loadAppPromiseResolve(true);
this.sendRenderEvent();
return;
}
if (data.context.event === EVENT.sizeChanged.name) {
this.handleSizeChanged(data);
}
if (data.context.event === EVENT.close.name) {
return this.closeBtnFunc();
}
if (data.context.event === EVENT.redirect.name) {
return this.handleRedirect(data.context.data);
}
if (data.context.event === EVENT.submitForm.name) {
this.submitForm(data.context.data);
return;
}
if (data.context.event === EVENT.hideCloseButton.name) {
this.handleCloseBtnShow(false);
return;
}
if (data.context.event === EVENT.showCloseButton.name) {
this.handleCloseBtnShow(true);
return;
}
if (data.context.event === EVENT.setAllowRetention.name) {
if (data.context.data === true) this._isRetention = true;
if (data.context.data === false) this._isRetention = false;
return;
}
if (data.context.event === EVENT.declareCheckoutInfo.name) {
this.handleDeclareInfo(data.context.data);
return;
}
if (data.context.event === EVENT.declareEventCallbackInfo.name) {
this._multipleCallbackEvents = data.context.data;
return;
}
if (data.context.event === EVENT.appHeartBeat.name) {
this.handleAppHeartBeat();
return;
}
if (data.context.event === EVENT.eventCallback.name) {
this.AMSSDK.logger.logInfo({
title: 'sdk_event_event_callback'
}).send();
}
// The plug-in communicates with the sdk after processing
this.dispatchToSDK(data.context.event, data.context.data, data.context.eventCallbackId);
}
}, {
key: "dismissLoadingFunc",
value: function dismissLoadingFunc() {
var _document$getElementB2;
var isShowMockup = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
var mockup = document.getElementById(MOCKUP_ID);
if (mockup) {
mockup.style.background = 'rgb(0, 0, 0, 0.6)';
mockup.style.display = isShowMockup ? 'block' : 'none';
}
(_document$getElementB2 = document.getElementById(LOADING_ID)) === null || _document$getElementB2 === void 0 || _document$getElementB2.remove();
}
}, {
key: "handleSizeChanged",
value: function handleSizeChanged(data) {
var _data$context$data4;
var cashier = document.getElementById(COMPONENT_CONTAINER_ID);
if (((_data$context$data4 = data.context.data) === null || _data$context$data4 === void 0 ? void 0 : _data$context$data4.height) <= 1 || data.context.data.height === parseInt(cashier.style.height)) return;
cashier.style.height = "".concat(data.context.data.height, "px");
this.app.style.opacity = '1';
if (this._renderDisplayType === renderDisplayTypeEnum.popup) {
if (this.platform === 'desktop') {
if (data.context.data.width) cashier.style.width = "".concat(data.context.data.width, "px");
cashier.classList.add("".concat(COMPONENT_CONTAINER_ID, "-").concat(this.platform, "-animation"));
this.app.style.height = "".concat(data.context.data.height, "px");
}
if (this.platform === 'mobile') {
cashier.classList.add("".concat(COMPONENT_CONTAINER_ID, "-").concat(this.platform, "-animation"));
var animationStyleId = "".concat(COMPONENT_CONTAINER_ID, "-").concat(this.platform, "-animation-style");
var animationStyle = document.getElementById(animationStyleId);
if (animationStyle) animationStyle === null || animationStyle === void 0 || animationStyle.remove();
// 此style用于弹窗出现和高度变化时动画动画不同属性不同
this.app.style.height = parseInt(this.app.style.height) > 0 ? '100%' : "".concat(data.context.data.height, "px");
// 弹出和弹入动画
var runkeyframes = "@keyframes ".concat(COMPONENT_CONTAINER_ID, "-slide-in {\n 0% {\n height: 1px;\n }\n 100% {\n height: ").concat(data.context.data.height, "px;\n }\n }\n @keyframes ").concat(COMPONENT_CONTAINER_ID, "-slide-out {\n 0% {\n height: ").concat(data.context.data.height, "px;\n opacity: 1;\n }\n 50% {\n opacity: 1;\n }\n 100% {\n height: 1px;\n opacity: 0;\n }\n }");
// 创建style标签
var style = document.createElement('style');
style.id = animationStyleId;
// 设置style属性
style.type = 'text/css';
// 将 keyframes样式写入style内
style.innerHTML = runkeyframes;
// 将style样式存放到head标签
document.getElementsByTagName('head')[0].appendChild(style);
// size变动时动画
setTimeout(function () {
cashier.style.transition = 'height 0.28s ease-in-out';
}, 500);
}
// 关闭loading保留蒙层
this.dismissLoadingFunc();
}
if (this._renderDisplayType === renderDisplayTypeEnum.inline) {
var _document$getElementB3;
(_document$getElementB3 = document.getElementById(LOADING_ID)) === null || _document$getElementB3 === void 0 || _document$getElementB3.remove();
this.app.style.height = "".concat(data.context.data.height, "px");
}
}
}, {
key: "handleRedirect",
value: function handleRedirect(data) {
var _data$isDestroy,
_this7 = this;
var _data = typeof data === 'string' ? {
normalUrl: data
} : _objectSpread(_objectSpread({}, data), {}, {
applinkUrl: (data === null || data === void 0 ? void 0 : data.applinkUrl) || '',
schemeUrl: (data === null || data === void 0 ? void 0 : data.schemeUrl) || '',
normalUrl: (data === null || data === void 0 ? void 0 : data.normalUrl) || '',
target: data === null || data === void 0 ? void 0 : data.target,
isDestroy: (_data$isDestroy = data === null || data === void 0 ? void 0 : data.isDestroy) !== null && _data$isDestroy !== void 0 ? _data$isDestroy : true
});
this.AMSSDK.logger.logInfo({
title: 'sdk_event_call_url_start'
}, _objectSpread({}, data)).send();
var successCallback = function successCallback(type, url) {
_this7.dispatchToSDK(EVENT.eventCallback.name, {
code: eventCodeEnum.SDK_CALL_URL_SUCCESS,
message: "Successfully opened the app,".concat(type, ": ").concat(url)
});
_this7.AMSSDK.logger.logInfo({
title: 'sdk_event_call_url_success'
}, {
redirectInfo: JSON.stringify(_data),
openType: type,
url: url
}).send();
};
var failCallback = function failCallback(type, url) {
_this7.dispatchToSDK(EVENT.eventCallback.name, {
code: eventCodeEnum.SDK_CALL_URL_ERROR,
message: "Failed to open app,applinkUrl: ".concat(_data === null || _data === void 0 ? void 0 : _data.applinkUrl, " schemeUrl: ").concat(_data === null || _data === void 0 ? void 0 : _data.schemeUrl, " normalUrl: ").concat(_data === null || _data === void 0 ? void 0 : _data.normalUrl)
});
_this7.AMSSDK.logger.logInfo({
title: 'sdk_error_call_url_failed'
}, {
redirectInfo: JSON.stringify(_data),
openType: type,
url: url
}).send();
};
// 支持 target: _blank新开tab页打开
if (_data.target === targetEnum.BLANK) {
if (!_data.normalUrl) return failCallback(RedirectType.NormalUrl, '');
successCallback(RedirectType.NormalUrl, _data.normalUrl);
window.open(_data.normalUrl);
return;
}
if (_data.target === targetEnum.REPLACE && !(_data !== null && _data !== void 0 && _data.applinkUrl) && !(_data !== null && _data !== void 0 && _data.schemeUrl)) {
if (!_data.normalUrl) return failCallback(RedirectType.NormalUrl, '');
successCallback(RedirectType.NormalUrl, _data.normalUrl);
window.location.replace(_data.normalUrl);
return;
}
// 销毁iframe和全局loading
if (_data !== null && _data !== void 0 && _data.isDestroy) this.cleanContainer();
this.AMSSDK._redirect({
applinkUrl: _data === null || _data === void 0 ? void 0 : _data.applinkUrl
}).then(function () {
successCallback(RedirectType.ApplinkUrl, _data === null || _data === void 0 ? void 0 : _data.applinkUrl);
}).catch(function () {
if (_data !== null && _data !== void 0 && _data.applinkUrl) failCallback(RedirectType.ApplinkUrl, _data === null || _data === void 0 ? void 0 : _data.applinkUrl);
return _this7.AMSSDK._redirect({
schemeUrl: _data === null || _data === void 0 ? void 0 : _data.schemeUrl
});
}).then(function () {
successCallback(RedirectType.SchemeUrl, _data === null || _data === void 0 ? void 0 : _data.schemeUrl);
}).catch(function () {
if (_data !== null && _data !== void 0 && _data.schemeUrl) failCallback(RedirectType.SchemeUrl, _data === null || _data === void 0 ? void 0 : _data.schemeUrl);
return _this7.AMSSDK._redirect({
normalUrl: _data === null || _data === void 0 ? void 0 : _data.normalUrl
});
}).then(function () {
successCallback(RedirectType.NormalUrl, _data === null || _data === void 0 ? void 0 : _data.normalUrl);
}).catch(function () {
failCallback(RedirectType.NormalUrl, _data === null || _data === void 0 ? void 0 : _data.normalUrl);
});
}
}, {
key: "handleDeclareInfo",
value: function handleDeclareInfo(_ref6) {
var _ref6$closeDialogData = _ref6.closeDialogData,
closeDialogData = _ref6$closeDialogData === void 0 ? {} : _ref6$closeDialogData;
_handleDeclareInfo({
closeDialogData: closeDialogData
});
}
}, {
key: "handleDeclarePopWindowCallback",
value: function handleDeclarePopWindowCallback() {
var eventInfoName = 'popWindowEventInfo';
if (this._multipleCallbackEvents && eventInfoName in this._multipleCallbackEvents) {
var eventInfo = this._multipleCallbackEvents[eventInfoName];
if (eventInfo.enableCallback) {
this.dispatchToSDK(EVENT.eventCallback.name, {
code: eventInfo.eventName,
result: {
result: eventInfo.eventResult || {}
}
});
}
} else {
console.log("not valid ".concat(eventInfoName, " in "), this._multipleCallbackEvents);
}
}
}, {
key: "handleAppHeartBeat",
value: function handleAppHeartBeat() {
var _this8 = this;
try {
if (!this._webAppHeartBeatTimeoutFn) {
this._webAppHeartBeatTimeoutFn = function () {
if (_this8.isAppAttached()) {
_this8.AMSSDK.logger.logError({
title: 'sdk_error_appHeartBeatTimeout'
});
}
};
}
if (this._webAppHeartBeatTimeoutId) {
clearTimeout(this._webAppHeartBeatTimeoutId);
this._webAppHeartBeatTimeoutId = null;
}
if (this._webAppHeartBeatTimeoutFn) {
this._webAppHeartBeatTimeoutId = setTimeout(this._webAppHeartBeatTimeoutFn, TIMEOUT_WEB_APP_HEART_BEAT);
}
setTimeout(function () {
if (_this8.isAppAttached()) {
_this8.dispatchToApp({
context: {
event: 'sdkHeartBeat',
data: {}
}
});
}
}, TIME_DELAY_SEND_HEART_BEAT);
} catch (error) {
this.AMSSDK.logger.logError({
title: 'sdk_error_handleAppHeartBeat'
}, {
errorMessage: error.message
});
}
}
}, {
key: "isAppAttached",
value: function isAppAttached() {
return this.app || this.popupApp;
}
}, {
key: "isWindowVisible",
value: function isWindowVisible() {
var _document;
return ((_document = document) === null || _document === void 0 ? void 0 : _document.visibilityState) === 'visible';
}
}, {
key: "handleCloseBtnShow",
value: function handleCloseBtnShow(showClose) {
var closeBlock = document.getElementById(COMPONENT_CLOSE_BLOCK_ID);
if (showClose) {
closeBlock === null || closeBlock === void 0 || closeBlock.classList.remove("".concat(COMPONENT_CLOSE_BLOCK_ID, "-hidden"));
} else if (showClose === false) {
closeBlock === null || closeBlock === void 0 || closeBlock.classList.add("".concat(COMPONENT_CLOSE_BLOCK_ID, "-hidden"));
}
}
/**
* @description Send message to SDK
*/
}, {
key: "dispatchToSDK",
value: function dispatchToSDK(event, data, eventCallbackId) {
this.AMSSDK._eventCenter.emit(event, data);
if (eventCallbackId) this.AMSSDK._eventCenter.emit(eventCallbackId, data);
}
/**
* @description Send message to iframe
*/
}, {
key: "dispatchToApp",
value: function dispatchToApp(payload) {
var targetElement = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var data = Object.assign({}, payload, {
name: messageName.SDK_TO_APP,
mode: this.AMSSDK.options.mode,
appId: COMPONENTPLUGINID,
instanceId: this.AMSSDK._instanceId
});
this.AMSSDK.logger.logInfo({
title: 'sdk_event_send_message_to_web'
}, {
event: data === null || data === void 0 ? void 0 : data.context.event
}).send();
if (targetElement && targetElement.contentWindow) {
return targetElement.contentWindow.postMessage(JSON.stringify(data), '*');
}
if (this.app || this.popupApp) {
var _this$app, _this$app2, _this$popupApp, _this$popupApp2;
(this === null || this === void 0 || (_this$app = this.app) === null || _this$app === void 0 ? void 0 : _this$app.contentWindow) && (this === null || this === void 0 || (_this$app2 = this.app) === null || _this$app2 === void 0 ? void 0 : _this$app2.contentWindow.postMessage(JSON.stringify(data), this.appDomain));
(this === null || this === void 0 || (_this$popupApp = this.popupApp) === null || _this$popupApp === void 0 ? void 0 : _this$popupApp.contentWindow) && (this === null || this === void 0 || (_this$popupApp2 = this.popupApp) === null || _this$popupApp2 === void 0 ? void 0 : _this$popupApp2.contentWindow.postMessage(JSON.stringify(data), '*'));
return;
}
throw new Error(ERRORMESSAGE.SDK_SUBMIT_ERROR.message);
}
/**
* @description Subscribe to messages from SDK
*/
}, {
key: "subscribeFromSDK",
value: function subscribeFromSDK() {
var eventKeyMap = {};
for (var key in eventKeyMap) {
// eslint-disable-next-line no-prototype-builtins
if (eventKeyMap.hasOwnProperty(key)) {
this.AMSSDK._eventCenter.on("".concat(COMPONENTPLUGINID, "-").concat(key), eventKeyMap[key].bind(this));
}
}
}
/**
* @description Send rendering events to iframe
*/
}, {
key: "sendRenderEvent",
value: (function () {
var _sendRenderEvent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
var _this$_renderParams6, _this$_renderParams7, _this$_renderParams8, _this$_renderParams9, _this$_renderParams10, res, submitRes;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
_context8.prev = 0;
if (!(!this._actionQueryPromise || !this._actionSubmitPromise)) {
_context8.next = 3;
break;
}
return _context8.abrupt("return");
case 3:
_context8.next = 5;
return this._actionQueryPromise;
case 5:
res = _context8.sent;
_context8.next = 8;
return this._actionSubmitPromise;
case 8:
submitRes = _context8.sent;
this._performanceData.push({
key: 'sdk_render_component',
value: Date.now()
});
this.dispatchToApp({
context: {
event: 'renderComponent',
data: {
queryResult: res,
submitResult: submitRes,
sessionResult: (_this$_renderParams6 = this._renderParams) === null || _this$_renderParams6 === void 0 ? void 0 : _this$_renderParams6.paymentSessionMetaData,
paymentSessionData: (_this$_renderParams7 = this._renderParams) === null || _this$_renderParams7 === void 0 ? void 0 : _this$_renderParams7.sessionData,
heightOfVisible: Math.max(window.changingPageHeight, window.innerHeight),
renderDisplayType: (_this$_renderParams8 = this._renderParams) === null || _this$_renderParams8 === void 0 ? void 0 : _this$_renderParams8.renderDisplayType,
appearance: (_this$_renderParams9 = this._renderParams) === null || _this$_renderParams9 === void 0 ? void 0 : _this$_renderParams9.appearance,
notRedirectAfterComplete: ((_this$_renderParams10 = this._renderParams) === null || _this$_renderParams10 === void 0 ? void 0 : _this$_renderParams10.notRedirectAfterComplete) === true,
merchantAppointParam: this._merchantAppointParam,
envInfo: {
screenHeight: screen.height,
screenWidth: screen.width
}
}
}
});
this.AMSSDK.logger.logInfo({
title: 'sdk_event_renderComponent'
});
this.dispatchToApp({
context: {
event: 'web-sdk-performance',
data: {
performanceData: this._performanceData
}
}
});
// eslint-disable-next-line no-empty
_context8.next = 17;
break;
case 15:
_context8.prev = 15;
_context8.t0 = _context8["catch"](0);
case 17:
case "end":
return _context8.stop();
}
}, _callee8, this, [[0, 15]]);
}));
function sendRenderEvent() {
return _sendRenderEvent.apply(this, arguments);
}
return sendRenderEvent;
}()
/**
* @description close cashier
*/
)
}, {
key: "cleanContainer",
value: function cleanContainer() {
var _document$getElementB4,
_this9 = this;
var immediately = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
this.AMSSDK.logger.logInfo({
title: 'sdk_event_clean_component'
}).send();
(_document$getElementB4 = document.getElementById(LOADING_ID)) === null || _document$getElementB4 === void 0 || _document$getElementB4.remove();
this.hideComponentAnimation();
var mockup = document.getElementById(MOCKUP_ID);
mockup === null || mockup === void 0 || mockup.classList.add("".concat(MOCKUP_ID, "-hidden"));
this._loadAppPromiseResolve && this._loadAppPromiseResolve(true);
this._performanceData = [];
this._isInitComponent = false;
this.app = null;
if (immediately) this.cleanElement();else {
setTimeout(function () {
_this9.cleanElement();
}, 300);
}
}
}, {
key: "hideComponentAnimation",
value: function hideComponentAnimation() {
var container = document.getElementById(COMPONENT_CONTAINER_ID);
if (this.app) this.app.style.height = container.style.height;
if (container) {
// size变化动画取消
container.style.transition = '';
container === null || container === void 0 || container.classList.remove("".concat(COMPONENT_CONTAINER_ID, "-").concat(this.platform));
container === null || container === void 0 || container.classList.remove("".concat(COMPONENT_CONTAINER_ID, "-").concat(this.platform, "-animation"));
container === null || container === void 0 || container.classList.add("".concat(COMPONENT_CONTAINER_ID, "-hidden-").concat(this.platform));
}
}
}, {
key: "closeBtnFunc",
value: function closeBtnFunc() {
// element && element.removeEventListener()
if (this._isRetention) this.showRetentionPopup();else {
this.cleanContainer();
this.dispatchToSDK(EVENT.close.name, {});
this.handleDeclarePopWindowCallback();
}
}
}, {
key: "retentionPopupLeaveFunc",
value: function retentionPopupLeaveFunc() {
this.dispatchToSDK(EVENT.close.name, {});
this.hideRetentionPopupFunc();
this.cleanContainer();
this.handleDeclarePopWindowCallback();
}
}, {
key: "removeRetentionPopup",
value: function removeRetentionPopup(platform) {
_removeRetentionPopup(platform, this.hideRetentionPopupFunc.bind(this), this.retentionPopupLeaveFunc.bind(this));
}
}, {
key: "showRetentionPopup",
value: function showRetentionPopup() {
var retentionPopup = document.getElementById(COMPONENT_RETENTION_ID);
var container = document.getElementById(COMPONENT_CONTAINER_ID);
if (retentionPopup) {
container === null || container === void 0 || container.classList.add("".concat(COMPONENT_CONTAINER_ID, "-opacity"));
retentionPopup.classList.remove("".concat(COMPONENT_RETENTION_ID, "-hidden"));
retentionPopup.classList.add("".concat(COMPONENT_RETENTION_ID, "-show"));
}
}
}, {
key: "hideRetentionPopupFunc",
value: function hideRetentionPopupFunc() {
hideRetentionPopup();
}
}, {
key: "submitForm",
value: function submitForm(data) {
var attributes = data.attributes;
var _document2 = document,
body = _document2.body;
var form = document.createElement('form');
form.setAttribute('height', '1');
form.setAttribute('width', '1');
Object.keys(attributes.data).forEach(function (key) {
var input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', key);
input.setAttribute('value', attributes.data[key]);
form.appendChild(input);
});
form.setAttribute('action', attributes.action);
form.setAttribute('method', 'post');
body.appendChild(form);
setTimeout(function () {
form.submit();
}, 0);
}
}]);
return ComponentApp;
}();
export { ComponentApp as default };