@pisell/pisellos
Version:
一个可扩展的前端模块化SDK框架,支持插件系统
888 lines (864 loc) • 60.5 kB
JavaScript
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
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 _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
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 { cloneDeep } from 'lodash-es';
import { BaseModule } from "../../../modules/BaseModule";
import { ResourceHooks } from "./types";
/**
* SQLite 存储名称
*/
var RESOURCE_STORE_NAME = 'resources';
// const BOOKING_STORE_NAME = 'resource_bookings'
/**
* 默认分页大小
*/
var DEFAULT_PAGE_SIZE = 999;
/**
* 同步防抖超时(毫秒)
*/
var RESOURCE_SYNC_DEBOUNCE_MS = 10000;
/**
* Resource 模块
*/
export var ResourceModule = /*#__PURE__*/function (_BaseModule) {
_inherits(ResourceModule, _BaseModule);
var _super = _createSuper(ResourceModule);
function ResourceModule(name, version) {
var _this;
_classCallCheck(this, ResourceModule);
_this = _super.call(this, name, version);
_defineProperty(_assertThisInitialized(_this), "defaultName", 'resource');
_defineProperty(_assertThisInitialized(_this), "defaultVersion", '1.0.0');
_defineProperty(_assertThisInitialized(_this), "store", void 0);
_defineProperty(_assertThisInitialized(_this), "dbManager", void 0);
_defineProperty(_assertThisInitialized(_this), "logger", void 0);
// LoggerManager 实例
_defineProperty(_assertThisInitialized(_this), "resourceDataSource", void 0);
/** 倒排索引: resourceId -> ResourceBooking[] */
_defineProperty(_assertThisInitialized(_this), "resourceIdIndex", new Map());
/** 待处理的同步消息队列 */
_defineProperty(_assertThisInitialized(_this), "pendingSyncMessages", []);
_defineProperty(_assertThisInitialized(_this), "syncTimer", void 0);
return _this;
}
// ─────────────────────────────────────────────────────────────────
// 初始化 & 生命周期
// ─────────────────────────────────────────────────────────────────
_createClass(ResourceModule, [{
key: "initialize",
value: function () {
var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) {
var _options$initialState,
_this2 = this;
var _options$initialState2, appPlugin, app;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
this.core = core;
this.store = options === null || options === void 0 ? void 0 : options.store;
if (Array.isArray(options === null || options === void 0 || (_options$initialState = options.initialState) === null || _options$initialState === void 0 ? void 0 : _options$initialState.list)) {
this.store.list = (options === null || options === void 0 || (_options$initialState2 = options.initialState) === null || _options$initialState2 === void 0 ? void 0 : _options$initialState2.list).map(function (item) {
return _this2.normalizeResource(item);
});
this.syncResourcesMap();
this.core.effects.emit(ResourceHooks.onResourcesChanged, this.store.list);
} else {
this.store.list = [];
this.store.map = new Map();
}
if (!Array.isArray(this.store.bookings)) {
this.store.bookings = [];
}
appPlugin = core.getPlugin('app');
if (appPlugin) {
app = appPlugin.getApp();
this.dbManager = app.sqlite || app.dbManager;
this.logger = app.logger;
}
this.initResourceDataSource();
this.setupResourceSync();
case 8:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function initialize(_x, _x2) {
return _initialize.apply(this, arguments);
}
return initialize;
}()
}, {
key: "logInfo",
value: function logInfo(title, metadata) {
if (this.logger) {
this.logger.addLog({
type: 'info',
title: "[ResourceModule] ".concat(title),
metadata: metadata || {}
});
}
}
}, {
key: "logError",
value: function logError(title, error, metadata) {
if (this.logger) {
this.logger.addLog({
type: 'error',
title: "[ResourceModule] ".concat(title),
metadata: metadata || {}
});
}
}
}, {
key: "preload",
value: function () {
var _preload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var _this3 = this;
var cachedResources, resources;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.loadResourcesFromSQLite();
case 2:
cachedResources = _context2.sent;
if (!(cachedResources.length > 0)) {
_context2.next = 10;
break;
}
this.store.list = cloneDeep(cachedResources).map(function (item) {
return _this3.normalizeResource(item);
});
this.syncResourcesMap();
_context2.next = 8;
return this.safeEmit(ResourceHooks.onResourcesChanged, this.store.list);
case 8:
_context2.next = 18;
break;
case 10:
_context2.next = 12;
return this.loadResourcesByServer();
case 12:
resources = _context2.sent;
if (!(resources.length > 0)) {
_context2.next = 18;
break;
}
this.store.list = cloneDeep(resources).map(function (item) {
return _this3.normalizeResource(item);
});
this.syncResourcesMap();
_context2.next = 18;
return this.safeEmit(ResourceHooks.onResourcesChanged, this.store.list);
case 18:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function preload() {
return _preload.apply(this, arguments);
}
return preload;
}()
}, {
key: "getRoutes",
value: function getRoutes() {
return [];
}
}, {
key: "destroy",
value: function destroy() {
var _this$resourceDataSou;
if (this.syncTimer) {
clearTimeout(this.syncTimer);
this.syncTimer = undefined;
}
this.pendingSyncMessages = [];
if ((_this$resourceDataSou = this.resourceDataSource) !== null && _this$resourceDataSou !== void 0 && _this$resourceDataSou.destroy) this.resourceDataSource.destroy();
_get(_getPrototypeOf(ResourceModule.prototype), "destroy", this).call(this);
}
// ─────────────────────────────────────────────────────────────────
// Resource CRUD
// ─────────────────────────────────────────────────────────────────
/**
* 获取所有资源(支持 includeBookings 附加预订信息)
*/
}, {
key: "getResources",
value: function getResources(queryOptions) {
var _this4 = this;
this.logInfo('getResources', {
queryOptions: queryOptions
});
if (!(queryOptions !== null && queryOptions !== void 0 && queryOptions.includeBookings)) {
return this.store.list;
}
return this.store.list.map(function (resource) {
return _this4.attachBookingsToResource(resource);
});
}
/**
* 根据 ID 获取单个资源
*/
}, {
key: "getResourceById",
value: function getResourceById(id, queryOptions) {
var resource = this.store.map.get(id);
if (!resource) return undefined;
if (queryOptions !== null && queryOptions !== void 0 && queryOptions.includeBookings) {
return this.attachBookingsToResource(resource);
}
return resource;
}
/**
* 创建资源
*/
}, {
key: "createResource",
value: function createResource(data) {
var _ref, _data$id;
var id = (_ref = (_data$id = data === null || data === void 0 ? void 0 : data.id) !== null && _data$id !== void 0 ? _data$id : data === null || data === void 0 ? void 0 : data.form_record_id) !== null && _ref !== void 0 ? _ref : Date.now();
var resource = this.normalizeResource(_objectSpread(_objectSpread({}, data), {}, {
id: id
}));
this.store.list.push(resource);
this.store.map.set(resource.id, resource);
this.saveResourcesToSQLite(this.store.list).catch(function () {});
this.safeEmit(ResourceHooks.onResourcesChanged, this.store.list);
return resource;
}
/**
* 更新资源
*/
}, {
key: "updateResource",
value: function updateResource(id, data) {
var _this5 = this;
var index = this.store.list.findIndex(function (r) {
return _this5.getIdKey(r.id) === _this5.getIdKey(id);
});
if (index === -1) return undefined;
var updated = this.normalizeResource(_objectSpread(_objectSpread(_objectSpread({}, this.store.list[index]), data), {}, {
id: id
}));
this.store.list[index] = updated;
this.store.map.set(updated.id, updated);
this.saveResourcesToSQLite(this.store.list).catch(function () {});
this.safeEmit(ResourceHooks.onResourcesChanged, this.store.list);
return updated;
}
/**
* 删除资源
*/
}, {
key: "deleteResource",
value: function deleteResource(id) {
var _this6 = this;
var key = this.getIdKey(id);
var index = this.store.list.findIndex(function (r) {
return _this6.getIdKey(r.id) === key;
});
if (index === -1) return false;
this.store.list.splice(index, 1);
this.store.map.delete(id);
this.saveResourcesToSQLite(this.store.list).catch(function () {});
this.safeEmit(ResourceHooks.onResourcesChanged, this.store.list);
return true;
}
// ─────────────────────────────────────────────────────────────────
// Booking CRUD
// ─────────────────────────────────────────────────────────────────
/**
* 根据资源 ID 获取预订列表
*/
}, {
key: "getBookingsByResourceId",
value: function getBookingsByResourceId(resourceId) {
return this.resourceIdIndex.get(resourceId) || [];
}
/**
* 创建预订
*/
// createBooking(booking: Partial<ResourceBooking>): ResourceBooking {
// const id = booking?.id ?? Date.now()
// const normalized: ResourceBooking = {
// id,
// ...booking,
// } as ResourceBooking
// this.store.bookings.push(normalized)
// const rid = normalized.resource_id ?? normalized.resourceId
// if (rid !== undefined) {
// const existing = this.resourceIdIndex.get(rid) || []
// existing.push(normalized)
// this.resourceIdIndex.set(rid, existing)
// }
// this.saveBookingsToSQLite(this.store.bookings).catch(() => {})
// this.safeEmit(ResourceHooks.onBookingsChanged, this.store.bookings)
// return normalized
// }
/**
* 更新预订
*/
// updateBooking(id: ResourceId, data: Partial<ResourceBooking>): ResourceBooking | undefined {
// const index = this.store.bookings.findIndex(b => this.getIdKey(b.id) === this.getIdKey(id))
// if (index === -1) return undefined
// const old = this.store.bookings[index]
// const updated: ResourceBooking = { ...old, ...data, id: old.id } as ResourceBooking
// this.store.bookings[index] = updated
// this.rebuildBookingsIndex()
// this.saveBookingsToSQLite(this.store.bookings).catch(() => {})
// this.safeEmit(ResourceHooks.onBookingsChanged, this.store.bookings)
// return updated
// }
/**
* 删除预订
*/
// deleteBooking(id: ResourceId): boolean {
// const index = this.store.bookings.findIndex(b => this.getIdKey(b.id) === this.getIdKey(id))
// if (index === -1) return false
// this.store.bookings.splice(index, 1)
// this.rebuildBookingsIndex()
// this.saveBookingsToSQLite(this.store.bookings).catch(() => {})
// this.safeEmit(ResourceHooks.onBookingsChanged, this.store.bookings)
// return true
// }
/**
* 清空缓存
*/
}, {
key: "clear",
value: (function () {
var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
this.store.list = [];
this.store.map.clear();
this.store.bookings = [];
this.resourceIdIndex.clear();
if (!this.dbManager) {
_context3.next = 12;
break;
}
_context3.prev = 5;
_context3.next = 8;
return this.dbManager.clear(RESOURCE_STORE_NAME);
case 8:
_context3.next = 12;
break;
case 10:
_context3.prev = 10;
_context3.t0 = _context3["catch"](5);
case 12:
_context3.next = 14;
return this.safeEmit(ResourceHooks.onResourcesChanged, this.store.list);
case 14:
_context3.next = 16;
return this.safeEmit(ResourceHooks.onBookingsChanged, this.store.bookings);
case 16:
case "end":
return _context3.stop();
}
}, _callee3, this, [[5, 10]]);
}));
function clear() {
return _clear.apply(this, arguments);
}
return clear;
}() // ─────────────────────────────────────────────────────────────────
// 内部工具方法
// ─────────────────────────────────────────────────────────────────
)
}, {
key: "attachBookingsToResource",
value: function attachBookingsToResource(resource) {
return _objectSpread(_objectSpread({}, resource), {}, {
bookings: this.getBookingsByResourceId(resource.id)
});
}
}, {
key: "normalizeResource",
value: function normalizeResource(resource) {
var _ref2,
_resource$id,
_this7 = this;
var normalized = _objectSpread(_objectSpread({}, resource), {}, {
id: (_ref2 = (_resource$id = resource === null || resource === void 0 ? void 0 : resource.id) !== null && _resource$id !== void 0 ? _resource$id : resource === null || resource === void 0 ? void 0 : resource.form_record_id) !== null && _ref2 !== void 0 ? _ref2 : ''
});
if (normalized.form_record_id === undefined && normalized.id !== '') {
normalized.form_record_id = normalized.id;
}
if (normalized.resource_form_id === undefined || normalized.resource_form_id === null) {
normalized.resource_form_id = '';
}
if (normalized.schedule === undefined || normalized.schedule === null) {
normalized.schedule = '';
}
if (Array.isArray(normalized.times)) {
normalized.times = normalized.times.map(function (timeSlot) {
var _timeSlot$start_at, _timeSlot$end_at, _timeSlot$start, _timeSlot$end;
if (!timeSlot || _typeof(timeSlot) !== 'object') return timeSlot;
var startAt = (_timeSlot$start_at = timeSlot.start_at) !== null && _timeSlot$start_at !== void 0 ? _timeSlot$start_at : timeSlot.start;
var endAt = (_timeSlot$end_at = timeSlot.end_at) !== null && _timeSlot$end_at !== void 0 ? _timeSlot$end_at : timeSlot.end;
return _objectSpread(_objectSpread({}, timeSlot), {}, {
start_at: startAt,
end_at: endAt,
start: (_timeSlot$start = timeSlot.start) !== null && _timeSlot$start !== void 0 ? _timeSlot$start : startAt,
end: (_timeSlot$end = timeSlot.end) !== null && _timeSlot$end !== void 0 ? _timeSlot$end : endAt
});
});
}
if (Array.isArray(normalized.children)) {
normalized.children = normalized.children.map(function (child) {
return _this7.normalizeResource(child);
});
}
return normalized;
}
}, {
key: "safeEmit",
value: function () {
var _safeEmit = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(event, payload) {
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
_context4.prev = 0;
_context4.next = 3;
return this.core.effects.emit(event, payload);
case 3:
_context4.next = 8;
break;
case 5:
_context4.prev = 5;
_context4.t0 = _context4["catch"](0);
// 不让外部监听器异常影响资源模块预加载或清理流程
console.error("[ResourceModule] \u4E8B\u4EF6\u6D3E\u53D1\u5931\u8D25: ".concat(event), _context4.t0);
case 8:
case "end":
return _context4.stop();
}
}, _callee4, this, [[0, 5]]);
}));
function safeEmit(_x3, _x4) {
return _safeEmit.apply(this, arguments);
}
return safeEmit;
}()
}, {
key: "syncResourcesMap",
value: function syncResourcesMap() {
this.store.map = new Map();
var _iterator = _createForOfIteratorHelper(this.store.list),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var resource = _step.value;
this.store.map.set(resource.id, resource);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
}, {
key: "syncBookingsIndex",
value: function syncBookingsIndex() {
this.resourceIdIndex.clear();
var _iterator2 = _createForOfIteratorHelper(this.store.bookings),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var _booking$resource_id;
var booking = _step2.value;
var rid = (_booking$resource_id = booking.resource_id) !== null && _booking$resource_id !== void 0 ? _booking$resource_id : booking.resourceId;
if (rid === undefined) continue;
var existing = this.resourceIdIndex.get(rid) || [];
existing.push(booking);
this.resourceIdIndex.set(rid, existing);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
}, {
key: "rebuildBookingsIndex",
value: function rebuildBookingsIndex() {
this.syncBookingsIndex();
}
}, {
key: "getIdKey",
value: function getIdKey(id) {
return String(id);
}
// ─────────────────────────────────────────────────────────────────
// 数据加载
// ─────────────────────────────────────────────────────────────────
}, {
key: "loadResourcesByServer",
value: function () {
var _loadResourcesByServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
var _this8 = this;
var response, resourceList, normalizedList;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
if (this.resourceDataSource) {
_context5.next = 2;
break;
}
return _context5.abrupt("return", []);
case 2:
_context5.prev = 2;
_context5.next = 5;
return this.resourceDataSource.getResourcePage({
num: DEFAULT_PAGE_SIZE,
skip: 1
});
case 5:
response = _context5.sent;
resourceList = Array.isArray(response === null || response === void 0 ? void 0 : response.list) ? response.list : [];
normalizedList = resourceList.map(function (item) {
return _this8.normalizeResource(item);
});
_context5.next = 10;
return this.saveResourcesToSQLite(normalizedList);
case 10:
_context5.next = 12;
return this.safeEmit(ResourceHooks.onResourcesLoaded, normalizedList);
case 12:
return _context5.abrupt("return", normalizedList);
case 15:
_context5.prev = 15;
_context5.t0 = _context5["catch"](2);
return _context5.abrupt("return", []);
case 18:
case "end":
return _context5.stop();
}
}, _callee5, this, [[2, 15]]);
}));
function loadResourcesByServer() {
return _loadResourcesByServer.apply(this, arguments);
}
return loadResourcesByServer;
}() // ─────────────────────────────────────────────────────────────────
// SQLite 持久化
// ─────────────────────────────────────────────────────────────────
}, {
key: "loadResourcesFromSQLite",
value: function () {
var _loadResourcesFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
var resources;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
if (this.dbManager) {
_context6.next = 2;
break;
}
return _context6.abrupt("return", []);
case 2:
_context6.prev = 2;
_context6.next = 5;
return this.dbManager.getAll(RESOURCE_STORE_NAME);
case 5:
resources = _context6.sent;
return _context6.abrupt("return", resources || []);
case 9:
_context6.prev = 9;
_context6.t0 = _context6["catch"](2);
return _context6.abrupt("return", []);
case 12:
case "end":
return _context6.stop();
}
}, _callee6, this, [[2, 9]]);
}));
function loadResourcesFromSQLite() {
return _loadResourcesFromSQLite.apply(this, arguments);
}
return loadResourcesFromSQLite;
}()
}, {
key: "saveResourcesToSQLite",
value: function () {
var _saveResourcesToSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(resourceList) {
var _this9 = this;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
if (this.dbManager) {
_context7.next = 2;
break;
}
return _context7.abrupt("return");
case 2:
_context7.prev = 2;
_context7.next = 5;
return this.dbManager.clear(RESOURCE_STORE_NAME);
case 5:
if (!(resourceList.length === 0)) {
_context7.next = 7;
break;
}
return _context7.abrupt("return");
case 7:
if (!this.dbManager.bulkAdd) {
_context7.next = 11;
break;
}
_context7.next = 10;
return this.dbManager.bulkAdd(RESOURCE_STORE_NAME, resourceList);
case 10:
return _context7.abrupt("return");
case 11:
_context7.next = 13;
return Promise.all(resourceList.map(function (r) {
return _this9.dbManager.add(RESOURCE_STORE_NAME, r);
}));
case 13:
_context7.next = 19;
break;
case 15:
_context7.prev = 15;
_context7.t0 = _context7["catch"](2);
console.error('saveResourcesToSQLite error', _context7.t0);
this.logError('保存资源到 SQLite 失败', {
error: _context7.t0 instanceof Error ? _context7.t0.message : String(_context7.t0),
resourceList: resourceList.length
});
case 19:
case "end":
return _context7.stop();
}
}, _callee7, this, [[2, 15]]);
}));
function saveResourcesToSQLite(_x5) {
return _saveResourcesToSQLite.apply(this, arguments);
}
return saveResourcesToSQLite;
}() // private async loadBookingsFromSQLite(): Promise<ResourceBooking[]> {
// if (!this.dbManager) return []
// try {
// const bookings = await this.dbManager.getAll(BOOKING_STORE_NAME)
// return bookings || []
// } catch {
// return []
// }
// }
// private async saveBookingsToSQLite(bookings: ResourceBooking[]): Promise<void> {
// if (!this.dbManager) return
// try {
// await this.dbManager.clear(BOOKING_STORE_NAME)
// if (bookings.length === 0) return
// if (this.dbManager.bulkAdd) {
// await this.dbManager.bulkAdd(BOOKING_STORE_NAME, bookings)
// return
// }
// await Promise.all(bookings.map(b => this.dbManager.add(BOOKING_STORE_NAME, b)))
// } catch {
// // 忽略 SQLite 异常
// }
// }
// ─────────────────────────────────────────────────────────────────
// pubsub 同步
// ─────────────────────────────────────────────────────────────────
}, {
key: "initResourceDataSource",
value: function initResourceDataSource() {
var _serverOptions;
var ResourceDataSourceClass = (_serverOptions = this.core.serverOptions) === null || _serverOptions === void 0 || (_serverOptions = _serverOptions.All_DATA_SOURCES) === null || _serverOptions === void 0 ? void 0 : _serverOptions.ResourceDataSource;
if (!ResourceDataSourceClass) return;
this.resourceDataSource = new ResourceDataSourceClass();
}
}, {
key: "setupResourceSync",
value: function () {
var _setupResourceSync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
var _this10 = this,
_result$data;
var result, _result$data2;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
if (this.resourceDataSource) {
_context8.next = 2;
break;
}
return _context8.abrupt("return");
case 2:
_context8.next = 4;
return this.resourceDataSource.run({
pubsub: {
callback: function callback(res) {
var data = (res === null || res === void 0 ? void 0 : res.data) || res;
if (!data) return;
var channelKey = data.module || 'resource';
_this10.pendingSyncMessages.push(_objectSpread(_objectSpread({}, data), {}, {
_channelKey: channelKey
}));
if (_this10.syncTimer) clearTimeout(_this10.syncTimer);
_this10.syncTimer = setTimeout(function () {
_this10.processSyncMessages();
}, RESOURCE_SYNC_DEBOUNCE_MS);
}
}
}).catch(function () {
// 忽略同步初始化异常
});
case 4:
result = _context8.sent;
console.log('result', result);
if (!(result !== null && result !== void 0 && (_result$data = result.data) !== null && _result$data !== void 0 && (_result$data = _result$data.list) !== null && _result$data !== void 0 && _result$data.length)) {
_context8.next = 9;
break;
}
_context8.next = 9;
return this.mergeResourcesToStore(result === null || result === void 0 || (_result$data2 = result.data) === null || _result$data2 === void 0 ? void 0 : _result$data2.list);
case 9:
case "end":
return _context8.stop();
}
}, _callee8, this);
}));
function setupResourceSync() {
return _setupResourceSync.apply(this, arguments);
}
return setupResourceSync;
}()
}, {
key: "processSyncMessages",
value: function () {
var _processSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
var messages, deleteIds, bodyUpdates, sseRefreshIds, _iterator3, _step3, _msg$ids2, _msg$relation_resourc, msg, _msg$ids, _msg$body$id, bodyId, uniqueDeleteIds, uniqueSSEIds, bodyList, freshResources;
return _regeneratorRuntime().wrap(function _callee9$(_context9) {
while (1) switch (_context9.prev = _context9.next) {
case 0:
messages = _toConsumableArray(this.pendingSyncMessages);
this.pendingSyncMessages = [];
if (!(messages.length === 0)) {
_context9.next = 4;
break;
}
return _context9.abrupt("return");
case 4:
deleteIds = [];
bodyUpdates = new Map();
sseRefreshIds = [];
_iterator3 = _createForOfIteratorHelper(messages);
_context9.prev = 8;
_iterator3.s();
case 10:
if ((_step3 = _iterator3.n()).done) {
_context9.next = 24;
break;
}
msg = _step3.value;
if (!(msg.operation === 'delete' || msg.action === 'delete')) {
_context9.next = 15;
break;
}
if ((_msg$ids = msg.ids) !== null && _msg$ids !== void 0 && _msg$ids.length) deleteIds.push.apply(deleteIds, _toConsumableArray(msg.ids));else if (msg.id !== undefined) deleteIds.push(msg.id);
return _context9.abrupt("continue", 22);
case 15:
if (!msg.body) {
_context9.next = 21;
break;
}
bodyId = (_msg$body$id = msg.body.id) !== null && _msg$body$id !== void 0 ? _msg$body$id : msg.id;
if (!(bodyId === undefined)) {
_context9.next = 19;
break;
}
return _context9.abrupt("continue", 22);
case 19:
bodyUpdates.set(this.getIdKey(bodyId), _objectSpread(_objectSpread({}, msg.body), {}, {
id: bodyId
}));
return _context9.abrupt("continue", 22);
case 21:
if ((_msg$ids2 = msg.ids) !== null && _msg$ids2 !== void 0 && _msg$ids2.length) {
sseRefreshIds.push.apply(sseRefreshIds, _toConsumableArray(msg.ids));
} else if (msg.id !== undefined) {
sseRefreshIds.push(msg.id);
} else if ((_msg$relation_resourc = msg.relation_resource_ids) !== null && _msg$relation_resourc !== void 0 && _msg$relation_resourc.length) {
sseRefreshIds.push.apply(sseRefreshIds, _toConsumableArray(msg.relation_resource_ids));
}
case 22:
_context9.next = 10;
break;
case 24:
_context9.next = 29;
break;
case 26:
_context9.prev = 26;
_context9.t0 = _context9["catch"](8);
_iterator3.e(_context9.t0);
case 29:
_context9.prev = 29;
_iterator3.f();
return _context9.finish(29);
case 32:
uniqueDeleteIds = this.uniqueResourceIds(deleteIds);
uniqueSSEIds = this.uniqueResourceIds(sseRefreshIds);
bodyList = _toConsumableArray(bodyUpdates.values());
if (!(uniqueDeleteIds.length > 0)) {
_context9.next = 38;
break;
}
_context9.next = 38;
return this.removeResourcesByIds(uniqueDeleteIds);
case 38:
if (!(bodyList.length > 0)) {
_context9.next = 41;
break;
}
_context9.next = 41;
return this.mergeResourcesToStore(bodyList);
case 41:
if (!(uniqueSSEIds.length > 0)) {
_context9.next = 48;
break;
}
_context9.next = 44;
return this.fetchResourcesBySSE(uniqueSSEIds);
case 44:
freshResources = _context9.sent;
if (!(freshResources.length > 0)) {
_context9.next = 48;
break;
}
_context9.next = 48;
return this.mergeResourcesToStore(freshResources);
case 48:
if (!(uniqueDeleteIds.length === 0 && bodyList.length === 0 && uniqueSSEIds.l