init: commons, request

main
Lei OT 4 months ago
commit 61defa16fe

@ -0,0 +1,5 @@
{
"presets": [
["@babel/preset-env", { "modules": false }]
]
}

6
.gitignore vendored

@ -0,0 +1,6 @@
node_modules
build/
dist
package-lock.json
**/*.tgz

@ -0,0 +1 @@
src/

@ -0,0 +1,24 @@
# @haina/npm
可复用的 npm 模块
支持 `ESM`(import) 和 `CommonJS`(require)
## 📦 Installation
```sh
npm install http://xxxx/npm/haina-npm-0.1.0.tgz
```
## 🚀 Usage
```js
// Import everything
import { commons, request } from '@haina/npm';
// Import only common utilities
import { isEmpty } from '@haina/npm/esm/utils/commons.js';
// Import only request utilities
import { fetchJSON } from '@haina/npm/esm/utils/request.js';
```

@ -0,0 +1,12 @@
"use strict";
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); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.request = exports.commons = void 0;
var _commons = _interopRequireWildcard(require("./utils/commons.js"));
exports.commons = _commons;
var _request = _interopRequireWildcard(require("./utils/request.js"));
exports.request = _request;
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }

@ -0,0 +1,853 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.UrlBuilder = exports.TagColorStyle = void 0;
exports.at = at;
exports.calcCacheSizes = exports.buildTree = void 0;
exports.camelCase = camelCase;
exports.clearAllCaches = exports.cartesianProductArray = void 0;
exports.clickUrl = clickUrl;
exports.cloneDeep = cloneDeep;
exports.copy = copy;
exports.debounce = void 0;
exports.escape2Html = escape2Html;
exports.fixToInt = exports.fixTo4Decimals = exports.fixTo2Decimals = exports.fixTo1Decimals = void 0;
exports.flush = flush;
exports.getNestedValue = exports.formatBytes = void 0;
exports.groupBy = groupBy;
exports.isEmpty = isEmpty;
exports.isNotEmpty = isNotEmpty;
exports.loadScript = void 0;
exports.merge = merge;
exports.numberFormatter = void 0;
exports.objectMapper = objectMapper;
exports.olog = void 0;
exports.omit = omit;
exports.omitEmpty = void 0;
exports.pick = pick;
exports.prepareUrl = prepareUrl;
exports.sortKeys = exports.sortBy = exports.sortArrayByOrder = exports.sanitizeFilename = exports.removeFormattingChars = void 0;
exports.sortObjectsByKeysMap = sortObjectsByKeysMap;
exports.splitArray2Parts = splitArray2Parts;
exports.stringToColour = void 0;
exports.throttle = throttle;
exports.uniqWith = void 0;
exports.unique = unique;
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 _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
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 _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 _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return 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 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 _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 copy(obj) {
return JSON.parse(JSON.stringify(obj));
}
function splitArray2Parts(arr, size) {
var result = [];
for (var i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
function camelCase(name) {
return name.substr(0, 1).toLowerCase() + name.substr(1);
}
var UrlBuilder = exports.UrlBuilder = /*#__PURE__*/function () {
function UrlBuilder(url) {
_classCallCheck(this, UrlBuilder);
this.url = url;
this.paramList = [];
}
return _createClass(UrlBuilder, [{
key: "append",
value: function append(name, value) {
if (isNotEmpty(value)) {
this.paramList.push({
name: name,
value: value
});
}
return this;
}
}, {
key: "build",
value: function build() {
var _this = this;
this.paramList.forEach(function (e, i, a) {
if (i === 0) {
_this.url += "?";
} else {
_this.url += "&";
}
_this.url += e.name + "=" + e.value;
});
return this.url;
}
}]);
}();
function isNotEmpty(val) {
return val !== undefined && val !== null && val !== "";
}
// export function isEmpty(val) {
// return val === undefined || val === null || val === ""
// }
function prepareUrl(url) {
return new UrlBuilder(url);
}
// export function debounce(fn, delay = 500) {
// let timer
// return e => {
// e.persist()
// clearTimeout(timer)
// timer = setTimeout(() => {
// fn(e)
// }, delay)
// }
// }
function throttle(fn, delay, atleast) {
var timeout = null,
startTime = new Date();
return function () {
var curTime = new Date();
clearTimeout(timeout);
if (curTime - startTime >= atleast) {
fn();
startTime = curTime;
} else {
timeout = setTimeout(fn, delay);
}
};
}
function clickUrl(url) {
var httpLink = document.createElement("a");
httpLink.href = url;
httpLink.target = "_blank";
httpLink.click();
}
function escape2Html(str) {
var temp = document.createElement("div");
temp.innerHTML = str;
var output = temp.innerText || temp.textContent;
temp = null;
return output;
}
/**
* ! 不支持计算 Set Map
* @param {*} val
* @example
* true if: 0, [], {}, null, '', undefined
* false if: 'false', 'undefined'
*/
function isEmpty(val) {
// return val === undefined || val === null || val === "";
return [Object, Array].includes((val || {}).constructor) && !Object.entries(val || {}).length;
}
/**
* 数组排序
*/
var sortBy = exports.sortBy = function sortBy(key) {
return function (a, b) {
return a[key] > b[key] ? 1 : b[key] > a[key] ? -1 : 0;
};
};
/**
* Object排序keys
*/
var sortKeys = exports.sortKeys = function sortKeys(obj) {
return Object.keys(obj).sort().reduce(function (a, k2) {
return _objectSpread(_objectSpread({}, a), {}, _defineProperty({}, k2, obj[k2]));
}, {});
};
function sortObjectsByKeysMap(objects, keyOrder) {
if (!objects) return {}; // Handle null/undefined input
if (!keyOrder || keyOrder.length === 0) return objects;
var objectMap = new Map(Object.entries(objects));
var sortedMap = new Map();
var _iterator = _createForOfIteratorHelper(keyOrder),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var key = _step.value;
if (objectMap.has(key)) {
sortedMap.set(key, objectMap.get(key));
objectMap["delete"](key); // Optimization: Remove from original map after adding
}
}
// Add remaining keys
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var _iterator2 = _createForOfIteratorHelper(objectMap),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var _step2$value = _slicedToArray(_step2.value, 2),
_key = _step2$value[0],
value = _step2$value[1];
sortedMap.set(_key, value);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return Object.fromEntries(sortedMap);
}
/**
* 数组排序, 给定排序数组
* @param {array} items 需要排序的数组
* @param {array} keyName 排序的key
* @param {array} keyOrder 给定排序
* @returns
*/
var sortArrayByOrder = exports.sortArrayByOrder = function sortArrayByOrder(items, keyName, keyOrder) {
return items.sort(function (a, b) {
return keyOrder.indexOf(a[keyName]) - keyOrder.indexOf(b[keyName]);
});
};
/**
* 合并Object, 递归地
*/
function merge() {
for (var _len = arguments.length, objects = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
objects[_key2] = arguments[_key2];
}
var isDeep = objects.some(function (obj) {
return obj !== null && _typeof(obj) === 'object';
});
var result = objects[0] || (isDeep ? {} : objects[0]);
var _loop = function _loop() {
var obj = objects[i];
if (!obj) return 1; // continue
Object.keys(obj).forEach(function (key) {
var val = obj[key];
if (isDeep) {
if (Array.isArray(val)) {
result[key] = [].concat(Array.isArray(result[key]) ? result[key] : [result[key]], val);
} else if (_typeof(val) === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
} else {
result[key] = typeof val === 'boolean' ? val : result[key];
}
});
};
for (var i = 1; i < objects.length; i++) {
if (_loop()) continue;
}
return result;
}
/**
* 数组分组
* - 相当于 lodash _.groupBy
* @see https://www.lodashjs.com/docs/lodash.groupBy#_groupbycollection-iteratee_identity
* ECMAScript 2021 原生
* - Object.groupBy(items, callbackFn)
*/
function groupBy() {
var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var callback = arguments.length > 1 ? arguments[1] : undefined;
return array.reduce(function (groups, item) {
var key = typeof callback === 'function' ? callback(item) : item[callback];
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(item);
return groups;
}, {});
}
/**
* 创建一个从 object 中选中的属性的对象
* @param {*} object
* @param {array} keys
*/
function pick(object, keys) {
return keys.reduce(function (obj, key) {
if (object && Object.prototype.hasOwnProperty.call(object, key)) {
obj[key] = object[key];
}
return obj;
}, {});
}
/**
* 返回对象的副本经过筛选以省略指定的键
* @param {*} object
* @param {string[]} keysToOmit
* @returns
*/
function omit(object, keysToOmit) {
return Object.fromEntries(Object.entries(object).filter(function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
key = _ref2[0];
return !keysToOmit.includes(key);
}));
}
/**
* 去除无效的值: undefined, null, '', []
* * 只删除 null undefined: flush 方法;
*/
var omitEmpty = exports.omitEmpty = function omitEmpty(_object) {
Object.keys(_object).forEach(function (key) {
return (_object[key] == null || _object[key] === '' || _object[key].length === 0) && delete _object[key];
});
return _object;
};
/**
* 深拷贝
*/
function cloneDeep(value) {
// return structuredClone(value);
if (_typeof(value) !== 'object' || value === null) {
return value;
}
var result = Array.isArray(value) ? [] : {};
for (var key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
result[key] = cloneDeep(value[key]);
}
}
return result;
}
/**
* 向零四舍五入, 固定精度设置
*/
function curriedFix() {
var precision = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return function (number) {
// Shift number by precision places
var shift = Math.pow(10, precision);
var shiftedNumber = number * shift;
// Round to nearest integer
var roundedNumber = Math.round(shiftedNumber);
// Shift back decimal place
return roundedNumber / shift;
};
}
/**
* 向零四舍五入, 保留2位小数
*/
var fixTo2Decimals = exports.fixTo2Decimals = curriedFix(2);
/**
* 向零四舍五入, 保留4位小数
*/
var fixTo4Decimals = exports.fixTo4Decimals = curriedFix(4);
var fixTo1Decimals = exports.fixTo1Decimals = curriedFix(1);
var fixToInt = exports.fixToInt = curriedFix(0);
/**
* 映射
* @example
* const keyMap = {
a: [{key: 'a1'}, {key: 'a2', transform: v => v * 2}],
b: {key: 'b1'}
};
const result = objectMapper({a: 1, b: 3}, keyMap);
// result = {a1: 1, a2: 2, b1: 3}
*
*/
function objectMapper(input, keyMap) {
// Loop through array mapping
if (Array.isArray(input)) {
return input.map(function (obj) {
return objectMapper(obj, keyMap);
});
}
if (_typeof(input) === 'object') {
var mappedObj = {};
Object.keys(input).forEach(function (key) {
// Keep original keys not in keyMap
if (!keyMap[key]) {
mappedObj[key] = input[key];
}
// Handle array of maps
if (Array.isArray(keyMap[key])) {
keyMap[key].forEach(function (map) {
var value = input[key];
if (map.transform) value = map.transform(value);
mappedObj[map.key] = value;
});
// Handle single map
} else {
var map = keyMap[key];
if (map) {
var value = input[key];
if (map.transform) value = map.transform(value);
mappedObj[map.key || key] = value;
}
}
});
return mappedObj;
}
return input;
}
/**
* 创建一个对应于对象路径的值数组
*/
function at(obj, path) {
var result;
if (Array.isArray(obj)) {
// array case
var indexes = path.split('.').map(function (i) {
return parseInt(i);
});
result = [];
for (var i = 0; i < indexes.length; i++) {
result.push(obj[indexes[i]]);
}
} else {
// object case
var _indexes = path.split('.').map(function (i) {
return i;
});
result = [obj];
for (var _i = 0; _i < _indexes.length; _i++) {
result = [result[0][_indexes[_i]]];
}
}
return result;
}
/**
* 删除 null/undefined
*/
function flush(collection) {
var result, len, i;
if (!collection) {
return undefined;
}
if (Array.isArray(collection)) {
result = [];
len = collection.length;
for (i = 0; i < len; i++) {
var elem = collection[i];
if (elem != null) {
result.push(elem);
}
}
return result;
}
if (_typeof(collection) === 'object') {
result = {};
var keys = Object.keys(collection);
len = keys.length;
for (i = 0; i < len; i++) {
var key = keys[i];
var value = collection[key];
if (value != null) {
result[key] = value;
}
}
return result;
}
return undefined;
}
/**
* 千分位 格式化数字
*/
var numberFormatter = exports.numberFormatter = function numberFormatter(number) {
return new Intl.NumberFormat().format(number);
};
/**
* @example
* const obj = { a: { b: 'c' } };
* const keyArr = ['a', 'b'];
* getNestedValue(obj, keyArr); // Returns: 'c'
*/
var getNestedValue = exports.getNestedValue = function getNestedValue(obj, keyArr) {
return keyArr.reduce(function (acc, curr) {
return acc && Object.prototype.hasOwnProperty.call(acc, curr) ? acc[curr] : undefined;
// return acc && acc[curr];
}, obj);
};
/**
* 计算笛卡尔积
*/
var _cartesianProductArray = exports.cartesianProductArray = function cartesianProductArray(arr) {
var sep = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '_';
var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var prefix = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
var result = [];
if (index === arr.length) {
return [prefix];
}
arr[index].forEach(function (item) {
result = result.concat(_cartesianProductArray(arr, sep, index + 1, prefix ? "".concat(prefix).concat(sep).concat(item) : "".concat(item)));
});
return result;
};
var stringToColour = exports.stringToColour = function stringToColour() {
var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var withFlag = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var hash = 0;
if (str.length === 0) return hash;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = withFlag ? '#' : '';
for (var _i2 = 0; _i2 < 3; _i2++) {
var value = hash >> _i2 * 8 & 0xff;
value = value % 150 + 50;
colour += ('00' + value.toString(16)).substr(-2);
}
return colour;
};
var debounce = exports.debounce = function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this,
args = arguments;
clearTimeout(timeout);
if (immediate && !timeout) func.apply(context, args);
timeout = setTimeout(function () {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
};
};
var removeFormattingChars = exports.removeFormattingChars = function removeFormattingChars(str) {
var regex = /[\r\n\t\v\f]/g;
str = str.replace(regex, ' ');
// Replace more than four consecutive spaces with a single space
str = str.replace(/\s{4,}/g, ' ');
return str;
};
var olog = exports.olog = function olog(text) {
var _console;
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key3 = 1; _key3 < _len2; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
(_console = console).log.apply(_console, ["%c ".concat(text, " "), 'background:#fb923c ; padding: 1px; border-radius: 3px; color: #fff'].concat(args));
};
var sanitizeFilename = exports.sanitizeFilename = function sanitizeFilename(str) {
// Remove whitespace and replace with hyphens
str = str.replace(/\s+/g, '-');
// Remove invalid characters and replace with hyphens
str = str.replace(/[^a-zA-Z0-9.-]/g, '-');
// Replace consecutive hyphens with a single hyphen
str = str.replace(/-+/g, '-');
// Trim leading and trailing hyphens
str = str.replace(/^-+|-+$/g, '');
return str;
};
var formatBytes = exports.formatBytes = function formatBytes(bytes) {
var decimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
if (bytes === 0) return '';
var k = 1024;
var dm = decimals < 0 ? 0 : decimals;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
var calcCacheSizes = exports.calcCacheSizes = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
var swCacheSize, diskCacheSize, indexedDBSize, cacheNames, _iterator3, _step3, name, cache, requests, _iterator4, _step4, request, response, _t, _t2, _t3;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
_context.p = 0;
swCacheSize = 0;
diskCacheSize = 0;
indexedDBSize = 0; // 1. Get the service worker cache size
if (!('caches' in window)) {
_context.n = 17;
break;
}
_context.n = 1;
return caches.keys();
case 1:
cacheNames = _context.v;
_iterator3 = _createForOfIteratorHelper(cacheNames);
_context.p = 2;
_iterator3.s();
case 3:
if ((_step3 = _iterator3.n()).done) {
_context.n = 14;
break;
}
name = _step3.value;
_context.n = 4;
return caches.open(name);
case 4:
cache = _context.v;
_context.n = 5;
return cache.keys();
case 5:
requests = _context.v;
_iterator4 = _createForOfIteratorHelper(requests);
_context.p = 6;
_iterator4.s();
case 7:
if ((_step4 = _iterator4.n()).done) {
_context.n = 10;
break;
}
request = _step4.value;
_context.n = 8;
return cache.match(request);
case 8:
response = _context.v;
swCacheSize += Number(response.headers.get('Content-Length')) || 0;
case 9:
_context.n = 7;
break;
case 10:
_context.n = 12;
break;
case 11:
_context.p = 11;
_t = _context.v;
_iterator4.e(_t);
case 12:
_context.p = 12;
_iterator4.f();
return _context.f(12);
case 13:
_context.n = 3;
break;
case 14:
_context.n = 16;
break;
case 15:
_context.p = 15;
_t2 = _context.v;
_iterator3.e(_t2);
case 16:
_context.p = 16;
_iterator3.f();
return _context.f(16);
case 17:
return _context.a(2, {
swCacheSize: swCacheSize,
diskCacheSize: diskCacheSize,
indexedDBSize: indexedDBSize,
totalSize: Number(swCacheSize) + Number(diskCacheSize) + indexedDBSize
});
case 18:
_context.p = 18;
_t3 = _context.v;
console.error('Error getting cache sizes:', _t3);
case 19:
return _context.a(2);
}
}, _callee, null, [[6, 11, 12, 13], [2, 15, 16, 17], [0, 18]]);
}));
return function calcCacheSizes() {
return _ref3.apply(this, arguments);
};
}();
var clearAllCaches = exports.clearAllCaches = /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(cb) {
var cacheNames, indexedDBNames, registration, _t4;
return _regenerator().w(function (_context2) {
while (1) switch (_context2.p = _context2.n) {
case 0:
_context2.p = 0;
if (!('caches' in window)) {
_context2.n = 2;
break;
}
_context2.n = 1;
return caches.keys();
case 1:
cacheNames = _context2.v;
_context2.n = 2;
return Promise.all(cacheNames.map(function (name) {
return caches["delete"](name);
}));
case 2:
_context2.n = 3;
return window.indexedDB.databases();
case 3:
indexedDBNames = _context2.v;
_context2.n = 4;
return Promise.all(indexedDBNames.map(function (dbName) {
return window.indexedDB.deleteDatabase(dbName.name);
}));
case 4:
_context2.n = 5;
return navigator.serviceWorker.getRegistration();
case 5:
registration = _context2.v;
if (!registration) {
_context2.n = 7;
break;
}
_context2.n = 6;
return registration.unregister();
case 6:
console.log('Service worker unregistered');
_context2.n = 8;
break;
case 7:
console.log('No service worker registered');
case 8:
if (typeof cb === 'function') {
cb();
}
_context2.n = 10;
break;
case 9:
_context2.p = 9;
_t4 = _context2.v;
console.error('Error clearing caches or unregistering service worker:', _t4);
case 10:
return _context2.a(2);
}
}, _callee2, null, [[0, 9]]);
}));
return function clearAllCaches(_x) {
return _ref4.apply(this, arguments);
};
}();
var loadScript = exports.loadScript = function loadScript(src) {
return new Promise(function (resolve, reject) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.onload = resolve;
script.onerror = reject;
script.crossOrigin = 'anonymous';
script.src = src;
if (document.head.append) {
document.head.append(script);
} else {
document.getElementsByTagName('head')[0].appendChild(script);
}
});
};
var TagColorStyle = exports.TagColorStyle = function TagColorStyle(tag) {
var outerStyle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var color = stringToColour(tag);
var outerStyleObj = outerStyle ? {
borderColor: "".concat(color, "66"),
backgroundColor: "".concat(color, "0D")
} : {};
return _objectSpread({
color: "".concat(color)
}, outerStyleObj);
};
// 数组去掉重复
function unique(arr) {
var x = new Set(arr);
return _toConsumableArray(x);
}
var uniqWith = exports.uniqWith = function uniqWith(arr, fn) {
return arr.filter(function (element, index) {
return arr.findIndex(function (step) {
return fn(element, step);
}) === index;
});
};
/**
* Creates a new tree node object.
* @param {string} key - The unique identifier for the node.
* @param {string} name - The display name of the node.
* @param {string|null} parent - The key of the parent node, or null if it's a root.
* @returns {object} A plain JavaScript object representing the tree node.
*/
function createTreeNode(key, name) {
var parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var keyMap = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var _raw = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
return {
key: key,
title: name,
parent: parent,
icon: _raw === null || _raw === void 0 ? void 0 : _raw.icon,
iconIndex: _raw === null || _raw === void 0 ? void 0 : _raw[keyMap.iconIndex],
_raw: _raw,
children: [],
parentTitle: '',
parentIconIndex: ''
};
}
/**
* Builds a tree structure from a flat list of nodes.
* @returns {Array<object>} An array of root tree nodes.
*/
var buildTree = exports.buildTree = function buildTree(list) {
var keyMap = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
rootKeys: [],
ignoreKeys: []
};
if (!list || list.length === 0) {
return [];
}
var nodeMap = new Map();
var treeRoots = [];
list.forEach(function (item) {
var node = createTreeNode(item[keyMap.key], item[keyMap.name], item[keyMap.parent], keyMap, item);
nodeMap.set(item[keyMap.key], node);
});
list.forEach(function (item) {
var node = nodeMap.get(item[keyMap.key]);
if (keyMap.rootKeys.includes(item[keyMap.parent]) || item[keyMap.parent] === null || item[keyMap.parent] === undefined) {
// This is a root node
treeRoots.push(node);
} else {
var parentNode = nodeMap.get(item[keyMap.parent]);
if (keyMap.ignoreKeys.includes(item[keyMap.parent])) {
var grandParentNode = nodeMap.get(parentNode.parent);
node.rawParent = node.parent;
node.parent = parentNode.parent;
node.parentTitle = parentNode.title;
node.parentIconIndex = parentNode.iconIndex;
grandParentNode.children.push(node);
} else if (keyMap.ignoreKeys.includes(item[keyMap.key])) {
//
} else if (parentNode) {
node.parentTitle = parentNode.title;
node.parentIconIndex = parentNode.iconIndex;
parentNode.children.push(node);
} else {
console.warn("Parent with key '".concat(item[keyMap.parent], "' not found for node '").concat(item[keyMap.key], "'. This node will be treated as a root."));
treeRoots.push(node);
}
}
});
return treeRoots;
};

