@jhqn/utils-core 0.0.1-beta.8 → 0.0.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,24 @@
1
1
  'use strict';
2
2
 
3
+ const detectBrowser = require('detect-browser');
4
+ const dayjs = require('dayjs');
5
+ const localeData = require('dayjs/plugin/localeData');
6
+ const duration = require('dayjs/plugin/duration');
7
+ const relativeTime = require('dayjs/plugin/relativeTime');
8
+ const customParseFormat = require('dayjs/plugin/customParseFormat');
9
+ const objectSupport = require('dayjs/plugin/objectSupport');
10
+ const zhCN = require('dayjs/locale/zh-cn');
11
+
12
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
13
+
14
+ const dayjs__default = /*#__PURE__*/_interopDefaultCompat(dayjs);
15
+ const localeData__default = /*#__PURE__*/_interopDefaultCompat(localeData);
16
+ const duration__default = /*#__PURE__*/_interopDefaultCompat(duration);
17
+ const relativeTime__default = /*#__PURE__*/_interopDefaultCompat(relativeTime);
18
+ const customParseFormat__default = /*#__PURE__*/_interopDefaultCompat(customParseFormat);
19
+ const objectSupport__default = /*#__PURE__*/_interopDefaultCompat(objectSupport);
20
+ const zhCN__default = /*#__PURE__*/_interopDefaultCompat(zhCN);
21
+
3
22
  const snake2Kebab = (str) => str.replace(/_([a-z])/g, (_, letter) => `-${letter.toLowerCase()}`);
4
23
  const snake2Pascal = (str) => str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/^[a-z]/, (letter) => letter.toUpperCase());
5
24
  const snake2Camel = (str) => str.replace(/(_([a-z]))/g, (match) => match[1].toUpperCase());
@@ -52,25 +71,61 @@ const jClear = console.clear.bind(console);
52
71
 
53
72
  const cnPhoneRE = /^1[3-9]\d{9}$/;
54
73
  const cnTelRE = /^0\d{9,11}$/;
55
- const isDef = (val) => val !== void 0 && val !== null;
56
- const isNumeric = (val) => typeof val === "number" || /^\d+(?:\.\d+)?$/.test(val);
74
+ const getVariableType = (val) => {
75
+ const value = Object.prototype.toString.call(val);
76
+ const result = value.match(/\[object (\S*)\]/)?.[1];
77
+ return result?.toLocaleLowerCase();
78
+ };
79
+ const isNumber = (val) => getVariableType(val) === "number";
80
+ const isString = (val) => getVariableType(val) === "string";
81
+ const isBoolean = (val) => getVariableType(val) === "boolean";
82
+ const isNull = (val) => getVariableType(val) === "null";
83
+ const isUndefined = (val) => getVariableType(val) === "undefined";
84
+ const isSymbol = (val) => getVariableType(val) === "symbol";
85
+ const isObject = (val) => getVariableType(val) === "object";
86
+ const isArray = (val) => getVariableType(val) === "array";
87
+ const isFunction = (val) => getVariableType(val) === "function";
88
+ const isDate = (val) => getVariableType(val) === "date";
89
+ const isRegExp = (val) => getVariableType(val) === "regexp";
90
+ const isPromise = (val) => getVariableType(val) === "promise";
91
+ const isSet = (val) => getVariableType(val) === "set";
92
+ const isMap = (val) => getVariableType(val) === "map";
93
+ const isWeakSet = (val) => getVariableType(val) === "weakset";
94
+ const isWeakMap = (val) => getVariableType(val) === "weakmap";
95
+ const isFile = (val) => getVariableType(val) === "file";
96
+ const isBlob = (val) => getVariableType(val) === "blob";
97
+ const isURL = (val) => getVariableType(val) === "url";
98
+ const isError = (val) => getVariableType(val) === "error";
99
+ const isDef = (val) => !isNull(val) && !isUndefined(val);
100
+ const isNumeric = (val) => {
101
+ if (isDef(val))
102
+ return typeof val === "number" || /^\d+(?:\.\d+)?$/.test(val);
103
+ return false;
104
+ };
57
105
  const checkImg = (ext) => {
58
106
  return /\.(?:jpg|jpeg|png|gif)$/.test((ext || "").toLowerCase());
59
107
  };
