@pisell/pisellos
Version:
一个可扩展的前端模块化SDK框架,支持插件系统
971 lines (959 loc) • 120 kB
JavaScript
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 _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
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); }
import { BaseModule } from "../../modules/BaseModule";
import { RegisterAndLoginHooks, VerificationCodeType, VerificationPurpose } from "./types";
import { createApiCaller } from "./config";
export * from "./types";
export * from "./config";
/**
* 注册登录解决方案实现
*/
export var RegisterAndLoginImpl = /*#__PURE__*/function (_BaseModule) {
_inherits(RegisterAndLoginImpl, _BaseModule);
var _super = _createSuper(RegisterAndLoginImpl);
function RegisterAndLoginImpl(name, version) {
var _this;
_classCallCheck(this, RegisterAndLoginImpl);
_this = _super.call(this, name, version);
// 提供给 baseModule 用的默认名称和默认版本
_defineProperty(_assertThisInitialized(_this), "defaultName", 'registerAndLogin');
_defineProperty(_assertThisInitialized(_this), "defaultVersion", '1.0.0');
_defineProperty(_assertThisInitialized(_this), "isSolution", true);
_defineProperty(_assertThisInitialized(_this), "request", void 0);
_defineProperty(_assertThisInitialized(_this), "window", void 0);
_defineProperty(_assertThisInitialized(_this), "store", void 0);
_defineProperty(_assertThisInitialized(_this), "apiCaller", void 0);
_defineProperty(_assertThisInitialized(_this), "otherParams", {});
_defineProperty(_assertThisInitialized(_this), "channel", 'default');
// 内存缓存
_defineProperty(_assertThisInitialized(_this), "countriesCache", null);
return _this;
}
/**
* 重新发送邮箱注册链接
*/
_createClass(RegisterAndLoginImpl, [{
key: "resendEmailRegisterLink",
value: (function () {
var _resendEmailRegisterLink = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var error, response;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
if (this.store.emailRegisterLinkCode) {
_context.next = 5;
break;
}
error = '没有找到邮箱注册链接的 code,请先调用 sendEmailRegisterLink';
this.store.error = error;
return _context.abrupt("return", {
status: false,
message: error
});
case 5:
this.store.isLoading = true;
this.store.error = null;
_context.next = 9;
return this.apiCaller.call('resendEmailRegisterLink', {
code: this.store.emailRegisterLinkCode
});
case 9:
response = _context.sent;
if (!response.status) {
_context.next = 15;
break;
}
_context.next = 13;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationSent, {
target: 'resend',
purpose: VerificationPurpose.REGISTER
});
case 13:
_context.next = 18;
break;
case 15:
this.store.error = response.message || '重新发送注册邀请链接失败';
_context.next = 18;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationFailed, {
target: 'resend',
error: this.store.error
});
case 18:
return _context.abrupt("return", response);
case 21:
_context.prev = 21;
_context.t0 = _context["catch"](0);
this.store.error = '重新发送注册邀请链接失败';
_context.next = 26;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationFailed, {
target: 'resend',
error: this.store.error
});
case 26:
return _context.abrupt("return", _context.t0);
case 27:
_context.prev = 27;
this.store.isLoading = false;
return _context.finish(27);
case 30:
case "end":
return _context.stop();
}
}, _callee, this, [[0, 21, 27, 30]]);
}));
function resendEmailRegisterLink() {
return _resendEmailRegisterLink.apply(this, arguments);
}
return resendEmailRegisterLink;
}()
/**
* 邮箱验证码注册
* @param params 注册参数
* @returns 注册结果
*/
)
}, {
key: "emailCodeRegister",
value: (function () {
var _emailCodeRegister = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(params) {
var response, _response$data, user, token, refreshToken, expiresAt;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
this.store.isLoading = true;
this.store.error = null;
_context2.next = 5;
return this.core.effects.emit(RegisterAndLoginHooks.onRegisterStarted, params);
case 5:
_context2.next = 7;
return this.apiCaller.call('emailCodeRegister', params);
case 7:
response = _context2.sent;
if (!(response.status && response.data)) {
_context2.next = 15;
break;
}
_response$data = response.data, user = _response$data.user, token = _response$data.token, refreshToken = _response$data.refreshToken, expiresAt = _response$data.expiresAt; // 如果注册成功并返回了 token,说明可以直接登录
if (token) {
this.store.currentUser = user;
this.store.isLoggedIn = true;
// 保存到本地存储
// this.window.localStorage.setItem('auth_token', token);
// this.window.localStorage.setItem('user_info', JSON.stringify(user));
// if (refreshToken) {
// this.window.localStorage.setItem('refresh_token', refreshToken);
// }
}
_context2.next = 13;
return this.core.effects.emit(RegisterAndLoginHooks.onRegisterSuccess, response.data);
case 13:
_context2.next = 18;
break;
case 15:
this.store.error = response.message || '邮箱验证码注册失败';
_context2.next = 18;
return this.core.effects.emit(RegisterAndLoginHooks.onRegisterFailed, {
error: this.store.error,
params: params
});
case 18:
return _context2.abrupt("return", response);
case 21:
_context2.prev = 21;
_context2.t0 = _context2["catch"](0);
this.store.error = '邮箱验证码注册失败';
_context2.next = 26;
return this.core.effects.emit(RegisterAndLoginHooks.onRegisterFailed, {
error: this.store.error,
params: params
});
case 26:
throw _context2.t0;
case 27:
_context2.prev = 27;
this.store.isLoading = false;
return _context2.finish(27);
case 30:
case "end":
return _context2.stop();
}
}, _callee2, this, [[0, 21, 27, 30]]);
}));
function emailCodeRegister(_x) {
return _emailCodeRegister.apply(this, arguments);
}
return emailCodeRegister;
}()
/**
* 手机验证码注册
*/
)
}, {
key: "phoneCodeRegister",
value: (function () {
var _phoneCodeRegister = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(params) {
var response, _response$data2, user, token, refreshToken, expiresAt;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
_context3.prev = 0;
this.store.isLoading = true;
this.store.error = null;
_context3.next = 5;
return this.core.effects.emit(RegisterAndLoginHooks.onRegisterStarted, params);
case 5:
_context3.next = 7;
return this.apiCaller.call('phoneCodeRegister', params);
case 7:
response = _context3.sent;
if (!(response.status && response.data)) {
_context3.next = 15;
break;
}
_response$data2 = response.data, user = _response$data2.user, token = _response$data2.token, refreshToken = _response$data2.refreshToken, expiresAt = _response$data2.expiresAt; // 如果注册成功并返回了 token,说明可以直接登录
if (token) {
this.store.currentUser = user;
this.store.isLoggedIn = true;
// 保存到本地存储
// this.window.localStorage.setItem('auth_token', token);
// this.window.localStorage.setItem('user_info', JSON.stringify(user));
// if (refreshToken) {
// this.window.localStorage.setItem('refresh_token', refreshToken);
// }
}
_context3.next = 13;
return this.core.effects.emit(RegisterAndLoginHooks.onRegisterSuccess, response.data);
case 13:
_context3.next = 18;
break;
case 15:
this.store.error = response.message || '注册失败';
_context3.next = 18;
return this.core.effects.emit(RegisterAndLoginHooks.onRegisterFailed, {
error: this.store.error,
params: params
});
case 18:
return _context3.abrupt("return", response);
case 21:
_context3.prev = 21;
_context3.t0 = _context3["catch"](0);
this.store.error = _context3.t0.message || '注册失败';
_context3.next = 26;
return this.core.effects.emit(RegisterAndLoginHooks.onRegisterFailed, {
error: this.store.error,
params: params
});
case 26:
throw _context3.t0;
case 27:
_context3.prev = 27;
this.store.isLoading = false;
return _context3.finish(27);
case 30:
case "end":
return _context3.stop();
}
}, _callee3, this, [[0, 21, 27, 30]]);
}));
function phoneCodeRegister(_x2) {
return _phoneCodeRegister.apply(this, arguments);
}
return phoneCodeRegister;
}())
}, {
key: "initialize",
value: function () {
var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(core, options) {
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
this.core = core;
// 初始化状态
this.store = _objectSpread({
currentUser: null,
isLoggedIn: false,
isLoading: false,
verificationCodeSent: {},
oauthConfig: options.oauthConfig || {},
error: null
}, options.store);
this.otherParams = options.otherParams || {};
// 获取渠道信息
this.channel = this.otherParams.channel || 'default';
// 获取依赖的插件
this.request = core.getPlugin('request');
this.window = core.getPlugin('window');
if (this.request) {
_context4.next = 8;
break;
}
throw new Error('RegisterAndLogin 模块需要 request 插件支持');
case 8:
if (this.window) {
_context4.next = 10;
break;
}
throw new Error('RegisterAndLogin 模块需要 window 插件支持');
case 10:
// 创建 API 调用器
this.apiCaller = createApiCaller(this.request, this.channel);
// 尝试从本地存储恢复登录状态
_context4.next = 13;
return this.restoreLoginState();
case 13:
// 预先调用获取区号的方法,初始内存缓存
this.getCountries();
console.log('[RegisterAndLogin] 初始化完成');
_context4.next = 17;
return this.core.effects.emit(RegisterAndLoginHooks.onInited, {});
case 17:
case "end":
return _context4.stop();
}
}, _callee4, this);
}));
function initialize(_x3, _x4) {
return _initialize.apply(this, arguments);
}
return initialize;
}()
/**
* 从本地存储恢复登录状态
*/
}, {
key: "restoreLoginState",
value: (function () {
var _restoreLoginState = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
var token, userInfo, user;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
_context5.prev = 0;
token = this.window.localStorage.getItem('auth_token');
userInfo = this.window.localStorage.getItem('user_info');
if (!(token && userInfo)) {
_context5.next = 9;
break;
}
user = JSON.parse(userInfo);
this.store.currentUser = user;
this.store.isLoggedIn = true;
// 验证 token 是否仍然有效
_context5.next = 9;
return this.validateToken(token);
case 9:
_context5.next = 15;
break;
case 11:
_context5.prev = 11;
_context5.t0 = _context5["catch"](0);
console.warn('[RegisterAndLogin] 恢复登录状态失败:', _context5.t0);
this.clearLoginState();
case 15:
case "end":
return _context5.stop();
}
}, _callee5, this, [[0, 11]]);
}));
function restoreLoginState() {
return _restoreLoginState.apply(this, arguments);
}
return restoreLoginState;
}()
/**
* 验证 token 有效性
*/
)
}, {
key: "validateToken",
value: (function () {
var _validateToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(token) {
var response;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
_context6.prev = 0;
_context6.next = 3;
return this.apiCaller.call('validateToken', token);
case 3:
response = _context6.sent;
if (!(response.status && response.data)) {
_context6.next = 9;
break;
}
this.store.currentUser = response.data;
return _context6.abrupt("return", true);
case 9:
this.clearLoginState();
return _context6.abrupt("return", false);
case 11:
_context6.next = 18;
break;
case 13:
_context6.prev = 13;
_context6.t0 = _context6["catch"](0);
console.warn('[RegisterAndLogin] Token 验证失败:', _context6.t0);
this.clearLoginState();
return _context6.abrupt("return", false);
case 18:
case "end":
return _context6.stop();
}
}, _callee6, this, [[0, 13]]);
}));
function validateToken(_x5) {
return _validateToken.apply(this, arguments);
}
return validateToken;
}()
/**
* 清除登录状态
*/
)
}, {
key: "clearLoginState",
value: function clearLoginState() {
this.store.currentUser = null;
this.store.isLoggedIn = false;
this.window.localStorage.removeItem('auth_token');
this.window.localStorage.removeItem('user_info');
this.window.localStorage.removeItem('refresh_token');
}
/**
* 发送邮箱验证码
*/
}, {
key: "sendEmailVerificationCode",
value: (function () {
var _sendEmailVerificationCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(params) {
var response, now;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
_context7.prev = 0;
this.store.isLoading = true;
this.store.error = null;
_context7.next = 5;
return this.apiCaller.call('sendEmailVerificationCode', params);
case 5:
response = _context7.sent;
if (!response.status) {
_context7.next = 13;
break;
}
// 记录验证码发送状态
now = Date.now();
this.store.verificationCodeSent[params.target] = {
sent: true,
sentAt: now,
expiresAt: now + 5 * 60 * 1000 // 5分钟过期
};
_context7.next = 11;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationSent, {
target: params.target,
purpose: params.purpose
});
case 11:
_context7.next = 16;
break;
case 13:
this.store.error = response.message || '发送验证码失败';
_context7.next = 16;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationFailed, {
target: params.target,
error: this.store.error
});
case 16:
return _context7.abrupt("return", response);
case 19:
_context7.prev = 19;
_context7.t0 = _context7["catch"](0);
this.store.error = '发送验证码失败';
_context7.next = 24;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationFailed, {
target: params.target,
error: this.store.error
});
case 24:
return _context7.abrupt("return", _context7.t0);
case 25:
_context7.prev = 25;
this.store.isLoading = false;
return _context7.finish(25);
case 28:
case "end":
return _context7.stop();
}
}, _callee7, this, [[0, 19, 25, 28]]);
}));
function sendEmailVerificationCode(_x6) {
return _sendEmailVerificationCode.apply(this, arguments);
}
return sendEmailVerificationCode;
}()
/**
* 发送邮箱登录验证码
*/
)
}, {
key: "sendEmailLoginCode",
value: (function () {
var _sendEmailLoginCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(params) {
var response, now;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
_context8.prev = 0;
this.store.isLoading = true;
this.store.error = null;
_context8.next = 5;
return this.apiCaller.call('sendEmailLoginCode', params);
case 5:
response = _context8.sent;
if (!response.status) {
_context8.next = 13;
break;
}
// 记录验证码发送状态
now = Date.now();
this.store.verificationCodeSent[params.target] = {
sent: true,
sentAt: now,
expiresAt: now + 5 * 60 * 1000 // 5分钟过期
};
_context8.next = 11;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationSent, {
target: params.target,
purpose: params.purpose
});
case 11:
_context8.next = 16;
break;
case 13:
this.store.error = response.message || '发送验证码失败';
_context8.next = 16;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationFailed, {
target: params.target,
error: this.store.error
});
case 16:
return _context8.abrupt("return", response);
case 19:
_context8.prev = 19;
_context8.t0 = _context8["catch"](0);
this.store.error = '发送验证码失败';
_context8.next = 24;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationFailed, {
target: params.target,
error: this.store.error
});
case 24:
return _context8.abrupt("return", _context8.t0);
case 25:
_context8.prev = 25;
this.store.isLoading = false;
return _context8.finish(25);
case 28:
case "end":
return _context8.stop();
}
}, _callee8, this, [[0, 19, 25, 28]]);
}));
function sendEmailLoginCode(_x7) {
return _sendEmailLoginCode.apply(this, arguments);
}
return sendEmailLoginCode;
}()
/**
* 发送手机号注册验证码
*/
)
}, {
key: "sendSmsRegisterCode",
value: (function () {
var _sendSmsRegisterCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(params) {
var response, now;
return _regeneratorRuntime().wrap(function _callee9$(_context9) {
while (1) switch (_context9.prev = _context9.next) {
case 0:
_context9.prev = 0;
this.store.isLoading = true;
this.store.error = null;
_context9.next = 5;
return this.apiCaller.call('sendSmsRegisterCode', params);
case 5:
response = _context9.sent;
if (!response.status) {
_context9.next = 13;
break;
}
// 记录验证码发送状态
now = Date.now();
this.store.verificationCodeSent[params.phone] = {
sent: true,
sentAt: now,
expiresAt: now + 5 * 60 * 1000 // 5分钟过期
};
_context9.next = 11;
return this.core.effects.emit(RegisterAndLoginHooks.onSmsVerificationSent, {
target: params.phone,
purpose: VerificationPurpose.REGISTER
});
case 11:
_context9.next = 16;
break;
case 13:
this.store.error = response.message || '发送注册验证码失败';
_context9.next = 16;
return this.core.effects.emit(RegisterAndLoginHooks.onSmsVerificationFailed, {
target: params.phone,
error: this.store.error
});
case 16:
return _context9.abrupt("return", response);
case 19:
_context9.prev = 19;
_context9.t0 = _context9["catch"](0);
this.store.error = '发送注册验证码失败';
_context9.next = 24;
return this.core.effects.emit(RegisterAndLoginHooks.onSmsVerificationFailed, {
target: params.phone,
error: this.store.error
});
case 24:
return _context9.abrupt("return", _context9.t0);
case 25:
_context9.prev = 25;
this.store.isLoading = false;
return _context9.finish(25);
case 28:
case "end":
return _context9.stop();
}
}, _callee9, this, [[0, 19, 25, 28]]);
}));
function sendSmsRegisterCode(_x8) {
return _sendSmsRegisterCode.apply(this, arguments);
}
return sendSmsRegisterCode;
}()
/**
* 发送邮箱注册邀请链接
*/
)
}, {
key: "sendEmailRegisterLink",
value: (function () {
var _sendEmailRegisterLink = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(email) {
var response, _response$data3, now;
return _regeneratorRuntime().wrap(function _callee10$(_context10) {
while (1) switch (_context10.prev = _context10.next) {
case 0:
_context10.prev = 0;
this.store.isLoading = true;
this.store.error = null;
_context10.next = 5;
return this.apiCaller.call('sendEmailRegisterLink', email);
case 5:
response = _context10.sent;
if (!response.status) {
_context10.next = 14;
break;
}
// 保存返回的 code
if ((_response$data3 = response.data) !== null && _response$data3 !== void 0 && _response$data3.code) {
this.store.emailRegisterLinkCode = response.data.code;
}
// 记录邀请链接发送状态
now = Date.now();
this.store.verificationCodeSent[email] = {
sent: true,
sentAt: now,
expiresAt: now + 24 * 60 * 60 * 1000 // 24小时过期
};
_context10.next = 12;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationSent, {
target: email,
purpose: VerificationPurpose.REGISTER
});
case 12:
_context10.next = 17;
break;
case 14:
this.store.error = response.message || '发送注册邀请链接失败';
_context10.next = 17;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationFailed, {
target: email,
error: this.store.error
});
case 17:
return _context10.abrupt("return", response);
case 20:
_context10.prev = 20;
_context10.t0 = _context10["catch"](0);
this.store.error = '发送注册邀请链接失败';
_context10.next = 25;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationFailed, {
target: email,
error: this.store.error
});
case 25:
return _context10.abrupt("return", _context10.t0);
case 26:
_context10.prev = 26;
this.store.isLoading = false;
return _context10.finish(26);
case 29:
case "end":
return _context10.stop();
}
}, _callee10, this, [[0, 20, 26, 29]]);
}));
function sendEmailRegisterLink(_x9) {
return _sendEmailRegisterLink.apply(this, arguments);
}
return sendEmailRegisterLink;
}()
/**
* 验证邮箱注册链接
*/
)
}, {
key: "verifyEmailRegistrationLink",
value: (function () {
var _verifyEmailRegistrationLink = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(params) {
var response;
return _regeneratorRuntime().wrap(function _callee11$(_context11) {
while (1) switch (_context11.prev = _context11.next) {
case 0:
_context11.prev = 0;
this.store.isLoading = true;
this.store.error = null;
_context11.next = 5;
return this.apiCaller.call('verifyEmailRegistrationLink', params);
case 5:
response = _context11.sent;
if (!response.status) {
_context11.next = 11;
break;
}
_context11.next = 9;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationVerified, {
target: 'email-registration-link',
purpose: VerificationPurpose.REGISTER
});
case 9:
_context11.next = 14;
break;
case 11:
this.store.error = response.message || '邮箱注册链接验证失败';
_context11.next = 14;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationFailed, {
target: 'email-registration-link',
error: this.store.error
});
case 14:
return _context11.abrupt("return", response);
case 17:
_context11.prev = 17;
_context11.t0 = _context11["catch"](0);
this.store.error = '邮箱注册链接验证失败';
_context11.next = 22;
return this.core.effects.emit(RegisterAndLoginHooks.onEmailVerificationFailed, {
target: 'email-registration-link',
error: this.store.error
});
case 22:
return _context11.abrupt("return", _context11.t0);
case 23:
_context11.prev = 23;
this.store.isLoading = false;
return _context11.finish(23);
case 26:
case "end":
return _context11.stop();
}
}, _callee11, this, [[0, 17, 23, 26]]);
}));
function verifyEmailRegistrationLink(_x10) {
return _verifyEmailRegistrationLink.apply(this, arguments);
}
return verifyEmailRegistrationLink;
}()
/**
* 邮箱密码登录
*/
)
}, {
key: "emailPasswordLogin",
value: (function () {
var _emailPasswordLogin = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(params) {
var response;
return _regeneratorRuntime().wrap(function _callee12$(_context12) {
while (1) switch (_context12.prev = _context12.next) {
case 0:
_context12.prev = 0;
this.store.isLoading = true;
this.store.error = null;
_context12.next = 5;
return this.core.effects.emit(RegisterAndLoginHooks.onLoginStarted, {
type: 'email-password',
email: params.email
});
case 5:
_context12.next = 7;
return this.apiCaller.call('emailPasswordLogin', params);
case 7:
response = _context12.sent;
if (!(response.status && response.data)) {
_context12.next = 17;
break;
}
// 保存用户信息和 token
this.store.isLoggedIn = true;
this.store.userInfo = response.data.user;
this.store.token = response.data.token;
// 如果有 refreshToken,也保存
if (response.data.refreshToken) {
this.store.refreshToken = response.data.refreshToken;
}
_context12.next = 15;
return this.core.effects.emit(RegisterAndLoginHooks.onLoginSuccess, {
user: response.data.user,
token: response.data.token,
loginType: 'email-password'
});
case 15:
_context12.next = 20;
break;
case 17:
this.store.error = response.message || '邮箱密码登录失败';
_context12.next = 20;
return this.core.effects.emit(RegisterAndLoginHooks.onLoginFailed, {
error: this.store.error,
loginType: 'email-password'
});
case 20:
return _context12.abrupt("return", response);
case 23:
_context12.prev = 23;
_context12.t0 = _context12["catch"](0);
this.store.error = '邮箱密码登录失败';
_context12.next = 28;
return this.core.effects.emit(RegisterAndLoginHooks.onLoginFailed, {
error: this.store.error,
loginType: 'email-password'
});
case 28:
return _context12.abrupt("return", _context12.t0);
case 29:
_context12.prev = 29;
this.store.isLoading = false;
return _context12.finish(29);
case 32:
case "end":
return _context12.stop();
}
}, _callee12, this, [[0, 23, 29, 32]]);
}));
function emailPasswordLogin(_x11) {
return _emailPasswordLogin.apply(this, arguments);
}
return emailPasswordLogin;
}()
/**
* 验证验证码
*/
)
}, {
key: "verifyCode",
value: (function () {
var _verifyCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(params) {
var response, hookName, _hookName;
return _regeneratorRuntime().wrap(function _callee13$(_context13) {
while (1) switch (_context13.prev = _context13.next) {
case 0:
_context13.prev = 0;
this.store.isLoading = true;
this.store.error = null;
_context13.next = 5;
return this.apiCaller.call('verifyCode', params);
case 5:
response = _context13.sent;
if (!response.status) {
_context13.next = 12;
break;
}
hookName = params.type === VerificationCodeType.EMAIL ? RegisterAndLoginHooks.onEmailVerificationVerified : RegisterAndLoginHooks.onSmsVerificationVerified;
_context13.next = 10;
return this.core.effects.emit(hookName, {
target: params.target,
purpose: params.purpose
});
case 10:
_context13.next = 16;
break;
case 12:
this.store.error = response.message || '验证码验证失败';
_hookName = params.type === VerificationCodeType.EMAIL ? RegisterAndLoginHooks.onEmailVerificationFailed : RegisterAndLoginHooks.onSmsVerificationFailed;
_context13.next = 16;
return this.core.effects.emit(_hookName, {
target: params.target,
error: this.store.error
});
case 16:
return _context13.abrupt("return", response);
case 19:
_context13.prev = 19;
_context13.t0 = _context13["catch"](0);
this.store.error = '验证码验证失败';
return _context13.abrupt("return", _context13.t0);
case 23:
_context13.prev = 23;
this.store.isLoading = false;
return _context13.finish(23);
case 26:
case "end":
return _context13.stop();
}
}, _callee13, this, [[0, 19, 23, 26]]);
}));
function verifyCode(_x12) {
return _verifyCode.apply(this, arguments);
}
return verifyCode;
}()
/**
* 用户注册
*/
)
}, {
key: "register",
value: (function () {
var _register = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14(params) {
var response, _response$data4, user, token, refreshToken, expiresAt;
return _regeneratorRuntime().wrap(function _callee14$(_context14) {
while (1) switch (_context14.prev = _context14.next) {
case 0:
_context14.prev = 0;
this.store.isLoa