@ -0,0 +1,126 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.appendRequestHeader = appendRequestHeader;
exports.fetchJSON = fetchJSON;
exports.fetchText = fetchText;
exports.postForm = postForm;
exports.postJSON = postJSON;
exports.postStream = postStream;
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 _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 _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); }
// import { BUILD_VERSION } from '@/config'
var BUILD_VERSION = '';
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
var customHeaders = [];
// 添加 HTTP Reuqest 自定义头部
function appendRequestHeader(n, v) {
customHeaders.push({
name: n,
value: v
});
}
function getRequestHeader() {
return customHeaders.reduce(function (acc, item) {
acc[item.name] = item.value;
return acc;
}, {});
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
var message = 'Fetch error: ' + response.url + ' ' + response.status + ' (' + response.statusText + ')';
var error = new Error(message);
error.response = response;
throw error;
}
}
function checkBizCode(responseJson) {
if (responseJson.errcode === 0) {
return responseJson;
} else {
throw new Error(responseJson.errmsg + ': ' + responseJson.errcode);
}
}
function fetchText(url) {
var headerObj = getRequestHeader();
return fetch(url, {
method: 'GET',
headers: _objectSpread({
'X-Web-Version': BUILD_VERSION
}, headerObj)
}).then(checkStatus).then(function (response) {
return response.text();
})["catch"](function (error) {
throw error;
});
}
function fetchJSON(url, data) {
var params = data ? new URLSearchParams(data).toString() : '';
var ifp = url.includes('?') ? data ? '&' : '' : '?';
var headerObj = getRequestHeader();
return fetch("".concat(url).concat(ifp).concat(params), {
method: 'GET',
headers: _objectSpread({
'X-Web-Version': BUILD_VERSION
}, headerObj)
}).then(checkStatus).then(function (response) {
return response.json();
}).then(checkBizCode)["catch"](function (error) {
throw error;
});
}
function postForm(url, data) {
var headerObj = getRequestHeader();
return fetch(url, {
method: 'POST',
body: data,
headers: _objectSpread({
'X-Web-Version': BUILD_VERSION
}, headerObj)
}).then(checkStatus).then(function (response) {
return response.json();
}).then(checkBizCode)["catch"](function (error) {
throw error;
});
}
function postJSON(url, obj) {
var headerObj = getRequestHeader();
return fetch(url, {
method: 'POST',
body: JSON.stringify(obj),
headers: _objectSpread({
'Content-type': 'application/json; charset=UTF-8',
'X-Web-Version': BUILD_VERSION
}, headerObj)
}).then(checkStatus).then(function (response) {
return response.json();
}).then(checkBizCode)["catch"](function (error) {
throw error;
});
}
function postStream(url, obj) {
var headerObj = getRequestHeader();
return fetch(url, {
method: 'POST',
body: JSON.stringify(obj),
headers: _objectSpread({
'Content-type': 'application/octet-stream',
'X-Web-Version': BUILD_VERSION
}, headerObj)
}).then(checkStatus).then(function (response) {
return response.json();
}).then(checkBizCode)["catch"](function (error) {
throw error;
});
}