108
+ const isEmpty = (val) => {
109
+ return !isDef(val) || val === "" || Array.isArray(val) && val.length === 0 || Object.prototype.toString.call(val) === "[object Object]" && Object.keys(val).length === 0 || val instanceof Map && val.size === 0 || val instanceof Set && val.size === 0;
110
+ };
60
111
  const isJSONStr = (str) => {
61
- try {
62
- JSON.parse(str);
63
- return true;
64
- } catch (e) {
65
- return false;
66
- }
112
+ if (isDef(str))
113
+ try {
114
+ JSON.parse(str);
115
+ return true;
116
+ } catch (e) {
117
+ return false;
118
+ }
119
+ return false;
67
120
  };
68
121
  const isArrStr = (str) => {
69
- try {
70
- return Array.isArray(JSON.parse(str));
71
- } catch (e) {
72
- return false;
73
- }
122
+ if (isDef(str))
123
+ try {
124
+ return Array.isArray(JSON.parse(str));
125
+ } catch (e) {
126
+ return false;
127
+ }
128
+ return false;
74
129
  };
75
130
  const isValidKey = (key, object) => key in object;
76
131
  const isPhone = (val) => {
@@ -83,39 +138,48 @@ const isTel = (val) => {
83
138
  return false;
84
139
  return cnTelRE.test(val.toString());
85
140
  };
86
-
87
- const hidePhone = (str) => {
88
- if (str) {
89
- if (isPhone(str)) {
90
- return str.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
91
- }
92
- if (isTel(str)) {
93
- return str.replace(/^(\d{3,4})-?\d{3,4}(\d{4})$/, "$1****$2");
94
- }
95
- return str;
96
- }
97
- return "";
141
+ const isEmail = (val) => {
142
+ if (!isDef(val))
143
+ return false;
144
+ const reg = /^[a-zA-Z\d](?:\w|-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,5}$/;
145
+ return reg.test(val);
98
146
  };
99
- const hideCardNo = (cardNo) => {
100
- if (cardNo) {
101
- return cardNo.replace(/^(.{4})\d+(.{2})$/, "$1*******$2");
102
- }
103
- return "";
147
+ const isIdCard = (val, compatible = true) => {
148
+ if (!isDef(val))
149
+ return false;
150
+ const card15 = /^[1-9]\d{7}(?:0[1-9]|10|11|12)(?:[0-2][1-9]|10|20|30|31)\d{2}[\dXx]$/;
151
+ const card18 = /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:[0-2][1-9]|10|20|30|31)\d{3}[\dXx]$/;
152
+ return card18.test(val) || (compatible ? card15.test(val) : false);
104
153
  };
105
- const hideName = (name) => {
106
- if (name) {
107
- let res = "";
108
- for (let i = 0; i < name.length; i += 1) {
109
- if (i === 0) {
110
- res += "*";
111
- } else {
112
- res += name[i];
113
- }
154
+ const nonASCII = (text) => /[^\x20-\x7E]/.test(text);
155
+ const isValidResCode = (res, code = 200) => res.code === code;
156
+ const isValidRes = (res, code) => isValidResCode(res, code) && isDef(res.data);
157
+ const isValidArrRes = (res, code) => isValidResCode(res, code) && Array.isArray(res.data);
158
+ const isValidPageRes = (res, code) => isValidResCode(res, code) && isDef(res.data) && Array.isArray(res.data.list || res.data.records);
159
+ const isValidFileType = (file, type) => {
160
+ if (type === "*")
161
+ return true;
162
+ const fileType = file.type;
163
+ const fileName = file.name;
164
+ function validate(item) {
165
+ if (item.startsWith(".")) {
166
+ return fileName.endsWith(item);
114
167
  }
115
- return res;
168
+ if (item.endsWith("/*")) {
169
+ return fileType.startsWith(item.replace("/*", ""));
170
+ }
171
+ if (item.includes("/")) {
172
+ return fileType === item;
173
+ }
174
+ return false;
116
175
  }
117
- return "";
176
+ const typeArrStr = type.split(",").map((item) => item.trim());
177
+ if (typeArrStr.length > 1) {
178
+ return typeArrStr.some(validate);
179
+ }
180
+ return validate(type);
118
181
  };
182
+
119
183
  const hideMiddle = (str) => {
120
184
  if (!isDef(str))
121
185
  return "";
@@ -137,6 +201,149 @@ const hideThird = (str) => {
137
201
  return "**";
138
202
  return str.slice(0, partLen) + "*".repeat(len - 2 * partLen) + str.slice(len - partLen);
139
203
  };
204
+ const hideHead = (str, count) => {
205
+ if (!isDef(str))
206
+ return "";
207
+ const len = str.length;
208
+ const cnt = count !== void 0 ? Math.max(Math.min(len, count), 0) : len - 1;
209
+ if (len === 1)
210
+ return "*";
211
+ return "*".repeat(cnt) + str.substring(cnt);
212
+ };
213
+ const hideTail = (str, count) => {
214
+ if (!isDef(str))
215
+ return "";
216
+ const len = str.length;
217
+ const cnt = count !== void 0 ? Math.max(Math.min(len, count), 0) : len - 1;
218
+ if (len === 1)
219
+ return "*";
220
+ return str.substring(0, len - cnt) + "*".repeat(cnt);
221
+ };
222
+ const hidePhone = (phone) => {
223
+ if (phone) {
224
+ if (isPhone(phone)) {
225
+ return phone.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
226
+ }
227
+ if (isTel(phone)) {
228
+ return phone.replace(/^(\d{3,4})-?\d{3,4}(\d{4})$/, "$1****$2");
229
+ }
230
+ return phone;
231
+ }
232
+ return "";
233
+ };
234
+ const hideCardNo = (cardNo, strong = true) => {
235
+ if (cardNo) {
236
+ if (isIdCard(cardNo, false)) {
237
+ return strong ? hideMiddle(cardNo) : cardNo.replace(/^(.)\d{3}(.{8})\d{5}(.)$/, "$1***$2*****$3");
238
+ }
239
+ return cardNo;
240
+ }
241
+ return "";
242
+ };
243
+ const hideName = (name) => {
244
+ if (name) {
245
+ let res = "";
246
+ for (let i = 0; i < name.length; i += 1) {
247
+ if (i === 0) {
248
+ res += "*";
249
+ } else {
250
+ res += name[i];
251
+ }
252
+ }
253
+ return res;
254
+ }
255
+ return "";
256
+ };
257
+ const hideSurname = (name) => {
258
+ return hideHead(name, 1);
259
+ };
260
+ const hideFirstName = (name) => {
261
+ return hideTail(name);
262
+ };
263
+ const hideEmail = (email) => {
264
+ if (email) {
265
+ if (!email.includes("@"))
266
+ return email;
267
+ const arr = email.split("@");
268
+ const name = arr[0];
269
+ const domain = arr[1];
270
+ if (!name || !domain)
271
+ return email;
272
+ const len = name.length;
273
+ let newName;
274
+ if (len <= 3) {
275
+ newName = `${name}***`;
276
+ } else {
277
+ newName = hideTail(name, 3);
278
+ }
279
+ return `${newName}@${domain}`;
280
+ }
281
+ return "";
282
+ };
283
+ const hideBankCard = (bankCard) => {
284
+ if (bankCard) {
285
+ const len = bankCard.length;
286
+ if (len <= 10)
287
+ return bankCard;
288
+ return bankCard.substring(0, 6) + "*".repeat(len - 10) + bankCard.substring(len - 4, len);
289
+ }
290
+ return "";
291
+ };
292
+
293
+ const inBrowser = typeof window !== "undefined";
294
+ const waitTime = (time = 100) => {
295
+ return new Promise((resolve) => {
296
+ setTimeout(() => {
297
+ resolve(true);
298
+ }, time);
299
+ });
300
+ };
301
+ const fixiOSInputAutoZoomIn = () => {
302
+ if (CSS.supports("(font:-apple-system-body) and (-webkit-touch-callout:none) and (-webkit-tap-highlight-color:hotpink)")) {
303
+ const viewport = document.querySelector('meta[name="viewport"]');
304
+ if (viewport !== null) {
305
+ viewport.content = `${viewport.content}, user-scalable=no`;
306
+ }
307
+ }
308
+ };
309
+ const userAgent = inBrowser ? window.navigator.userAgent : "";
310
+ const getHostEnv = () => {
311
+ const ua = userAgent.toLowerCase();
312
+ const baseInfo = detectBrowser.detect();
313
+ const zlb = ua.includes("@zlb");
314
+ const zyd = ua.includes("saas");
315
+ const zzd = ua.includes("zhejiang") || ua.includes("tauruszjd");
316
+ const wx = ua.includes("micromessenger");
317
+ const zfb = ua.includes("alipay");
318
+ const mini = ua.includes("miniprogram");
319
+ return {
320
+ ...baseInfo,
321
+ /**
322
+ * 是否是浙里办
323
+ */
324
+ zlb,
325
+ /**
326
+ * 是否是专有钉
327
+ */
328
+ zyd,
329
+ /**
330
+ * 是否是浙政钉
331
+ */
332
+ zzd,
333
+ /**
334
+ * 是否是微信
335
+ */
336
+ wx,
337
+ /**
338
+ * 是否是支付宝
339
+ */
340
+ zfb,
341
+ /**
342
+ * 是否是小程序
343
+ */
344
+ mini
345
+ };
346
+ };
140
347
 
141
348
  const parseToJSON = (str, reviver2) => isJSONStr(str) ? JSON.parse(str, reviver2) : null;
142
349
  const replacer = (_, value) => {
@@ -158,24 +365,175 @@ const reviver = (_, value) => {
158
365
  };
159
366
  const filterObj = (obj, keys, reverse = false) => Object.fromEntries(Object.entries(obj).filter(([key]) => reverse ? !keys.includes(key) : keys.includes(key)));
160
367
 
368
+ dayjs__default.extend(localeData__default).locale("zh-cn", zhCN__default);
369
+ dayjs__default.extend(duration__default);
370
+ dayjs__default.extend(relativeTime__default);
371
+ dayjs__default.extend(customParseFormat__default);
372
+ dayjs__default.extend(objectSupport__default);
373
+ const dateFmt = (date, format = "YYYY-MM-DD HH:mm:ss") => {
374
+ const dd = dayjs__default(date);
375
+ let fmt = format;
376
+ if (!isDef(date) || !dd.isValid())
377
+ return "";
378
+ if (format === "date")
379
+ fmt = "YYYY-MM-DD";
380
+ if (format === "datetime")
381
+ fmt = "YYYY-MM-DD HH:mm:ss";
382
+ return dd.format(fmt);
383
+ };
384
+ const dateDuration = (start, end) => {
385
+ const startDay = dayjs__default(start);
386
+ const endDay = dayjs__default(end);
387
+ if (!isDef(start) || !startDay.isValid() || !isDef(end) || !endDay.isValid())
388
+ return "";
389
+ const dd = dayjs__default.duration(endDay.diff(startDay));
390
+ const year = dd.years();
391
+ const month = dd.months();
392
+ const day = dd.days();
393
+ const format = [
394
+ year === 0 ? "" : "Y\u5E74",
395
+ month === 0 ? "" : "M\u4E2A\u6708",
396
+ day === 0 ? "" : `${day < 10 && (year !== 0 || month !== 0) ? "\u96F6" : ""}D\u5929`
397
+ ].join("");
398
+ return dd.format(format);
399
+ };
400
+
401
+ let BASE_ATTACH_URL;
402
+ function setBaseAttachUrl(baseUrl) {
403
+ BASE_ATTACH_URL = baseUrl;
404
+ }
405
+ function getBaseAttachUrl() {
406
+ return BASE_ATTACH_URL;
407
+ }
408
+ if (undefined?.VITE_BASE_ATTACH_URL) {
409
+ setBaseAttachUrl(undefined.VITE_BASE_ATTACH_URL);
410
+ }
411
+
412
+ const toThousands = (num) => {
413
+ const arr = num.toString().split(".");
414
+ const integer = arr[0]?.replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
415
+ if (arr.length > 1)
416
+ return `${integer}.${arr[1]}`;
417
+ return integer;
418
+ };
419
+ const currencyFmt = (currency, maximumFractionDigits = 2) => {
420
+ if (!isDef(currency))
421
+ return "";
422
+ const num = Number(currency);
423
+ if (Number.isNaN(num))
424
+ return "";
425
+ return new Intl.NumberFormat("zh-CN", { style: "currency", currency: "CNY", maximumFractionDigits }).format(num);
426
+ };
427
+
428
+ const resUrl = (url) => {
429
+ if (!isDef(url))
430
+ return void 0;
431
+ if (/^https?:\/\//.test(url) || /^blob:/.test(url) || /^data:/.test(url)) {
432
+ return url;
433
+ }
434
+ const baseUrl = getBaseAttachUrl();
435
+ if (!isDef(baseUrl)) {
436
+ throw new Error("\u8BF7\u5148\u8BBE\u7F6E import.meta\u200B.env.VITE_BASE_ATTACH_URL");
437
+ }
438
+ return `${baseUrl}/${url}`.replace(/([^:]\/)\/+/g, "$1");
439
+ };
440
+ const recoverFile = (resource) => {
441
+ const { uri, url, ...item } = resource;
442
+ const validUrl = uri || url;
443
+ return {
444
+ ...item,
445
+ url: resUrl(validUrl),
446
+ content: resUrl(validUrl),
447
+ uri: validUrl || "",
448
+ status: "done",
449
+ percent: 100
450
+ };
451
+ };
452
+ const attachFmt = (data) => {
453
+ let attachList = [];
454
+ const prototype = Object.prototype.toString.call(data);
455
+ if (!data)
456
+ attachList = [];
457
+ else if (Array.isArray(data))
458
+ attachList = data.filter(Boolean);
459
+ else if (typeof data === "string") {
460
+ if (isArrStr(data)) {
461
+ attachList = (parseToJSON(data) || []).filter(Boolean);
462
+ } else {
463
+ const jsonData = parseToJSON(data);
464
+ const prototypeJson = Object.prototype.toString.call(jsonData);
465
+ if (prototypeJson === "[object Object]")
466
+ attachList = [jsonData].filter(Boolean);
467
+ else
468
+ attachList = [{ id: data, name: "name", uri: data, group: "default" }];
469
+ }
470
+ } else if (prototype === "[object Object]")
471
+ attachList = [data];
472
+ return attachList.map(recoverFile);
473
+ };
474
+
475
+ exports.dayjs = dayjs__default;
476
+ exports.attachFmt = attachFmt;
161
477
  exports.camel2Kebab = camel2Kebab;
162
478
  exports.camel2Pascal = camel2Pascal;
163
479
  exports.camel2Snake = camel2Snake;
164
480
  exports.camel2Title = camel2Title;
165
481
  exports.checkImg = checkImg;
482
+ exports.currencyFmt = currencyFmt;
483
+ exports.dateDuration = dateDuration;
484
+ exports.dateFmt = dateFmt;
166
485
  exports.filterObj = filterObj;
486
+ exports.fixiOSInputAutoZoomIn = fixiOSInputAutoZoomIn;
487
+ exports.getBaseAttachUrl = getBaseAttachUrl;
488
+ exports.getHostEnv = getHostEnv;
489
+ exports.getVariableType = getVariableType;
490
+ exports.hideBankCard = hideBankCard;
167
491
  exports.hideCardNo = hideCardNo;
492
+ exports.hideEmail = hideEmail;
493
+ exports.hideFirstName = hideFirstName;
494
+ exports.hideHead = hideHead;
168
495
  exports.hideMiddle = hideMiddle;
169
496
  exports.hideName = hideName;
170
497
  exports.hidePhone = hidePhone;
498
+ exports.hideSurname = hideSurname;
499
+ exports.hideTail = hideTail;
171
500
  exports.hideThird = hideThird;
501
+ exports.inBrowser = inBrowser;
172
502
  exports.isArrStr = isArrStr;
503
+ exports.isArray = isArray;
504
+ exports.isBlob = isBlob;
505
+ exports.isBoolean = isBoolean;
506
+ exports.isDate = isDate;
173
507
  exports.isDef = isDef;
508
+ exports.isEmail = isEmail;
509
+ exports.isEmpty = isEmpty;
510
+ exports.isError = isError;
511
+ exports.isFile = isFile;
512
+ exports.isFunction = isFunction;
513
+ exports.isIdCard = isIdCard;
174
514
  exports.isJSONStr = isJSONStr;
515
+ exports.isMap = isMap;
516
+ exports.isNull = isNull;
517
+ exports.isNumber = isNumber;
175
518
  exports.isNumeric = isNumeric;
519
+ exports.isObject = isObject;
176
520
  exports.isPhone = isPhone;
521
+ exports.isPromise = isPromise;
522
+ exports.isRegExp = isRegExp;
523
+ exports.isSet = isSet;
524
+ exports.isString = isString;
525
+ exports.isSymbol = isSymbol;
177
526
  exports.isTel = isTel;
527
+ exports.isURL = isURL;
528
+ exports.isUndefined = isUndefined;
529
+ exports.isValidArrRes = isValidArrRes;
530
+ exports.isValidFileType = isValidFileType;
178
531
  exports.isValidKey = isValidKey;
532
+ exports.isValidPageRes = isValidPageRes;
533
+ exports.isValidRes = isValidRes;
534
+ exports.isValidResCode = isValidResCode;
535
+ exports.isWeakMap = isWeakMap;
536
+ exports.isWeakSet = isWeakSet;
179
537
  exports.jClear = jClear;
180
538
  exports.jDebug = jDebug;
181
539
  exports.jError = jError;
@@ -191,13 +549,17 @@ exports.kebab2Camel = kebab2Camel;
191
549
  exports.kebab2Pascal = kebab2Pascal;
192
550
  exports.kebab2Snake = kebab2Snake;
193
551
  exports.kebab2Title = kebab2Title;
552
+ exports.nonASCII = nonASCII;
194
553
  exports.parseToJSON = parseToJSON;
195
554
  exports.pascal2Camel = pascal2Camel;
196
555
  exports.pascal2Kebab = pascal2Kebab;
197
556
  exports.pascal2Snake = pascal2Snake;
198
557
  exports.pascal2Title = pascal2Title;
558
+ exports.recoverFile = recoverFile;
199
559
  exports.replacer = replacer;
560
+ exports.resUrl = resUrl;
200
561
  exports.reviver = reviver;
562
+ exports.setBaseAttachUrl = setBaseAttachUrl;
201
563
  exports.snake2Camel = snake2Camel;
202
564
  exports.snake2Kebab = snake2Kebab;
203
565
  exports.snake2Pascal = snake2Pascal;
@@ -206,3 +568,6 @@ exports.title2Camel = title2Camel;
206
568
  exports.title2Kebab = title2Kebab;
207
569
  exports.title2Pascal = title2Pascal;
208
570
  exports.title2Snake = title2Snake;
571
+ exports.toThousands = toThousands;
572
+ exports.userAgent = userAgent;
573
+ exports.waitTime = waitTime;