UNPKG

@trap_stevo/merchtide

Version:

Empowering the future of digital commerce, this API delivers the ultimate solution for building and managing online superstores. Seamlessly integrating product management, payment processing, and order tracking, it offers unmatched flexibility and scalabi

847 lines (844 loc) 124 kB
"use strict"; function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } 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 _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(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 = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw 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 _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 _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 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 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 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 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 _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : 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); } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } 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 _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } 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: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } 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); } var EventEmitter = require("events"); var _require = require("./HUDManagers/UniversalUtilityManager"), validEmail = _require.validEmail, cleanData = _require.cleanData; var PaymentUtilityManager = require("./HUDManagers/PaymentUtilityManager"); var PayCoreManager = require("./HUDManagers/PayCoreManager"); var ProductManager = require("./HUDManagers/ProductManager"); var OrderManager = require("./HUDManagers/OrderManager"); function deepMerge(target) { for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } for (var _i = 0, _sources = sources; _i < _sources.length; _i++) { var src = _sources[_i]; if (!src || _typeof(src) !== "object") { continue; } for (var _i2 = 0, _Object$keys = Object.keys(src); _i2 < _Object$keys.length; _i2++) { var key = _Object$keys[_i2]; var v = src[key]; if (v && _typeof(v) === "object" && !Array.isArray(v)) { if (!target[key] || _typeof(target[key]) !== "object" || Array.isArray(target[key])) { target[key] = {}; } deepMerge(target[key], v); } else { target[key] = v; } } } return target; } ; function buildProcessorPayload(coreName, base) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, passthrough = _ref.passthrough, override = _ref.override; var extra = passthrough && (passthrough[coreName] || passthrough) || {}; var baseClone = deepMerge({}, base); if (override === true) { return deepMerge({}, baseClone, extra); } return deepMerge({}, extra, baseClone); } ; function pickRequestOptions(coreName, options) { if (!options || _typeof(options) !== "object") { return undefined; } return options[coreName] || options; } ; var MerchTide = /*#__PURE__*/function (_EventEmitter) { function MerchTide() { var _this; _classCallCheck(this, MerchTide); _this = _callSuper(this, MerchTide); _this.purchUtilities = PaymentUtilityManager; _this.productManager = ProductManager; _this.orderManager = OrderManager; _this.payCoreManager = PayCoreManager; return _this; } // --- Payment Processor Management --- _inherits(MerchTide, _EventEmitter); return _createClass(MerchTide, [{ key: "initializePayCore", value: function initializePayCore(name, config) { return this.payCoreManager.initializePayCore(name, config); } }, { key: "getPayCore", value: function getPayCore(name) { return this.payCoreManager.getPayCore(name); } // --- Product ↔ PayCore Registration Management --- }, { key: "registerProductWithPayCore", value: function () { var _registerProductWithPayCore = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(coreName, productID, priceDetails) { var additionalDetails, core, product, registeredProduct, registeredPrice, _existingProducts$dat, _existingPrices$data, existingProducts, existingPrices, priceData, updatedProduct, _args = arguments; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: additionalDetails = _args.length > 3 && _args[3] !== undefined ? _args[3] : {}; core = this.payCoreManager.getPayCore(coreName); if (core) { _context.next = 4; break; } throw new Error("Payment core '".concat(coreName, "' not initialized.")); case 4: product = this.productManager.getProductByID(productID); if (product) { _context.next = 7; break; } throw new Error("Product not found."); case 7: if (!(product["".concat(coreName, "ProductID")] && product["".concat(coreName, "PriceID")])) { _context.next = 9; break; } return _context.abrupt("return", product); case 9: _context.t0 = coreName.toLowerCase(); _context.next = _context.t0 === "stripe" ? 12 : _context.t0 === "paypal" ? 33 : 40; break; case 12: _context.next = 14; return core.products.search({ query: "name:'".concat(product.name, "'") }); case 14: existingProducts = _context.sent; if (!((existingProducts === null || existingProducts === void 0 || (_existingProducts$dat = existingProducts.data) === null || _existingProducts$dat === void 0 ? void 0 : _existingProducts$dat.length) > 0)) { _context.next = 19; break; } registeredProduct = existingProducts.data[0]; _context.next = 22; break; case 19: _context.next = 21; return core.products.create(_objectSpread({ name: product.name, description: product.description }, additionalDetails)); case 21: registeredProduct = _context.sent; case 22: _context.next = 24; return core.prices.list({ product: registeredProduct.id, active: true }); case 24: existingPrices = _context.sent; if ((existingPrices === null || existingPrices === void 0 || (_existingPrices$data = existingPrices.data) === null || _existingPrices$data === void 0 ? void 0 : _existingPrices$data.length) > 0) { registeredPrice = existingPrices.data.find(function (p) { return p.unit_amount === priceDetails.unitAmount && p.currency === (priceDetails.currency || "usd") && JSON.stringify(p.recurring) === JSON.stringify(priceDetails.recurring || null); }); } if (registeredPrice) { _context.next = 32; break; } priceData = { unit_amount: priceDetails.unitAmount, currency: priceDetails.currency || "usd", product: registeredProduct.id }; if (priceDetails.recurring) { priceData.recurring = priceDetails.recurring; } _context.next = 31; return core.prices.create(priceData); case 31: registeredPrice = _context.sent; case 32: return _context.abrupt("break", 41); case 33: _context.next = 35; return core.createProduct(_objectSpread({ name: product.name, description: product.description }, additionalDetails)); case 35: registeredProduct = _context.sent; _context.next = 38; return core.createPlan({ billing_cycles: priceDetails.recurring || null, currency: priceDetails.currency || "usd", amount: priceDetails.unitAmount / 100, product_id: registeredProduct.id }); case 38: registeredPrice = _context.sent; return _context.abrupt("break", 41); case 40: throw new Error("Unsupported payment core '".concat(coreName, "'.")); case 41: updatedProduct = this.productManager.updateProduct(productID, _defineProperty(_defineProperty({}, "".concat(coreName, "ProductID"), registeredProduct.id), "".concat(coreName, "PriceID"), registeredPrice.id)); this.emit("product-registered", updatedProduct); return _context.abrupt("return", updatedProduct); case 44: case "end": return _context.stop(); } }, _callee, this); })); function registerProductWithPayCore(_x, _x2, _x3) { return _registerProductWithPayCore.apply(this, arguments); } return registerProductWithPayCore; }() }, { key: "updateProductPricingInPayCore", value: function () { var _updateProductPricingInPayCore = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(coreName, productID, newPriceDetails) { var core, product, updatedPrice, productUpdatedPricing, updatedProduct; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: core = this.payCoreManager.getPayCore(coreName); if (core) { _context2.next = 3; break; } throw new Error("Payment core '".concat(coreName, "' not initialized.")); case 3: product = this.productManager.getProductByID(productID); if (product) { _context2.next = 6; break; } throw new Error("Product not found."); case 6: _context2.t0 = coreName.toLowerCase(); _context2.next = _context2.t0 === "stripe" ? 9 : _context2.t0 === "paypal" ? 21 : 27; break; case 9: if (product.stripeProductID) { _context2.next = 11; break; } throw new Error("Product not registered with Stripe."); case 11: productUpdatedPricing = { unit_amount: newPriceDetails.unitAmount, currency: newPriceDetails.currency || "usd", product: product.stripeProductID }; if (newPriceDetails.recurring) { productUpdatedPricing.recurring = newPriceDetails.recurring; } _context2.next = 15; return core.prices.create(productUpdatedPricing); case 15: updatedPrice = _context2.sent; if (!product.stripePriceID) { _context2.next = 19; break; } _context2.next = 19; return core.prices.update(product.stripePriceID, { active: false }); case 19: product.stripePriceID = updatedPrice.id; return _context2.abrupt("break", 28); case 21: if (product.paypalPlanID) { _context2.next = 23; break; } throw new Error("Product not registered with PayPal."); case 23: _context2.next = 25; return core.plans.update(product.paypalPlanID, { billing_cycles: newPriceDetails.recurring || null, currency_code: newPriceDetails.currency || "usd", amount: (newPriceDetails.unitAmount / 100).toFixed(2) }); case 25: updatedPrice = _context2.sent; return _context2.abrupt("break", 28); case 27: throw new Error("Unsupported payment core '".concat(coreName, "'.")); case 28: updatedProduct = this.productManager.updateProduct(productID, _defineProperty({}, "".concat(coreName, "PriceID"), updatedPrice.id)); this.emit("product-price-updated", updatedProduct); return _context2.abrupt("return", updatedProduct); case 31: case "end": return _context2.stop(); } }, _callee2, this); })); function updateProductPricingInPayCore(_x4, _x5, _x6) { return _updateProductPricingInPayCore.apply(this, arguments); } return updateProductPricingInPayCore; }() // --- Payment Runner Management --- }, { key: "processPaymentWithCore", value: function () { var _processPaymentWithCore = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(core, coreName, paymentData) { var eventID, paymentEventDetails, paymentProcessedDetails, result, base, paymentMethodType, billing, _paymentData$automati, _paymentData$automati2, payload, req, finalAmount, purchaseUnit, _base, _payload, _req, _args3 = arguments; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: eventID = _args3.length > 3 && _args3[3] !== undefined ? _args3[3] : "payment-created"; paymentEventDetails = _args3.length > 4 && _args3[4] !== undefined ? _args3[4] : {}; paymentProcessedDetails = _args3.length > 5 && _args3[5] !== undefined ? _args3[5] : {}; if (core) { _context3.next = 5; break; } throw new Error("Payment core '".concat(coreName, "' not initialized.")); case 5: _context3.t0 = coreName.toLowerCase(); _context3.next = _context3.t0 === "stripe" ? 8 : _context3.t0 === "paypal" ? 19 : 29; break; case 8: base = { currency: paymentData.currencySymbol || "usd", amount: paymentData.finalAmount, metadata: paymentData.metadata || {}, confirm: true }; if (paymentData.receiptEmail && validEmail(paymentData.receiptEmail)) { base.receipt_email = paymentData.receiptEmail; } if (paymentData.payment_method && paymentData.payment_method.startsWith("pm_")) { base.payment_method = paymentData.payment_method; if (paymentData.customerID) { base.customer = paymentData.customerID; } } else if (paymentData.payment_method) { paymentMethodType = paymentData.paymentMethodType || "card"; billing = paymentData.billingAddress ? { name: paymentData.billingAddress.name, email: paymentData.billingAddress.email, phone: paymentData.billingAddress.phone, address: { line1: paymentData.billingAddress.line1, line2: paymentData.billingAddress.line2, city: paymentData.billingAddress.city, state: paymentData.billingAddress.state, postal_code: paymentData.billingAddress.postalCode, country: paymentData.billingAddress.country } } : undefined; base.payment_method_data = _objectSpread(_objectSpread(_objectSpread({ type: paymentMethodType }, paymentMethodType === "card" ? { card: { number: paymentData.payment_method } } : {}), billing ? { billing_details: billing } : {}), paymentData.paymentMethodDataConfigurations || {}); } if (paymentData.automaticPaymentMethods) { base.automatic_payment_methods = { enabled: (_paymentData$automati = paymentData.automaticPaymentMethods.enabled) !== null && _paymentData$automati !== void 0 ? _paymentData$automati : true, allow_redirects: (_paymentData$automati2 = paymentData.automaticPaymentMethods.allowRedirects) !== null && _paymentData$automati2 !== void 0 ? _paymentData$automati2 : "never", preferred_methods: paymentData.automaticPaymentMethods.preferredMethods || undefined }; } if (paymentData.returnUrl) { base.return_url = paymentData.returnUrl; } payload = buildProcessorPayload("stripe", base, { passthrough: paymentData.passthrough, override: paymentData.override }); req = pickRequestOptions("stripe", paymentData.requestOptions); _context3.next = 17; return core.paymentIntents.create(payload, req); case 17: result = _context3.sent; return _context3.abrupt("break", 30); case 19: finalAmount = paymentData.finalAmount; purchaseUnit = { amount: { currency_code: paymentData.currencySymbol || "USD", value: (finalAmount / 100).toFixed(2) }, custom_id: paymentData.metadata ? JSON.stringify(paymentData.metadata) : undefined }; if (paymentData.billingAddress) { purchaseUnit.shipping = { name: { full_name: paymentData.billingAddress.name }, address: { address_line_1: paymentData.billingAddress.line1 || undefined, address_line_2: paymentData.billingAddress.line2 || undefined, admin_area_2: paymentData.billingAddress.city || undefined, admin_area_1: paymentData.billingAddress.state || undefined, postal_code: paymentData.billingAddress.postalCode || undefined, country_code: paymentData.billingAddress.country || undefined } }; } _base = _objectSpread({ intent: "CAPTURE", purchase_units: [purchaseUnit] }, paymentData.returnUrl && { return_url: paymentData.returnUrl }); _payload = buildProcessorPayload("paypal", _base, { passthrough: paymentData.passthrough, override: paymentData.override }); _req = pickRequestOptions("paypal", paymentData.requestOptions); _context3.next = 27; return core.orders.create(_payload, _req); case 27: result = _context3.sent; return _context3.abrupt("break", 30); case 29: throw new Error("Unsupported payment core '".concat(coreName, "'.")); case 30: this.emit(eventID, _objectSpread({ coreName: coreName, paymentData: paymentData, result: result }, paymentEventDetails || {})); return _context3.abrupt("return", _objectSpread({ paymentDetails: result, totalPaid: paymentData.finalAmount }, paymentProcessedDetails || {})); case 32: case "end": return _context3.stop(); } }, _callee3, this); })); function processPaymentWithCore(_x7, _x8, _x9) { return _processPaymentWithCore.apply(this, arguments); } return processPaymentWithCore; }() // --- Payment Management --- }, { key: "createPayment", value: function () { var _createPayment = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(coreName, data) { var eventID, paymentEventDetails, paymentProcessedDetails, core, product, finalAmount, quantity, subtotal, taxAmount, _args4 = arguments; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: eventID = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : "payment-created"; paymentEventDetails = _args4.length > 3 && _args4[3] !== undefined ? _args4[3] : {}; paymentProcessedDetails = _args4.length > 4 && _args4[4] !== undefined ? _args4[4] : {}; core = this.payCoreManager.getPayCore(coreName); if (core) { _context4.next = 6; break; } throw new Error("Payment core '".concat(coreName, "' not initialized.")); case 6: product = this.productManager.getProductByID(data.productID); if (!(!product || !product.unitPrice)) { _context4.next = 9; break; } throw new Error("Product not found or missing unit price."); case 9: if (!data.quantity) { _context4.next = 16; break; } quantity = data.quantity; taxAmount = data.taxAmount ? PaymentUtilityManager.convertToCents(data.taxAmount, data.currencySymbol || "usd") : 0; subtotal = quantity * product.unitPrice; finalAmount = subtotal + taxAmount; _context4.next = 30; break; case 16: if (!data.amount) { _context4.next = 29; break; } if (!isNaN(data.amount)) { _context4.next = 19; break; } throw new Error("Invalid amount provided."); case 19: taxAmount = data.taxAmount ? PaymentUtilityManager.convertToCents(data.taxAmount, data.currencySymbol || "usd") : 0; subtotal = PaymentUtilityManager.convertToCents(data.amount, data.currencySymbol || "usd"); if (!(subtotal < taxAmount)) { _context4.next = 23; break; } throw new Error("Invalid amount ~ Tax exceeds total payment."); case 23: finalAmount = subtotal + taxAmount; quantity = Math.floor(subtotal / product.unitPrice); if (!(quantity <= 0)) { _context4.next = 27; break; } throw new Error("Invalid amount ~ Not enough to purchase even one unit."); case 27: _context4.next = 30; break; case 29: throw new Error("Must provide an 'amount' or 'quantity' (Usage ~ data.amount or data.quantity)."); case 30: _context4.next = 32; return this.processPaymentWithCore(core, coreName, _objectSpread(_objectSpread({}, data), {}, { finalAmount: finalAmount, payment_method: data.payment_method, currencySymbol: data.currencySymbol, billingAddress: data.billingAddress, automaticPaymentMethods: data.automaticPaymentMethods, returnUrl: data.returnUrl, passthrough: data.passthrough, override: data.override, requestOptions: data.requestOptions }), eventID, _objectSpread({ subtotalPaid: subtotal, totalPaid: finalAmount, taxPaid: taxAmount, quantity: quantity }, paymentEventDetails || {}), _objectSpread({ quantityPurchased: quantity, subtotalPaid: subtotal, taxPaid: taxAmount }, paymentProcessedDetails || {})); case 32: return _context4.abrupt("return", _context4.sent); case 33: case "end": return _context4.stop(); } }, _callee4, this); })); function createPayment(_x10, _x11) { return _createPayment.apply(this, arguments); } return createPayment; }() }, { key: "invokePayment", value: function () { var _invokePayment = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(coreName, data) { var eventID, paymentEventDetails, paymentProcessedDetails, core, finalAmount, taxAmount, totalAmount, product, paymentMetadata, _args5 = arguments; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: eventID = _args5.length > 2 && _args5[2] !== undefined ? _args5[2] : "payment-created"; paymentEventDetails = _args5.length > 3 && _args5[3] !== undefined ? _args5[3] : {}; paymentProcessedDetails = _args5.length > 4 && _args5[4] !== undefined ? _args5[4] : {}; core = this.payCoreManager.getPayCore(coreName); if (core) { _context5.next = 6; break; } throw new Error("Payment core '".concat(coreName, "' not initialized.")); case 6: if (!(!data.amount || isNaN(data.amount) || data.amount <= 0)) { _context5.next = 8; break; } throw new Error("Invalid payment amount."); case 8: finalAmount = PaymentUtilityManager.convertToCents(data.amount, data.currencySymbol || "usd"); taxAmount = data.taxAmount ? PaymentUtilityManager.convertToCents(data.taxAmount, data.currencySymbol || "usd") : 0; totalAmount = finalAmount + taxAmount; product = null; if (!data.productID) { _context5.next = 16; break; } product = this.productManager.getProductByID(data.productID); if (product) { _context5.next = 16; break; } throw new Error("Product ~ ".concat(data.productID, " not found.")); case 16: paymentMetadata = {}; if (product) { paymentMetadata.productID = product.id; paymentMetadata.productName = product.name; paymentMetadata.productDescription = product.description; } _context5.next = 20; return this.processPaymentWithCore(core, coreName, { finalAmount: totalAmount, payment_method: data.payment_method, currencySymbol: data.currencySymbol, billingAddress: data.billingAddress, automaticPaymentMethods: data.automaticPaymentMethods, returnUrl: data.returnUrl, metadata: paymentMetadata, passthrough: data.passthrough, override: data.override, requestOptions: data.requestOptions }, eventID, _objectSpread({ subtotalPaid: finalAmount, totalPaid: totalAmount, taxPaid: taxAmount }, paymentEventDetails || {}), _objectSpread({ quantityPurchased: data.quantity || 1, subtotalPaid: finalAmount, taxPaid: taxAmount }, paymentProcessedDetails || {})); case 20: return _context5.abrupt("return", _context5.sent); case 21: case "end": return _context5.stop(); } }, _callee5, this); })); function invokePayment(_x12, _x13) { return _invokePayment.apply(this, arguments); } return invokePayment; }() }, { key: "createRefund", value: function () { var _createRefund = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(coreName, data) { var core, result, payload, req, _payload2, _req2; return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: core = this.payCoreManager.getPayCore(coreName); if (core) { _context6.next = 3; break; } throw new Error("Payment core '".concat(coreName, "' not initialized.")); case 3: _context6.t0 = coreName.toLowerCase(); _context6.next = _context6.t0 === "stripe" ? 6 : _context6.t0 === "paypal" ? 12 : 18; break; case 6: payload = buildProcessorPayload("stripe", data, { passthrough: data.passthrough, override: data.override }); req = pickRequestOptions("stripe", data.requestOptions); _context6.next = 10; return core.refunds.create(payload, req); case 10: result = _context6.sent; return _context6.abrupt("break", 19); case 12: _payload2 = buildProcessorPayload("paypal", { transaction_id: data.transactionID, amount: { currency_code: data.currencySymbol || "USD", value: data.amount ? (data.amount / 100).toFixed(2) : undefined } }, { passthrough: data.passthrough, override: data.override }); _req2 = pickRequestOptions("paypal", data.requestOptions); _context6.next = 16; return core.refunds.create(_payload2, _req2); case 16: result = _context6.sent; return _context6.abrupt("break", 19); case 18: throw new Error("Unsupported payment core '".concat(coreName, "'.")); case 19: this.emit("refund-created", { coreName: coreName, data: data, result: result }); return _context6.abrupt("return", result); case 21: case "end": return _context6.stop(); } }, _callee6, this); })); function createRefund(_x14, _x15) { return _createRefund.apply(this, arguments); } return createRefund; }() // --- Subscription Management --- }, { key: "createSubscription", value: function () { var _createSubscription = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(coreName, data) { var core, result, priceID, prod, defaultPaymentMethod, pm, owner, reqAttach, base, payload, req, planID, _prod, _base2, _payload3, _req3; return _regeneratorRuntime().wrap(function _callee7$(_context7) { while (1) switch (_context7.prev = _context7.next) { case 0: core = this.payCoreManager.getPayCore(coreName); if (core) { _context7.next = 3; break; } throw new Error("Payment core '".concat(coreName, "' not initialized.")); case 3: if (data.customerID) { _context7.next = 5; break; } throw new Error("Customer ID required for subscriptions (Usage ~ data.customerID)."); case 5: _context7.next = 7; return this.validateCustomer(core, data.customerID); case 7: _context7.t0 = String(coreName).toLowerCase(); _context7.next = _context7.t0 === "stripe" ? 10 : _context7.t0 === "paypal" ? 45 : 58; break; case 10: priceID = data.priceID; if (priceID) { _context7.next = 16; break; } prod = this.productManager.getProductByID(data.productID); if (!(!prod || !prod.stripePriceID)) { _context7.next = 15; break; } throw new Error("Product not registered."); case 15: priceID = prod.stripePriceID; case 16: defaultPaymentMethod = data.default_payment_method || data.paymentMethodID || null; if (!(defaultPaymentMethod && defaultPaymentMethod.startsWith("pm_"))) { _context7.next = 33; break; } _context7.prev = 18; _context7.next = 21; return core.paymentMethods.retrieve(defaultPaymentMethod); case 21: pm = _context7.sent; owner = (pm === null || pm === void 0 ? void 0 : pm.customer) || null; if (!(!owner || owner !== data.customerID)) { _context7.next = 27; break; } reqAttach = pickRequestOptions("stripe", data.requestOptions); _context7.next = 27; return core.paymentMethods.attach(defaultPaymentMethod, { customer: data.customerID }, reqAttach); case 27: _context7.next = 33; break; case 29: _context7.prev = 29; _context7.t1 = _context7["catch"](18); _context7.t1.message = "Could not attach payment method ".concat(defaultPaymentMethod, " to customer ").concat(data.customerID, ": ").concat(err.message); throw _context7.t1; case 33: base = { customer: data.customerID, items: [{ price: priceID }] }; if (data.startNow === true) { base.trial_end = "now"; } else if (data.trialEnd) { base.trial_end = data.trialEnd; } if (data.collection_method) { base.collection_method = data.collection_method; } if (data.payment_behavior) { base.payment_behavior = data.payment_behavior; } if (data.proration_behavior) { base.proration_behavior = data.proration_behavior; } if (defaultPaymentMethod) { base.default_payment_method = defaultPaymentMethod; } payload = buildProcessorPayload("stripe", base, { passthrough: data.passthrough, override: data.override }); req = pickRequestOptions("stripe", data.requestOp