@ -0,0 +1,4 @@
import * as _commons from './utils/commons.js';
export { _commons as commons };
import * as _request from './utils/request.js';
export { _request as request };

@ -0,0 +1,817 @@
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 _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
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 _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 _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return 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 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 _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); }
export function copy(obj) {
return JSON.parse(JSON.stringify(obj));
}
export function splitArray2Parts(arr, size) {
var result = [];
for (var i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
export function camelCase(name) {
return name.substr(0, 1).toLowerCase() + name.substr(1);
}
export var UrlBuilder = /*#__PURE__*/function () {
function UrlBuilder(url) {
_classCallCheck(this, UrlBuilder);
this.url = url;
this.paramList = [];
}
return _createClass(UrlBuilder, [{
key: "append",
value: function append(name, value) {
if (isNotEmpty(value)) {
this.paramList.push({
name: name,
value: value
});
}
return this;
}
}, {
key: "build",
value: function build() {
var _this = this;
this.paramList.forEach(function (e, i, a) {
if (i === 0) {
_this.url += "?";
} else {
_this.url += "&";
}
_this.url += e.name + "=" + e.value;
});
return this.url;
}
}]);
}();
export function isNotEmpty(val) {
return val !== undefined && val !== null && val !== "";
}
// export function isEmpty(val) {
// return val === undefined || val === null || val === ""
// }
export function prepareUrl(url) {
return new UrlBuilder(url);
}
// export function debounce(fn, delay = 500) {
// let timer
// return e => {
// e.persist()
// clearTimeout(timer)
// timer = setTimeout(() => {
// fn(e)
// }, delay)
// }
// }
export function throttle(fn, delay, atleast) {
var timeout = null,
startTime = new Date();
return function () {
var curTime = new Date();
clearTimeout(timeout);
if (curTime - startTime >= atleast) {
fn();
startTime = curTime;
} else {
timeout = setTimeout(fn, delay);
}
};
}
export function clickUrl(url) {
var httpLink = document.createElement("a");
httpLink.href = url;
httpLink.target = "_blank";
httpLink.click();
}
export function escape2Html(str) {
var temp = document.createElement("div");
temp.innerHTML = str;
var output = temp.innerText || temp.textContent;
temp = null;
return output;
}
/**
* ! 不支持计算 Set Map
* @param {*} val
* @example
* true if: 0, [], {}, null, '', undefined
* false if: 'false', 'undefined'
*/
export function isEmpty(val) {
// return val === undefined || val === null || val === "";
return [Object, Array].includes((val || {}).constructor) && !Object.entries(val || {}).length;
}
/**
* 数组排序
*/
export var sortBy = function sortBy(key) {
return function (a, b) {
return a[key] > b[key] ? 1 : b[key] > a[key] ? -1 : 0;
};
};
/**
* Object排序keys
*/
export var sortKeys = function sortKeys(obj) {
return Object.keys(obj).sort().reduce(function (a, k2) {
return _objectSpread(_objectSpread({}, a), {}, _defineProperty({}, k2, obj[k2]));
}, {});
};
export function sortObjectsByKeysMap(objects, keyOrder) {
if (!objects) return {}; // Handle null/undefined input
if (!keyOrder || keyOrder.length === 0) return objects;
var objectMap = new Map(Object.entries(objects));
var sortedMap = new Map();
var _iterator = _createForOfIteratorHelper(keyOrder),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var key = _step.value;
if (objectMap.has(key)) {
sortedMap.set(key, objectMap.get(key));
objectMap["delete"](key); // Optimization: Remove from original map after adding
}
}
// Add remaining keys
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var _iterator2 = _createForOfIteratorHelper(objectMap),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var _step2$value = _slicedToArray(_step2.value, 2),
_key = _step2$value[0],
value = _step2$value[1];
sortedMap.set(_key, value);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return Object.fromEntries(sortedMap);
}
/**
* 数组排序, 给定排序数组
* @param {array} items 需要排序的数组
* @param {array} keyName 排序的key
* @param {array} keyOrder 给定排序
* @returns
*/
export var sortArrayByOrder = function sortArrayByOrder(items, keyName, keyOrder) {
return items.sort(function (a, b) {
return keyOrder.indexOf(a[keyName]) - keyOrder.indexOf(b[keyName]);
});
};
/**
* 合并Object, 递归地
*/
export function merge() {
for (var _len = arguments.length, objects = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
objects[_key2] = arguments[_key2];
}
var isDeep = objects.some(function (obj) {
return obj !== null && _typeof(obj) === 'object';
});
var result = objects[0] || (isDeep ? {} : objects[0]);
var _loop = function _loop() {
var obj = objects[i];
if (!obj) return 1; // continue
Object.keys(obj).forEach(function (key) {
var val = obj[key];
if (isDeep) {
if (Array.isArray(val)) {
result[key] = [].concat(Array.isArray(result[key]) ? result[key] : [result[key]], val);
} else if (_typeof(val) === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
} else {
result[key] = typeof val === 'boolean' ? val : result[key];
}
});
};
for (var i = 1; i < objects.length; i++) {
if (_loop()) continue;
}
return result;
}
/**
* 数组分组
* - 相当于 lodash _.groupBy
* @see https://www.lodashjs.com/docs/lodash.groupBy#_groupbycollection-iteratee_identity
* ECMAScript 2021 原生
* - Object.groupBy(items, callbackFn)
*/
export function groupBy() {
var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var callback = arguments.length > 1 ? arguments[1] : undefined;
return array.reduce(function (groups, item) {
var key = typeof callback === 'function' ? callback(item) : item[callback];
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(item);
return groups;
}, {});
}
/**
* 创建一个从 object 中选中的属性的对象
* @param {*} object
* @param {array} keys
*/
export function pick(object, keys) {
return keys.reduce(function (obj, key) {
if (object && Object.prototype.hasOwnProperty.call(object, key)) {
obj[key] = object[key];
}
return obj;
}, {});
}
/**
* 返回对象的副本经过筛选以省略指定的键
* @param {*} object
* @param {string[]} keysToOmit
* @returns
*/
export function omit(object, keysToOmit) {
return Object.fromEntries(Object.entries(object).filter(function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
key = _ref2[0];
return !keysToOmit.includes(key);
}));
}
/**
* 去除无效的值: undefined, null, '', []
* * 只删除 null undefined: flush 方法;
*/
export var omitEmpty = function omitEmpty(_object) {
Object.keys(_object).forEach(function (key) {
return (_object[key] == null || _object[key] === '' || _object[key].length === 0) && delete _object[key];
});
return _object;
};
/**
* 深拷贝
*/
export function cloneDeep(value) {
// return structuredClone(value);
if (_typeof(value) !== 'object' || value === null) {
return value;
}
var result = Array.isArray(value) ? [] : {};
for (var key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
result[key] = cloneDeep(value[key]);
}
}
return result;
}
/**
* 向零四舍五入, 固定精度设置
*/
function curriedFix() {
var precision = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return function (number) {
// Shift number by precision places
var shift = Math.pow(10, precision);
var shiftedNumber = number * shift;
// Round to nearest integer
var roundedNumber = Math.round(shiftedNumber);
// Shift back decimal place
return roundedNumber / shift;
};
}
/**
* 向零四舍五入, 保留2位小数
*/
export var fixTo2Decimals = curriedFix(2);
/**
* 向零四舍五入, 保留4位小数
*/
export var fixTo4Decimals = curriedFix(4);
export var fixTo1Decimals = curriedFix(1);
export var fixToInt = curriedFix(0);
/**
* 映射
* @example
* const keyMap = {
a: [{key: 'a1'}, {key: 'a2', transform: v => v * 2}],
b: {key: 'b1'}
};
const result = objectMapper({a: 1, b: 3}, keyMap);
// result = {a1: 1, a2: 2, b1: 3}
*
*/
export function objectMapper(input, keyMap) {
// Loop through array mapping
if (Array.isArray(input)) {
return input.map(function (obj) {
return objectMapper(obj, keyMap);
});
}
if (_typeof(input) === 'object') {
var mappedObj = {};
Object.keys(input).forEach(function (key) {
// Keep original keys not in keyMap
if (!keyMap[key]) {
mappedObj[key] = input[key];
}
// Handle array of maps
if (Array.isArray(keyMap[key])) {
keyMap[key].forEach(function (map) {
var value = input[key];
if (map.transform) value = map.transform(value);
mappedObj[map.key] = value;
});
// Handle single map
} else {
var map = keyMap[key];
if (map) {
var value = input[key];
if (map.transform) value = map.transform(value);
mappedObj[map.key || key] = value;
}
}
});
return mappedObj;
}
return input;
}
/**
* 创建一个对应于对象路径的值数组
*/
export function at(obj, path) {
var result;
if (Array.isArray(obj)) {
// array case
var indexes = path.split('.').map(function (i) {
return parseInt(i);
});
result = [];
for (var i = 0; i < indexes.length; i++) {
result.push(obj[indexes[i]]);
}
} else {
// object case
var _indexes = path.split('.').map(function (i) {
return i;
});
result = [obj];
for (var _i = 0; _i < _indexes.length; _i++) {
result = [result[0][_indexes[_i]]];
}
}
return result;
}
/**
* 删除 null/undefined
*/
export function flush(collection) {
var result, len, i;
if (!collection) {
return undefined;
}
if (Array.isArray(collection)) {
result = [];
len = collection.length;
for (i = 0; i < len; i++) {
var elem = collection[i];
if (elem != null) {
result.push(elem);
}
}
return result;
}
if (_typeof(collection) === 'object') {
result = {};
var keys = Object.keys(collection);
len = keys.length;
for (i = 0; i < len; i++) {
var key = keys[i];
var value = collection[key];
if (value != null) {
result[key] = value;
}
}
return result;
}
return undefined;
}
/**
* 千分位 格式化数字
*/
export var numberFormatter = function numberFormatter(number) {
return new Intl.NumberFormat().format(number);
};
/**
* @example
* const obj = { a: { b: 'c' } };
* const keyArr = ['a', 'b'];
* getNestedValue(obj, keyArr); // Returns: 'c'
*/
export var getNestedValue = function getNestedValue(obj, keyArr) {
return keyArr.reduce(function (acc, curr) {
return acc && Object.prototype.hasOwnProperty.call(acc, curr) ? acc[curr] : undefined;
// return acc && acc[curr];
}, obj);
};
/**
* 计算笛卡尔积
*/
var _cartesianProductArray = function cartesianProductArray(arr) {
var sep = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '_';
var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var prefix = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
var result = [];
if (index === arr.length) {
return [prefix];
}
arr[index].forEach(function (item) {
result = result.concat(_cartesianProductArray(arr, sep, index + 1, prefix ? "".concat(prefix).concat(sep).concat(item) : "".concat(item)));
});
return result;
};
export { _cartesianProductArray as cartesianProductArray };
export var stringToColour = function stringToColour() {
var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var withFlag = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var hash = 0;
if (str.length === 0) return hash;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = withFlag ? '#' : '';
for (var _i2 = 0; _i2 < 3; _i2++) {
var value = hash >> _i2 * 8 & 0xff;
value = value % 150 + 50;
colour += ('00' + value.toString(16)).substr(-2);
}
return colour;
};
export var debounce = function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this,
args = arguments;
clearTimeout(timeout);
if (immediate && !timeout) func.apply(context, args);
timeout = setTimeout(function () {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
};
};
export var removeFormattingChars = function removeFormattingChars(str) {
var regex = /[\r\n\t\v\f]/g;
str = str.replace(regex, ' ');
// Replace more than four consecutive spaces with a single space
str = str.replace(/\s{4,}/g, ' ');
return str;
};
export var olog = function olog(text) {
var _console;
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key3 = 1; _key3 < _len2; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
(_console = console).log.apply(_console, ["%c ".concat(text, " "), 'background:#fb923c ; padding: 1px; border-radius: 3px; color: #fff'].concat(args));
};
export var sanitizeFilename = function sanitizeFilename(str) {
// Remove whitespace and replace with hyphens
str = str.replace(/\s+/g, '-');
// Remove invalid characters and replace with hyphens
str = str.replace(/[^a-zA-Z0-9.-]/g, '-');
// Replace consecutive hyphens with a single hyphen
str = str.replace(/-+/g, '-');
// Trim leading and trailing hyphens
str = str.replace(/^-+|-+$/g, '');
return str;
};
export var formatBytes = function formatBytes(bytes) {
var decimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
if (bytes === 0) return '';
var k = 1024;
var dm = decimals < 0 ? 0 : decimals;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
export var calcCacheSizes = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
var swCacheSize, diskCacheSize, indexedDBSize, cacheNames, _iterator3, _step3, name, cache, requests, _iterator4, _step4, request, response, _t, _t2, _t3;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
_context.p = 0;
swCacheSize = 0;
diskCacheSize = 0;
indexedDBSize = 0; // 1. Get the service worker cache size
if (!('caches' in window)) {
_context.n = 17;
break;
}
_context.n = 1;
return caches.keys();
case 1:
cacheNames = _context.v;
_iterator3 = _createForOfIteratorHelper(cacheNames);
_context.p = 2;
_iterator3.s();
case 3:
if ((_step3 = _iterator3.n()).done) {
_context.n = 14;
break;
}
name = _step3.value;
_context.n = 4;
return caches.open(name);
case 4:
cache = _context.v;
_context.n = 5;
return cache.keys();
case 5:
requests = _context.v;
_iterator4 = _createForOfIteratorHelper(requests);
_context.p = 6;
_iterator4.s();
case 7:
if ((_step4 = _iterator4.n()).done) {
_context.n = 10;
break;
}
request = _step4.value;
_context.n = 8;
return cache.match(request);
case 8:
response = _context.v;
swCacheSize += Number(response.headers.get('Content-Length')) || 0;
case 9:
_context.n = 7;
break;
case 10:
_context.n = 12;
break;
case 11:
_context.p = 11;
_t = _context.v;
_iterator4.e(_t);
case 12:
_context.p = 12;
_iterator4.f();
return _context.f(12);
case 13:
_context.n = 3;
break;
case 14:
_context.n = 16;
break;
case 15:
_context.p = 15;
_t2 = _context.v;
_iterator3.e(_t2);
case 16:
_context.p = 16;
_iterator3.f();
return _context.f(16);
case 17:
return _context.a(2, {
swCacheSize: swCacheSize,
diskCacheSize: diskCacheSize,
indexedDBSize: indexedDBSize,
totalSize: Number(swCacheSize) + Number(diskCacheSize) + indexedDBSize
});
case 18:
_context.p = 18;
_t3 = _context.v;
console.error('Error getting cache sizes:', _t3);
case 19:
return _context.a(2);
}
}, _callee, null, [[6, 11, 12, 13], [2, 15, 16, 17], [0, 18]]);
}));
return function calcCacheSizes() {
return _ref3.apply(this, arguments);
};
}();
export var clearAllCaches = /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(cb) {
var cacheNames, indexedDBNames, registration, _t4;
return _regenerator().w(function (_context2) {
while (1) switch (_context2.p = _context2.n) {
case 0:
_context2.p = 0;
if (!('caches' in window)) {
_context2.n = 2;
break;
}
_context2.n = 1;
return caches.keys();
case 1:
cacheNames = _context2.v;
_context2.n = 2;
return Promise.all(cacheNames.map(function (name) {
return caches["delete"](name);
}));
case 2:
_context2.n = 3;
return window.indexedDB.databases();
case 3:
indexedDBNames = _context2.v;
_context2.n = 4;
return Promise.all(indexedDBNames.map(function (dbName) {
return window.indexedDB.deleteDatabase(dbName.name);
}));
case 4:
_context2.n = 5;
return navigator.serviceWorker.getRegistration();
case 5:
registration = _context2.v;
if (!registration) {
_context2.n = 7;
break;
}
_context2.n = 6;
return registration.unregister();
case 6:
console.log('Service worker unregistered');
_context2.n = 8;
break;
case 7:
console.log('No service worker registered');
case 8:
if (typeof cb === 'function') {
cb();
}
_context2.n = 10;
break;
case 9:
_context2.p = 9;
_t4 = _context2.v;
console.error('Error clearing caches or unregistering service worker:', _t4);
case 10:
return _context2.a(2);
}
}, _callee2, null, [[0, 9]]);
}));
return function clearAllCaches(_x) {
return _ref4.apply(this, arguments);
};
}();
export var loadScript = function loadScript(src) {
return new Promise(function (resolve, reject) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.onload = resolve;
script.onerror = reject;
script.crossOrigin = 'anonymous';
script.src = src;
if (document.head.append) {
document.head.append(script);
} else {
document.getElementsByTagName('head')[0].appendChild(script);
}
});
};
export var TagColorStyle = function TagColorStyle(tag) {
var outerStyle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var color = stringToColour(tag);
var outerStyleObj = outerStyle ? {
borderColor: "".concat(color, "66"),
backgroundColor: "".concat(color, "0D")
} : {};
return _objectSpread({
color: "".concat(color)
}, outerStyleObj);
};
// 数组去掉重复
export function unique(arr) {
var x = new Set(arr);
return _toConsumableArray(x);
}
export var uniqWith = function uniqWith(arr, fn) {
return arr.filter(function (element, index) {
return arr.findIndex(function (step) {
return fn(element, step);
}) === index;
});
};
/**
* Creates a new tree node object.
* @param {string} key - The unique identifier for the node.
* @param {string} name - The display name of the node.
* @param {string|null} parent - The key of the parent node, or null if it's a root.
* @returns {object} A plain JavaScript object representing the tree node.
*/
function createTreeNode(key, name) {
var parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var keyMap = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var _raw = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
return {
key: key,
title: name,
parent: parent,
icon: _raw === null || _raw === void 0 ? void 0 : _raw.icon,
iconIndex: _raw === null || _raw === void 0 ? void 0 : _raw[keyMap.iconIndex],
_raw: _raw,
children: [],
parentTitle: '',
parentIconIndex: ''
};
}
/**
* Builds a tree structure from a flat list of nodes.
* @returns {Array<object>} An array of root tree nodes.
*/
export var buildTree = function buildTree(list) {
var keyMap = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
rootKeys: [],
ignoreKeys: []
};
if (!list || list.length === 0) {
return [];
}
var nodeMap = new Map();
var treeRoots = [];
list.forEach(function (item) {
var node = createTreeNode(item[keyMap.key], item[keyMap.name], item[keyMap.parent], keyMap, item);
nodeMap.set(item[keyMap.key], node);
});
list.forEach(function (item) {
var node = nodeMap.get(item[keyMap.key]);
if (keyMap.rootKeys.includes(item[keyMap.parent]) || item[keyMap.parent] === null || item[keyMap.parent] === undefined) {
// This is a root node
treeRoots.push(node);
} else {
var parentNode = nodeMap.get(item[keyMap.parent]);
if (keyMap.ignoreKeys.includes(item[keyMap.parent])) {
var grandParentNode = nodeMap.get(parentNode.parent);
node.rawParent = node.parent;
node.parent = parentNode.parent;
node.parentTitle = parentNode.title;
node.parentIconIndex = parentNode.iconIndex;
grandParentNode.children.push(node);
} else if (keyMap.ignoreKeys.includes(item[keyMap.key])) {
//
} else if (parentNode) {
node.parentTitle = parentNode.title;
node.parentIconIndex = parentNode.iconIndex;
parentNode.children.push(node);
} else {
console.warn("Parent with key '".concat(item[keyMap.parent], "' not found for node '").concat(item[keyMap.key], "'. This node will be treated as a root."));
treeRoots.push(node);
}
}
});
return treeRoots;
};

@ -0,0 +1,115 @@
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 _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 _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); }
// import { BUILD_VERSION } from '@/config'
var BUILD_VERSION = '';
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
var customHeaders = [];
// 添加 HTTP Reuqest 自定义头部
export function appendRequestHeader(n, v) {
customHeaders.push({
name: n,
value: v
});
}
function getRequestHeader() {
return customHeaders.reduce(function (acc, item) {
acc[item.name] = item.value;
return acc;
}, {});
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
var message = 'Fetch error: ' + response.url + ' ' + response.status + ' (' + response.statusText + ')';
var error = new Error(message);
error.response = response;
throw error;
}
}
function checkBizCode(responseJson) {
if (responseJson.errcode === 0) {
return responseJson;
} else {
throw new Error(responseJson.errmsg + ': ' + responseJson.errcode);
}
}
export function fetchText(url) {
var headerObj = getRequestHeader();
return fetch(url, {
method: 'GET',
headers: _objectSpread({
'X-Web-Version': BUILD_VERSION
}, headerObj)
}).then(checkStatus).then(function (response) {
return response.text();
})["catch"](function (error) {
throw error;
});
}
export function fetchJSON(url, data) {
var params = data ? new URLSearchParams(data).toString() : '';
var ifp = url.includes('?') ? data ? '&' : '' : '?';
var headerObj = getRequestHeader();
return fetch("".concat(url).concat(ifp).concat(params), {
method: 'GET',
headers: _objectSpread({
'X-Web-Version': BUILD_VERSION
}, headerObj)
}).then(checkStatus).then(function (response) {
return response.json();
}).then(checkBizCode)["catch"](function (error) {
throw error;
});
}
export function postForm(url, data) {
var headerObj = getRequestHeader();
return fetch(url, {
method: 'POST',
body: data,
headers: _objectSpread({
'X-Web-Version': BUILD_VERSION
}, headerObj)
}).then(checkStatus).then(function (response) {
return response.json();
}).then(checkBizCode)["catch"](function (error) {
throw error;
});
}
export function postJSON(url, obj) {
var headerObj = getRequestHeader();
return fetch(url, {
method: 'POST',
body: JSON.stringify(obj),
headers: _objectSpread({
'Content-type': 'application/json; charset=UTF-8',
'X-Web-Version': BUILD_VERSION
}, headerObj)
}).then(checkStatus).then(function (response) {
return response.json();
}).then(checkBizCode)["catch"](function (error) {
throw error;
});
}
export function postStream(url, obj) {
var headerObj = getRequestHeader();
return fetch(url, {
method: 'POST',
body: JSON.stringify(obj),
headers: _objectSpread({
'Content-type': 'application/octet-stream',
'X-Web-Version': BUILD_VERSION
}, headerObj)
}).then(checkStatus).then(function (response) {
return response.json();
}).then(checkBizCode)["catch"](function (error) {
throw error;
});
}

2614
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,30 @@
{
"name": "@haina/npm",
"version": "0.1.0",
"main": "build/esm/index.js",
"exports": {
".": {
"import": "./build/esm/index.js",
"require": "./build/cjs/index.js"
},
"./esm/*": "./build/esm/*",
"./cjs/*": "./build/cjs/*"
},
"files": [
"build"
],
"scripts": {
"clean": "rimraf build",
"build:cjs": "babel src --out-dir build/cjs --plugins=@babel/plugin-transform-modules-commonjs",
"build:esm": "babel src --out-dir build/esm",
"build": "npm run clean && npm run build:cjs && npm run build:esm",
"pack": "npm run build && npm pack --pack-destination ./dist",
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"@babel/cli": "^7.28.3",
"@babel/core": "^7.28.5",
"@babel/preset-env": "^7.28.5",
"rimraf": "^6.1.2"
}
}

@ -0,0 +1,3 @@
export * as commons from './utils/commons.js';
export * as request from './utils/request.js';

@ -0,0 +1,679 @@
export function copy(obj) {
return JSON.parse(JSON.stringify(obj))
}
export function splitArray2Parts(arr, size) {
const result = []
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size))
}
return result
}
export function camelCase(name) {
return name.substr(0, 1).toLowerCase() + name.substr(1)
}
export class UrlBuilder {
constructor(url) {
this.url = url
this.paramList = []
}
append(name, value) {
if (isNotEmpty(value)) {
this.paramList.push({ name: name, value: value })
}
return this
}
build() {
this.paramList.forEach((e, i, a) => {
if (i === 0) {
this.url += "?"
} else {
this.url += "&"
}
this.url += e.name + "=" + e.value
})
return this.url
}
}
export function isNotEmpty(val) {
return val !== undefined && val !== null && val !== ""
}
// export function isEmpty(val) {
// return val === undefined || val === null || val === ""
// }
export function prepareUrl(url) {
return new UrlBuilder(url)
}
// export function debounce(fn, delay = 500) {
// let timer
// return e => {
// e.persist()
// clearTimeout(timer)
// timer = setTimeout(() => {
// fn(e)
// }, delay)
// }
// }
export function throttle(fn, delay, atleast) {
let timeout = null,
startTime = new Date()
return function () {
let curTime = new Date()
clearTimeout(timeout)
if (curTime - startTime >= atleast) {
fn()
startTime = curTime
} else {
timeout = setTimeout(fn, delay)
}
}
}
export function clickUrl(url) {
const httpLink = document.createElement("a")
httpLink.href = url
httpLink.target = "_blank"
httpLink.click()
}
export function escape2Html(str) {
var temp = document.createElement("div")
temp.innerHTML = str
var output = temp.innerText || temp.textContent
temp = null
return output
}
/**
* ! 不支持计算 Set Map
* @param {*} val
* @example
* true if: 0, [], {}, null, '', undefined
* false if: 'false', 'undefined'
*/
export function isEmpty(val) {
// return val === undefined || val === null || val === "";
return [Object, Array].includes((val || {}).constructor) && !Object.entries(val || {}).length;
}
/**
* 数组排序
*/
export const sortBy = (key) => {
return (a, b) => (a[key] > b[key] ? 1 : b[key] > a[key] ? -1 : 0);
};
/**
* Object排序keys
*/
export const sortKeys = (obj) =>
Object.keys(obj)
.sort()
.reduce((a, k2) => ({ ...a, [k2]: obj[k2] }), {});
export function sortObjectsByKeysMap(objects, keyOrder) {
if (!objects) return {} // Handle null/undefined input
if (!keyOrder || keyOrder.length === 0) return objects
const objectMap = new Map(Object.entries(objects))
const sortedMap = new Map()
for (const key of keyOrder) {
if (objectMap.has(key)) {
sortedMap.set(key, objectMap.get(key))
objectMap.delete(key) // Optimization: Remove from original map after adding
}
}
// Add remaining keys
for (const [key, value] of objectMap) {
sortedMap.set(key, value)
}
return Object.fromEntries(sortedMap)
}
/**
* 数组排序, 给定排序数组
* @param {array} items 需要排序的数组
* @param {array} keyName 排序的key
* @param {array} keyOrder 给定排序
* @returns
*/
export const sortArrayByOrder = (items, keyName, keyOrder) => {
return items.sort((a, b) => {
return keyOrder.indexOf(a[keyName]) - keyOrder.indexOf(b[keyName]);
});
};
/**
* 合并Object, 递归地
*/
export function merge(...objects) {
const isDeep = objects.some((obj) => obj !== null && typeof obj === 'object');
const result = objects[0] || (isDeep ? {} : objects[0]);
for (let i = 1; i < objects.length; i++) {
const obj = objects[i];
if (!obj) continue;
Object.keys(obj).forEach((key) => {
const val = obj[key];
if (isDeep) {
if (Array.isArray(val)) {
result[key] = [].concat(Array.isArray(result[key]) ? result[key] : [result[key]], val);
} else if (typeof val === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
} else {
result[key] = typeof val === 'boolean' ? val : result[key];
}
});
}
return result;
}
/**
* 数组分组
* - 相当于 lodash _.groupBy
* @see https://www.lodashjs.com/docs/lodash.groupBy#_groupbycollection-iteratee_identity
* ECMAScript 2021 原生
* - Object.groupBy(items, callbackFn)
*/
export function groupBy(array = [], callback) {
return array.reduce((groups, item) => {
const key = typeof callback === 'function' ? callback(item) : item[callback];
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(item);
return groups;
}, {});
}
/**
* 创建一个从 object 中选中的属性的对象
* @param {*} object
* @param {array} keys
*/
export function pick(object, keys) {
return keys.reduce((obj, key) => {
if (object && Object.prototype.hasOwnProperty.call(object, key)) {
obj[key] = object[key];
}
return obj;
}, {});
}
/**
* 返回对象的副本经过筛选以省略指定的键
* @param {*} object
* @param {string[]} keysToOmit
* @returns
*/
export function omit(object, keysToOmit) {
return Object.fromEntries(Object.entries(object).filter(([key]) => !keysToOmit.includes(key)));
}
/**
* 去除无效的值: undefined, null, '', []
* * 只删除 null undefined: flush 方法;
*/
export const omitEmpty = _object => {
Object.keys(_object).forEach(key => (_object[key] == null || _object[key] === '' || _object[key].length === 0) && delete _object[key]);
return _object;
};
/**
* 深拷贝
*/
export function cloneDeep(value) {
// return structuredClone(value);
if (typeof value !== 'object' || value === null) {
return value;
}
const result = Array.isArray(value) ? [] : {};
for (const key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
result[key] = cloneDeep(value[key]);
}
}
return result;
}
/**
* 向零四舍五入, 固定精度设置
*/
function curriedFix(precision = 0) {
return function (number) {
// Shift number by precision places
const shift = Math.pow(10, precision);
const shiftedNumber = number * shift;
// Round to nearest integer
const roundedNumber = Math.round(shiftedNumber);
// Shift back decimal place
return roundedNumber / shift;
};
}
/**
* 向零四舍五入, 保留2位小数
*/
export const fixTo2Decimals = curriedFix(2);
/**
* 向零四舍五入, 保留4位小数
*/
export const fixTo4Decimals = curriedFix(4);
export const fixTo1Decimals = curriedFix(1);
export const fixToInt = curriedFix(0);
/**
* 映射
* @example
* const keyMap = {
a: [{key: 'a1'}, {key: 'a2', transform: v => v * 2}],
b: {key: 'b1'}
};
const result = objectMapper({a: 1, b: 3}, keyMap);
// result = {a1: 1, a2: 2, b1: 3}
*
*/
export function objectMapper(input, keyMap) {
// Loop through array mapping
if (Array.isArray(input)) {
return input.map((obj) => objectMapper(obj, keyMap));
}
if (typeof input === 'object') {
const mappedObj = {};
Object.keys(input).forEach((key) => {
// Keep original keys not in keyMap
if (!keyMap[key]) {
mappedObj[key] = input[key];
}
// Handle array of maps
if (Array.isArray(keyMap[key])) {
keyMap[key].forEach((map) => {
let value = input[key];
if (map.transform) value = map.transform(value);
mappedObj[map.key] = value;
});
// Handle single map
} else {
const map = keyMap[key];
if (map) {
let value = input[key];
if (map.transform) value = map.transform(value);
mappedObj[map.key || key] = value;
}
}
});
return mappedObj;
}
return input;
}
/**
* 创建一个对应于对象路径的值数组
*/
export function at(obj, path) {
let result;
if (Array.isArray(obj)) {
// array case
const indexes = path.split('.').map((i) => parseInt(i));
result = [];
for (let i = 0; i < indexes.length; i++) {
result.push(obj[indexes[i]]);
}
} else {
// object case
const indexes = path.split('.').map((i) => i);
result = [obj];
for (let i = 0; i < indexes.length; i++) {
result = [result[0][indexes[i]]];
}
}
return result;
}
/**
* 删除 null/undefined
*/
export function flush(collection) {
let result, len, i;
if (!collection) {
return undefined;
}
if (Array.isArray(collection)) {
result = [];
len = collection.length;
for (i = 0; i < len; i++) {
const elem = collection[i];
if (elem != null) {
result.push(elem);
}
}
return result;
}
if (typeof collection === 'object') {
result = {};
const keys = Object.keys(collection);
len = keys.length;
for (i = 0; i < len; i++) {
const key = keys[i];
const value = collection[key];
if (value != null) {
result[key] = value;
}
}
return result;
}
return undefined;
}
/**
* 千分位 格式化数字
*/
export const numberFormatter = (number) => {
return new Intl.NumberFormat().format(number);
};
/**
* @example
* const obj = { a: { b: 'c' } };
* const keyArr = ['a', 'b'];
* getNestedValue(obj, keyArr); // Returns: 'c'
*/
export const getNestedValue = (obj, keyArr) => {
return keyArr.reduce((acc, curr) => {
return acc && Object.prototype.hasOwnProperty.call(acc, curr) ? acc[curr] : undefined;
// return acc && acc[curr];
}, obj);
};
/**
* 计算笛卡尔积
*/
export const cartesianProductArray = (arr, sep = '_', index = 0, prefix = '') => {
let result = [];
if (index === arr.length) {
return [prefix];
}
arr[index].forEach((item) => {
result = result.concat(cartesianProductArray(arr, sep, index + 1, prefix ? `${prefix}${sep}${item}` : `${item}`));
});
return result;
};
export const stringToColour = (str='', withFlag = true) => {
var hash = 0
if (str.length === 0) return hash;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash)
}
var colour = withFlag ? '#' : ''
for (let i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xff
value = (value % 150) + 50
colour += ('00' + value.toString(16)).substr(-2)
}
return colour
}
export const debounce = (func, wait, immediate) => {
var timeout;
return function () {
var context = this,
args = arguments;
clearTimeout(timeout);
if (immediate && !timeout) func.apply(context, args);
timeout = setTimeout(function () {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
};
}
export const removeFormattingChars = (str) => {
const regex = /[\r\n\t\v\f]/g;
str = str.replace(regex, ' ');
// Replace more than four consecutive spaces with a single space
str = str.replace(/\s{4,}/g, ' ');
return str;
}
export const olog = (text, ...args) => {
console.log(
`%c ${text} `,
'background:#fb923c ; padding: 1px; border-radius: 3px; color: #fff',...args
);
};
export const sanitizeFilename = (str) => {
// Remove whitespace and replace with hyphens
str = str.replace(/\s+/g, '-');
// Remove invalid characters and replace with hyphens
str = str.replace(/[^a-zA-Z0-9.-]/g, '-');
// Replace consecutive hyphens with a single hyphen
str = str.replace(/-+/g, '-');
// Trim leading and trailing hyphens
str = str.replace(/^-+|-+$/g, '');
return str;
}
export const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return '';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
export const calcCacheSizes = async () => {
try {
let swCacheSize = 0;
let diskCacheSize = 0;
let indexedDBSize = 0;
// 1. Get the service worker cache size
if ('caches' in window) {
const cacheNames = await caches.keys();
for (const name of cacheNames) {
const cache = await caches.open(name);
const requests = await cache.keys();
for (const request of requests) {
const response = await cache.match(request);
swCacheSize += Number(response.headers.get('Content-Length')) || 0;
}
}
}
// 2. Get the disk cache size
// const diskCacheName = 'disk-cache';
// const diskCache = await caches.open(diskCacheName);
// const diskCacheKeys = await diskCache.keys();
// for (const request of diskCacheKeys) {
// const response = await diskCache.match(request);
// diskCacheSize += Number(response.headers.get('Content-Length')) || 0;
// }
// 3. Get the IndexedDB cache size
// const indexedDBNames = await window.indexedDB.databases();
// for (const dbName of indexedDBNames) {
// const db = await window.indexedDB.open(dbName.name);
// const objectStoreNames = db.objectStoreNames;
// if (objectStoreNames !== undefined) {
// const objectStores = Array.from(objectStoreNames).map((storeName) => db.transaction([storeName], 'readonly').objectStore(storeName));
// for (const objectStore of objectStores) {
// const request = objectStore.count();
// request.onsuccess = () => {
// indexedDBSize += request.result;
// };
// }
// }
// }
return { swCacheSize, diskCacheSize, indexedDBSize, totalSize: Number(swCacheSize) + Number(diskCacheSize) + indexedDBSize };
} catch (error) {
console.error('Error getting cache sizes:', error);
}
};
export const clearAllCaches = async (cb) => {
try {
// 1. Clear the service worker cache
if ('caches' in window) {
// if (navigator.serviceWorker) {
const cacheNames = await caches.keys();
await Promise.all(cacheNames.map((name) => caches.delete(name)));
}
// 2. Clear the disk cache (HTTP cache)
// const diskCacheName = 'disk-cache';
// await window.caches.delete(diskCacheName);
// const diskCache = await window.caches.open(diskCacheName);
// const diskCacheKeys = await diskCache.keys();
// await Promise.all(diskCacheKeys.map((request) => diskCache.delete(request)));
// 3. Clear the IndexedDB cache
const indexedDBNames = await window.indexedDB.databases();
await Promise.all(indexedDBNames.map((dbName) => window.indexedDB.deleteDatabase(dbName.name)));
// Unregister the service worker
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
await registration.unregister();
console.log('Service worker unregistered');
} else {
console.log('No service worker registered');
}
if (typeof cb === 'function' ) {
cb();
}
} catch (error) {
console.error('Error clearing caches or unregistering service worker:', error);
}
};
export const loadScript = (src) => {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.type = 'text/javascript';
script.onload = resolve;
script.onerror = reject;
script.crossOrigin = 'anonymous';
script.src = src;
if (document.head.append) {
document.head.append(script);
} else {
document.getElementsByTagName('head')[0].appendChild(script);
}
});
};
export const TagColorStyle = (tag, outerStyle = false) => {
const color = stringToColour(tag);
const outerStyleObj = outerStyle ? { borderColor: `${color}66`, backgroundColor: `${color}0D` } : {};
return { color: `${color}`, ...outerStyleObj };
};
// 数组去掉重复
export function unique(arr) {
const x = new Set(arr);
return [...x];
}
export const uniqWith = (arr, fn) => arr.filter((element, index) => arr.findIndex((step) => fn(element, step)) === index);
/**
* Creates a new tree node object.
* @param {string} key - The unique identifier for the node.
* @param {string} name - The display name of the node.
* @param {string|null} parent - The key of the parent node, or null if it's a root.
* @returns {object} A plain JavaScript object representing the tree node.
*/
function createTreeNode(key, name, parent = null, keyMap={}, _raw={}) {
return {
key: key,
title: name,
parent: parent,
icon: _raw?.icon,
iconIndex: _raw?.[keyMap.iconIndex],
_raw: _raw,
children: [],
parentTitle: '',
parentIconIndex: '',
};
}
/**
* Builds a tree structure from a flat list of nodes.
* @returns {Array<object>} An array of root tree nodes.
*/
export const buildTree = (list, keyMap={ rootKeys: [], ignoreKeys: [] }) => {
if (!list || list.length === 0) {
return []
}
const nodeMap = new Map()
const treeRoots = []
list.forEach((item) => {
const node = createTreeNode(item[keyMap.key], item[keyMap.name], item[keyMap.parent], keyMap, item)
nodeMap.set(item[keyMap.key], node)
})
list.forEach((item) => {
const node = nodeMap.get(item[keyMap.key])
if (keyMap.rootKeys.includes(item[keyMap.parent]) || item[keyMap.parent] === null || item[keyMap.parent] === undefined) {
// This is a root node
treeRoots.push(node)
} else {
const parentNode = nodeMap.get(item[keyMap.parent])
if (keyMap.ignoreKeys.includes(item[keyMap.parent])) {
const grandParentNode = nodeMap.get(parentNode.parent);
node.rawParent = node.parent;
node.parent = parentNode.parent;
node.parentTitle = parentNode.title;
node.parentIconIndex = parentNode.iconIndex;
grandParentNode.children.push(node)
} else if (keyMap.ignoreKeys.includes(item[keyMap.key])) {
//
}
else if (parentNode) {
node.parentTitle = parentNode.title;
node.parentIconIndex = parentNode.iconIndex;
parentNode.children.push(node)
} else {
console.warn(`Parent with key '${item[keyMap.parent]}' not found for node '${item[keyMap.key]}'. This node will be treated as a root.`)
treeRoots.push(node)
}
}
})
return treeRoots
}

@ -0,0 +1,129 @@
// import { BUILD_VERSION } from '@/config'
const BUILD_VERSION = ''
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const customHeaders = []
// 添加 HTTP Reuqest 自定义头部
export function appendRequestHeader(n, v) {
customHeaders.push({
name: n,
value: v
})
}
function getRequestHeader() {
return customHeaders.reduce((acc, item) => {
acc[item.name] = item.value;
return acc;
}, {});
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
const message =
'Fetch error: ' + response.url + ' ' + response.status + ' (' +
response.statusText + ')'
const error = new Error(message)
error.response = response
throw error
}
}
function checkBizCode(responseJson) {
if (responseJson.errcode === 0) {
return responseJson;
} else {
throw new Error(responseJson.errmsg + ': ' + responseJson.errcode);
}
}
export function fetchText(url) {
const headerObj = getRequestHeader()
return fetch(url, {
method: 'GET',
headers: {
'X-Web-Version': BUILD_VERSION,
...headerObj
}
}).then(checkStatus)
.then(response => response.text())
.catch(error => {
throw error
})
}
export function fetchJSON(url, data) {
const params = data ? new URLSearchParams(data).toString() : '';
const ifp = url.includes('?') ? (data ? '&' : '') : '?';
const headerObj = getRequestHeader()
return fetch(`${url}${ifp}${params}`, {
method: 'GET',
headers: {
'X-Web-Version': BUILD_VERSION,
...headerObj
}
}).then(checkStatus)
.then(response => response.json())
.then(checkBizCode)
.catch(error => {
throw error;
});
}
export function postForm(url, data) {
const headerObj = getRequestHeader()
return fetch(url, {
method: 'POST',
body: data,
headers: {
'X-Web-Version': BUILD_VERSION,
...headerObj
}
}).then(checkStatus)
.then(response => response.json())
.then(checkBizCode)
.catch(error => {
throw error
})
}
export function postJSON(url, obj) {
const headerObj = getRequestHeader()
return fetch(url, {
method: 'POST',
body: JSON.stringify(obj),
headers: {
'Content-type': 'application/json; charset=UTF-8',
'X-Web-Version': BUILD_VERSION,
...headerObj
}
}).then(checkStatus)
.then(response => response.json())
.then(checkBizCode)
.catch(error => {
throw error
})
}
export function postStream(url, obj) {
const headerObj = getRequestHeader()
return fetch(url, {
method: 'POST',
body: JSON.stringify(obj),
headers: {
'Content-type': 'application/octet-stream',
'X-Web-Version': BUILD_VERSION,
...headerObj
}
}).then(checkStatus)
.then(response => response.json())
.then(checkBizCode)
.catch(error => {
throw error
})
}
Loading…
Cancel
Save