@oipage/core.js 1.0.0-alpha.1 → 1.1.0-alpha.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.
Files changed (85) hide show
  1. package/CHANGELOG +52 -5
  2. package/LICENSE +20 -20
  3. package/README.md +170 -50
  4. package/dist/core.esm.js +2711 -0
  5. package/dist/core.js +2715 -147
  6. package/dist/core.min.js +2 -6
  7. package/package.json +63 -34
  8. package/src/Array/group.js +35 -0
  9. package/src/Array/index.js +21 -0
  10. package/src/Array/list.js +79 -0
  11. package/src/Array/sort.js +40 -0
  12. package/src/Array/tool.js +20 -0
  13. package/src/Array/unique.js +30 -0
  14. package/src/Cache/driver.js +86 -0
  15. package/src/Cache/expire.js +21 -0
  16. package/src/Cache/index.js +33 -0
  17. package/src/Cache/store.js +113 -0
  18. package/src/Color/adjust.js +67 -0
  19. package/src/Color/convert.js +100 -0
  20. package/src/Color/index.js +19 -0
  21. package/src/Color/tool.js +39 -0
  22. package/src/Digits/compare.js +33 -0
  23. package/src/Digits/format.js +55 -0
  24. package/src/Digits/index.js +32 -0
  25. package/src/Digits/math.js +75 -0
  26. package/src/Digits/precise.js +230 -0
  27. package/src/Digits/tool.js +29 -0
  28. package/src/Id/index.js +17 -0
  29. package/src/Id/nanoid.js +24 -0
  30. package/src/Id/random.js +40 -0
  31. package/src/Id/tool.js +38 -0
  32. package/src/Id/uuid.js +21 -0
  33. package/src/Object/check.js +15 -0
  34. package/src/Object/clone.js +66 -0
  35. package/src/Object/equal.js +63 -0
  36. package/src/Object/index.js +25 -0
  37. package/src/Object/merge.js +35 -0
  38. package/src/Object/path.js +58 -0
  39. package/src/Object/pick.js +34 -0
  40. package/src/Query/index.js +14 -0
  41. package/src/Query/parse.js +40 -0
  42. package/src/Query/stringify.js +45 -0
  43. package/src/Query/tool.js +58 -0
  44. package/src/Query/url.js +63 -0
  45. package/src/String/case.js +35 -0
  46. package/src/String/escape.js +40 -0
  47. package/src/String/index.js +28 -0
  48. package/src/String/mask.js +70 -0
  49. package/src/String/pad.js +23 -0
  50. package/src/String/trim.js +10 -0
  51. package/src/String/truncate.js +36 -0
  52. package/src/String/width.js +27 -0
  53. package/src/Time/arithmetic.js +61 -0
  54. package/src/Time/calendar.js +37 -0
  55. package/src/Time/compare.js +28 -0
  56. package/src/Time/field.js +37 -0
  57. package/src/Time/format.js +28 -0
  58. package/src/Time/index.js +97 -0
  59. package/src/Time/tool.js +20 -0
  60. package/src/Validate/contact.js +14 -0
  61. package/src/Validate/identity.js +57 -0
  62. package/src/Validate/index.js +24 -0
  63. package/src/Validate/network.js +59 -0
  64. package/src/Validate/type.js +28 -0
  65. package/src/index.js +10 -1
  66. package/src/shared/date.js +123 -0
  67. package/src/shared/is.js +63 -0
  68. package/src/tool.js +3 -0
  69. package/types/Array.d.ts +33 -0
  70. package/types/Cache.d.ts +51 -0
  71. package/types/Color.d.ts +43 -0
  72. package/types/Digits.d.ts +92 -0
  73. package/types/Id.d.ts +25 -0
  74. package/types/Object.d.ts +45 -0
  75. package/types/Query.d.ts +35 -0
  76. package/types/String.d.ts +62 -0
  77. package/types/Time.d.ts +136 -0
  78. package/types/Validate.d.ts +39 -0
  79. package/types/index.d.ts +30 -3
  80. package/.github/FUNDING.yml +0 -12
  81. package/.mailmap +0 -1
  82. package/AUTHORS.txt +0 -6
  83. package/src/Dater/index.js +0 -61
  84. package/src/Dater/tool.js +0 -25
  85. package/types/Dater.ts +0 -31
@@ -0,0 +1,2711 @@
1
+ /*!
2
+ * @oipage/core.js v1.1.0-alpha.0
3
+ * git+https://github.com/oi-contrib/oipage-corejs.git
4
+ */
5
+ /**
6
+ * 日期相关的纯函数工具
7
+ * 内部使用,不对外导出
8
+ */
9
+
10
+ // 常见的日期格式片段(按最长优先匹配)
11
+ const TOKENS = ["yyyy", "MM", "dd", "HH", "mm", "ss", "yy", "M", "d"];
12
+
13
+ const GROUP_PATTERN = {
14
+ yyyy: "(\\d{4})",
15
+ yy: "(\\d{2})",
16
+ MM: "(\\d{1,2})",
17
+ M: "(\\d{1,2})",
18
+ dd: "(\\d{1,2})",
19
+ d: "(\\d{1,2})",
20
+ HH: "(\\d{1,2})",
21
+ mm: "(\\d{1,2})",
22
+ ss: "(\\d{1,2})"
23
+ };
24
+
25
+ function pad2$1(value) {
26
+ return value < 10 ? "0" + value : "" + value
27
+ }
28
+
29
+ function isLeapYear(year) {
30
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
31
+ }
32
+
33
+ // 某年某月有多少天
34
+ function daysInMonth(year, month) {
35
+ return [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]
36
+ }
37
+
38
+ /**
39
+ * 按 format 把年月日格式化为字符串
40
+ * 支持 yyyy、yy、MM、M、dd、d、HH、mm、ss,其中时间部分固定输出 00
41
+ */
42
+ function formatDate(year, month, day, format) {
43
+ return String(format).replace(/yyyy|MM|dd|HH|mm|ss|yy|M|d/g, function (token) {
44
+ switch (token) {
45
+ case "yyyy": return "" + year
46
+ case "yy": return pad2$1(year % 100)
47
+ case "MM": return pad2$1(month)
48
+ case "M": return "" + month
49
+ case "dd": return pad2$1(day)
50
+ case "d": return "" + day
51
+ default: return "00" // HH、mm、ss
52
+ }
53
+ })
54
+ }
55
+
56
+ /**
57
+ * 按 format 解析日期字符串
58
+ * 格式中的非 token 字符按“任意一个非数字字符”处理,因此可以不区分分隔符
59
+ * 解析失败会抛出错误,不接受兜底到“今天”
60
+ */
61
+ function parseDate(input, format) {
62
+ let source = "";
63
+ let tokens = [];
64
+ let index = 0;
65
+
66
+ while (index < format.length) {
67
+ let matched = null;
68
+ for (let i = 0; i < TOKENS.length; i++) {
69
+ if (format.substring(index, index + TOKENS[i].length) === TOKENS[i]) {
70
+ matched = TOKENS[i];
71
+ break
72
+ }
73
+ }
74
+
75
+ if (matched) {
76
+ source += GROUP_PATTERN[matched];
77
+ tokens.push(matched);
78
+ index += matched.length;
79
+ } else {
80
+ source += "[^0-9]?";
81
+ index += 1;
82
+ }
83
+ }
84
+
85
+ let result = new RegExp("^" + source).exec(String(input).trim());
86
+ if (!result) {
87
+ throw new TypeError("无法按格式 " + format + " 解析日期:" + input)
88
+ }
89
+
90
+ let year = null, month = null, day = null;
91
+ for (let i = 0; i < tokens.length; i++) {
92
+ let value = +result[i + 1];
93
+ switch (tokens[i]) {
94
+ case "yyyy": year = value; break
95
+ case "yy": year = value <= 49 ? 2000 + value : 1900 + value; break
96
+ case "MM": case "M": month = value; break
97
+ case "dd": case "d": day = value; break
98
+ }
99
+ }
100
+
101
+ if (year === null || month === null || day === null) {
102
+ throw new TypeError("格式 " + format + " 中缺少年、月、日:" + input)
103
+ }
104
+
105
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {
106
+ throw new TypeError("非法的日期:" + input)
107
+ }
108
+
109
+ return { year: year, month: month, day: day }
110
+ }
111
+
112
+ /**
113
+ * 用 setFullYear 构造本地时间零点,避免 new Date(年, ...) 把 0-99 年映射成 1900+
114
+ */
115
+ function toLocalDate(year, month, day) {
116
+ let date = new Date(2000, 0, 1, 0, 0, 0, 0);
117
+ date.setFullYear(year, month - 1, day);
118
+ return date
119
+ }
120
+
121
+ // 是否合法的年月日组合
122
+ function isValidDate(year, month, day) {
123
+ return typeof year === "number" && isFinite(year) && year === Math.floor(year)
124
+ && typeof month === "number" && month === Math.floor(month) && month >= 1 && month <= 12
125
+ && typeof day === "number" && day === Math.floor(day) && day >= 1
126
+ && day <= daysInMonth(year, month)
127
+ }
128
+
129
+ /**
130
+ * 基础类型判断
131
+ * 内部使用的工具函数,不对外导出
132
+ */
133
+ const toString = Object.prototype.toString;
134
+
135
+ function is(value, type) {
136
+ return toString.call(value) === "[object " + type + "]"
137
+ }
138
+
139
+ function isInteger$1(value) {
140
+ return typeof value === "number" && isFinite(value) && Math.floor(value) === value
141
+ }
142
+
143
+ function isDate(value) {
144
+ return is(value, "Date")
145
+ }
146
+
147
+ function isRegExp(value) {
148
+ return is(value, "RegExp")
149
+ }
150
+
151
+ function isMap(value) {
152
+ return is(value, "Map")
153
+ }
154
+
155
+ function isSet(value) {
156
+ return is(value, "Set")
157
+ }
158
+
159
+ function isArrayBuffer(value) {
160
+ return is(value, "ArrayBuffer")
161
+ }
162
+
163
+ const objectToString = Function.prototype.toString.call(Object);
164
+
165
+ function isPlainObject(value) {
166
+ if (!is(value, "Object")) return false
167
+
168
+ let proto = Object.getPrototypeOf(value);
169
+ if (proto === null) return true
170
+
171
+ // 跨 realm(iframe、另一个 window、vm 沙箱)时 proto 不是当前 realm 的 Object.prototype,
172
+ // 改为比较原型上 constructor 的源码,避免把外来普通对象误判成类实例
173
+ let ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
174
+ return typeof ctor === "function" && Function.prototype.toString.call(ctor) === objectToString
175
+ }
176
+
177
+ function isNil(value) {
178
+ return value === null || value === undefined
179
+ }
180
+
181
+ /**
182
+ * Time 字段与转换
183
+ */
184
+
185
+ function useFields(Time) {
186
+ /**
187
+ * 当前维护的日期是否仍然合法(直接修改 year/month/day 后可能非法)
188
+ */
189
+ Time.prototype.isValid = function () {
190
+ return isValidDate(this.year, this.month, this.day)
191
+ };
192
+
193
+ /**
194
+ * 复制一个内容相同、格式相同的新对象
195
+ */
196
+ Time.prototype.clone = function () {
197
+ return new Time(this.getTime(), {
198
+ input: this.inputFormat,
199
+ output: this.outputFormat
200
+ })
201
+ };
202
+
203
+ /**
204
+ * 本地时间零点对应的时间戳
205
+ */
206
+ Time.prototype.getTime = function () {
207
+ return toLocalDate(this.year, this.month, this.day).getTime()
208
+ };
209
+
210
+ /**
211
+ * 转成可以直接使用的 Date 对象(本地时间零点)
212
+ */
213
+ Time.prototype.toDate = function () {
214
+ return toLocalDate(this.year, this.month, this.day)
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Time 格式化输出
220
+ */
221
+
222
+ function useFormat$1(Time) {
223
+ /**
224
+ * 按指定格式返回当前维护的日期,不传时用 outputFormat
225
+ */
226
+ Time.prototype.format = function (format) {
227
+ return formatDate(this.year, this.month, this.day, format || this.outputFormat)
228
+ };
229
+
230
+ /**
231
+ * 按照 outputFormat 格式返回当前维护的日期
232
+ */
233
+ Time.prototype.valueOf = function () {
234
+ return this.format()
235
+ };
236
+
237
+ Time.prototype.toString = function () {
238
+ return this.format()
239
+ };
240
+
241
+ Time.prototype.toJSON = function () {
242
+ return this.format()
243
+ };
244
+ }
245
+
246
+ /**
247
+ * Time 日期加减
248
+ */
249
+
250
+ function useArithmetic(Time) {
251
+ /**
252
+ * 新增 year 年(负数即减少),闰日会自动夹取到当月最后一天
253
+ */
254
+ Time.prototype.addYear = function (year) {
255
+ if (!isInteger$1(year)) throw new TypeError("addYear 需要整数,收到:" + year)
256
+ this.year += year;
257
+
258
+ let totalDay = daysInMonth(this.year, this.month);
259
+ if (totalDay < this.day) this.day = totalDay;
260
+
261
+ return this
262
+ };
263
+
264
+ /**
265
+ * 新增 month 月(负数即减少),月末日期会自动夹取到当月最后一天
266
+ */
267
+ Time.prototype.addMonth = function (month) {
268
+ if (!isInteger$1(month)) throw new TypeError("addMonth 需要整数,收到:" + month)
269
+
270
+ let total = (this.year * 12 + this.month - 1) + month;
271
+ this.year = Math.floor(total / 12);
272
+ this.month = total - this.year * 12 + 1;
273
+
274
+ let totalDay = daysInMonth(this.year, this.month);
275
+ if (totalDay < this.day) this.day = totalDay;
276
+
277
+ return this
278
+ };
279
+
280
+ /**
281
+ * 新增 day 天(负数即减少)
282
+ * 使用本地日历做加减,跨月、跨年、跨夏令时都安全
283
+ */
284
+ Time.prototype.addDay = function (day) {
285
+ if (!isInteger$1(day)) throw new TypeError("addDay 需要整数,收到:" + day)
286
+
287
+ let dateObj = this.toDate();
288
+ dateObj.setDate(dateObj.getDate() + day);
289
+
290
+ this.year = dateObj.getFullYear();
291
+ this.month = dateObj.getMonth() + 1;
292
+ this.day = dateObj.getDate();
293
+
294
+ return this
295
+ };
296
+
297
+ /**
298
+ * 新增 week 周(负数即减少)
299
+ */
300
+ Time.prototype.addWeek = function (week) {
301
+ if (!isInteger$1(week)) throw new TypeError("addWeek 需要整数,收到:" + week)
302
+ return this.addDay(week * 7)
303
+ };
304
+ }
305
+
306
+ /**
307
+ * Time 内部工具
308
+ */
309
+
310
+ function utcStamp(year, month, day) {
311
+ let date = new Date(0);
312
+ date.setUTCFullYear(year, month - 1, day);
313
+ date.setUTCHours(0, 0, 0, 0);
314
+ return date.getTime()
315
+ }
316
+
317
+ function toTime(Time, value, inputFormat) {
318
+ if (value instanceof Time) return value
319
+ if (isDate(value) || typeof value === "number") return new Time(value)
320
+ if (typeof value === "string") {
321
+ return new Time(value, inputFormat ? { input: inputFormat, output: inputFormat } : undefined)
322
+ }
323
+ throw new TypeError("无法转换为 Time 的参数:" + value)
324
+ }
325
+
326
+ /**
327
+ * Time 比较
328
+ */
329
+
330
+ function useCompare$1(Time) {
331
+ /**
332
+ * 与另一个日期相差的天数(this 比 other 晚则为正数)
333
+ */
334
+ Time.prototype.diffDays = function (other) {
335
+ let target = toTime(Time, other, this.inputFormat);
336
+ let selfStamp = utcStamp(this.year, this.month, this.day);
337
+ let targetStamp = utcStamp(target.year, target.month, target.day);
338
+ return Math.round((selfStamp - targetStamp) / 86400000)
339
+ };
340
+
341
+ Time.prototype.isBefore = function (other) {
342
+ return this.diffDays(other) < 0
343
+ };
344
+
345
+ Time.prototype.isAfter = function (other) {
346
+ return this.diffDays(other) > 0
347
+ };
348
+
349
+ Time.prototype.isSame = function (other) {
350
+ return this.diffDays(other) === 0
351
+ };
352
+ }
353
+
354
+ /**
355
+ * Time 月历信息
356
+ */
357
+
358
+ function useCalendar(Time) {
359
+ /**
360
+ * 把日期调整到当月第一天
361
+ */
362
+ Time.prototype.startOfMonth = function () {
363
+ this.day = 1;
364
+ return this
365
+ };
366
+
367
+ /**
368
+ * 把日期调整到当月最后一天
369
+ */
370
+ Time.prototype.endOfMonth = function () {
371
+ this.day = daysInMonth(this.year, this.month);
372
+ return this
373
+ };
374
+
375
+ /**
376
+ * 星期几:0 表示周日,1-6 表示周一至周六
377
+ */
378
+ Time.prototype.getWeekDay = function () {
379
+ return this.toDate().getDay()
380
+ };
381
+
382
+ Time.prototype.isLeapYear = function () {
383
+ return isLeapYear(this.year)
384
+ };
385
+
386
+ Time.prototype.daysInMonth = function () {
387
+ return daysInMonth(this.year, this.month)
388
+ };
389
+ }
390
+
391
+ /**
392
+ * 日期对象:只维护年、月、日
393
+ *
394
+ * @param {string|Date|number} date 日期,可以是字符串、Date 对象或时间戳,默认今天
395
+ * @param {object} format 格式配置
396
+ * @param {string} format.input 字符串输入格式,默认 yyyy/MM/dd
397
+ * @param {string} format.output 输出格式,默认 yyyy/MM/dd
398
+ */
399
+ function Time(date, format) {
400
+ format = format || {};
401
+
402
+ Object.defineProperty(this, "inputFormat", {
403
+ value: format.input || "yyyy/MM/dd",
404
+ writable: true,
405
+ enumerable: false
406
+ });
407
+ Object.defineProperty(this, "outputFormat", {
408
+ value: format.output || "yyyy/MM/dd",
409
+ writable: true,
410
+ enumerable: false
411
+ });
412
+
413
+ let year, month, day;
414
+
415
+ // 空值兜底为今天
416
+ if (date === undefined || date === null || date === "") {
417
+ let now = new Date();
418
+ year = now.getFullYear();
419
+ month = now.getMonth() + 1;
420
+ day = now.getDate();
421
+ }
422
+
423
+ // 字符串
424
+ else if (typeof date === "string") {
425
+ let temp = parseDate(date, this.inputFormat);
426
+ year = temp.year;
427
+ month = temp.month;
428
+ day = temp.day;
429
+ }
430
+
431
+ // 时间戳
432
+ else if (typeof date === "number") {
433
+ if (!isFinite(date)) throw new TypeError("非法的日期时间戳:" + date)
434
+ let dateObj = new Date(date);
435
+ year = dateObj.getFullYear();
436
+ month = dateObj.getMonth() + 1;
437
+ day = dateObj.getDate();
438
+ }
439
+
440
+ // Date 对象
441
+ else if (isDate(date)) {
442
+ if (isNaN(date.getTime())) throw new TypeError("非法的 Date 对象")
443
+ year = date.getFullYear();
444
+ month = date.getMonth() + 1;
445
+ day = date.getDate();
446
+ }
447
+
448
+ else {
449
+ throw new TypeError("Time 只接受字符串、Date 对象或时间戳,收到:" + date)
450
+ }
451
+
452
+ if (!isValidDate(year, month, day)) {
453
+ throw new TypeError("非法的日期:" + date)
454
+ }
455
+
456
+ this.year = year;
457
+ this.month = month;
458
+ this.day = day;
459
+ }
460
+
461
+ useFields(Time);
462
+ useFormat$1(Time);
463
+ useArithmetic(Time);
464
+ useCompare$1(Time);
465
+ useCalendar(Time);
466
+
467
+ /**
468
+ * 今天
469
+ */
470
+ Time.today = function (format) {
471
+ return new Time(undefined, format)
472
+ };
473
+
474
+ /**
475
+ * 按指定格式解析日期字符串
476
+ */
477
+ Time.parse = function (input, format) {
478
+ return new Time(input, { input: format, output: format })
479
+ };
480
+
481
+ /**
482
+ * 十进制高精度运算引擎
483
+ *
484
+ * 内部用 BigInt 保存“整数部分 + 小数位数”({ big, scale },实际值 = big / 10^scale),
485
+ * 全部运算都在整数域完成,不经过浮点,避免 0.1 + 0.2 这类精度问题。
486
+ * 注意:这里一律用 BigInt() 构造而不是 10n 字面量,保证产物不需要提高语法目标。
487
+ */
488
+
489
+ // 部分旧引擎(老版本小程序基础库、iOS 14 以下 Safari)没有 BigInt,
490
+ // 这里不能在模块加载期就调用 BigInt(),否则整个包都会 import 失败
491
+ const HAS_BIGINT = typeof BigInt === "function";
492
+ const TEN = HAS_BIGINT ? BigInt(10) : 10;
493
+ const ZERO = HAS_BIGINT ? BigInt(0) : 0;
494
+ const TWO = HAS_BIGINT ? BigInt(2) : 2;
495
+
496
+ const NUMBER_RE = /^([+-]?)(\d+)?(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
497
+
498
+ const ROUNDINGS = ["half-up", "half-even", "ceil", "floor", "trunc"];
499
+
500
+ function pow10(n) {
501
+ let result = BigInt(1);
502
+ for (let i = 0; i < n; i++) result = result * TEN;
503
+ return result
504
+ }
505
+
506
+ function abs(value) {
507
+ return value < ZERO ? -value : value
508
+ }
509
+
510
+ // 去掉小数末尾多余的 0
511
+ function normalize(big, scale) {
512
+ while (scale > 0 && big % TEN === ZERO) {
513
+ big = big / TEN;
514
+ scale -= 1;
515
+ }
516
+ return { big: big, scale: scale }
517
+ }
518
+
519
+ function checkRounding(rounding) {
520
+ if (ROUNDINGS.indexOf(rounding) === -1) {
521
+ throw new TypeError("不支持的舍入模式:" + rounding + ",可选 " + ROUNDINGS.join("、"))
522
+ }
523
+ return rounding
524
+ }
525
+
526
+ /**
527
+ * 把任意数字形态转成内部十进制表示
528
+ * 支持 number、string(可带千分位和小数)、bigint、以及内部表示
529
+ */
530
+ function toDecimal(value) {
531
+ if (!HAS_BIGINT) {
532
+ throw new TypeError("当前运行环境不支持 BigInt,Digits 无法使用:请升级小程序基础库 / iOS 14+ / Node 10.4+")
533
+ }
534
+
535
+ if (value && typeof value === "object" && typeof value.big === "bigint") {
536
+ return value
537
+ }
538
+
539
+ if (typeof value === "bigint") {
540
+ return { big: value, scale: 0 }
541
+ }
542
+
543
+ let str;
544
+ if (typeof value === "number") {
545
+ if (!isFinite(value)) throw new TypeError("不是合法的数字:" + value)
546
+ str = String(value);
547
+ } else if (typeof value === "string") {
548
+ str = value.trim().replace(/,/g, "");
549
+ } else {
550
+ throw new TypeError("不是合法的数字:" + value)
551
+ }
552
+
553
+ let matched = NUMBER_RE.exec(str);
554
+ if (!matched || (!matched[2] && !matched[3])) {
555
+ throw new TypeError("不是合法的数字:" + value)
556
+ }
557
+
558
+ let negative = matched[1] === "-";
559
+ let integerPart = matched[2] || "";
560
+ let decimalPart = matched[3] || "";
561
+ let exponent = matched[4] ? parseInt(matched[4], 10) : 0;
562
+
563
+ let digits = integerPart + decimalPart;
564
+ let scale = decimalPart.length - exponent;
565
+
566
+ if (scale < 0) {
567
+ digits += "0".repeat(-scale);
568
+ scale = 0;
569
+ }
570
+
571
+ digits = digits.replace(/^0+(?=\d)/, "");
572
+
573
+ let big = BigInt(digits);
574
+ if (negative) big = -big;
575
+
576
+ return normalize(big, scale)
577
+ }
578
+
579
+ // 内部十进制表示转字符串(精确值,不丢精度)
580
+ function toStr(decimal) {
581
+ let negative = decimal.big < ZERO;
582
+ let digits = (negative ? -decimal.big : decimal.big).toString();
583
+ let scale = decimal.scale;
584
+
585
+ if (scale === 0) return (negative ? "-" : "") + digits
586
+
587
+ if (digits.length <= scale) {
588
+ digits = "0".repeat(scale - digits.length + 1) + digits;
589
+ }
590
+
591
+ let cut = digits.length - scale;
592
+ return (negative ? "-" : "") + digits.substring(0, cut) + "." + digits.substring(cut)
593
+ }
594
+
595
+ function toNumber(decimal) {
596
+ return Number(toStr(decimal))
597
+ }
598
+
599
+ function compare(a, b) {
600
+ a = toDecimal(a);
601
+ b = toDecimal(b);
602
+
603
+ let maxScale = Math.max(a.scale, b.scale);
604
+ let left = a.big * pow10(maxScale - a.scale);
605
+ let right = b.big * pow10(maxScale - b.scale);
606
+
607
+ return left === right ? 0 : (left > right ? 1 : -1)
608
+ }
609
+
610
+ function add(a, b) {
611
+ a = toDecimal(a);
612
+ b = toDecimal(b);
613
+
614
+ let maxScale = Math.max(a.scale, b.scale);
615
+ let left = a.big * pow10(maxScale - a.scale);
616
+ let right = b.big * pow10(maxScale - b.scale);
617
+
618
+ return normalize(left + right, maxScale)
619
+ }
620
+
621
+ function subtract(a, b) {
622
+ a = toDecimal(a);
623
+ b = toDecimal(b);
624
+
625
+ let maxScale = Math.max(a.scale, b.scale);
626
+ let left = a.big * pow10(maxScale - a.scale);
627
+ let right = b.big * pow10(maxScale - b.scale);
628
+
629
+ return normalize(left - right, maxScale)
630
+ }
631
+
632
+ function multiply(a, b) {
633
+ a = toDecimal(a);
634
+ b = toDecimal(b);
635
+
636
+ return normalize(a.big * b.big, a.scale + b.scale)
637
+ }
638
+
639
+ /**
640
+ * 在“已截断的商 q 和余数 r”上按指定模式进位,q、denominator 都是非负的绝对值
641
+ */
642
+ function roundQuotient(q, r, denominator, negative, rounding) {
643
+ if (r === ZERO) return q
644
+
645
+ let doubled = r * TWO;
646
+
647
+ switch (rounding) {
648
+ case "half-up":
649
+ if (doubled >= denominator) q += BigInt(1);
650
+ break
651
+ case "half-even":
652
+ if (doubled > denominator || (doubled === denominator && q % TWO !== ZERO)) q += BigInt(1);
653
+ break
654
+ case "ceil":
655
+ if (!negative) q += BigInt(1);
656
+ break
657
+ case "floor":
658
+ if (negative) q += BigInt(1);
659
+ break
660
+ }
661
+
662
+ return q
663
+ }
664
+
665
+ function divide(a, b, scale, rounding) {
666
+ a = toDecimal(a);
667
+ b = toDecimal(b);
668
+
669
+ if (b.big === ZERO) throw new RangeError("除数不能为0")
670
+
671
+ scale = scale === undefined ? 16 : scale;
672
+ rounding = checkRounding(rounding || "half-up");
673
+
674
+ let negative = (a.big < ZERO) !== (b.big < ZERO);
675
+
676
+ let left = abs(a.big) * pow10(b.scale + scale);
677
+ let right = abs(b.big) * pow10(a.scale);
678
+
679
+ let q = left / right;
680
+ let r = left % right;
681
+
682
+ q = roundQuotient(q, r, right, negative, rounding);
683
+
684
+ return normalize(negative ? -q : q, scale)
685
+ }
686
+
687
+ /**
688
+ * 把十进制表示按 scale 位小数舍入
689
+ */
690
+ function round(decimal, scale, rounding) {
691
+ decimal = toDecimal(decimal);
692
+ scale = scale === undefined ? 0 : scale;
693
+ rounding = checkRounding(rounding || "half-up");
694
+
695
+ if (scale < 0) throw new RangeError("scale 不能为负数:" + scale)
696
+
697
+ if (decimal.scale <= scale) {
698
+ return { big: decimal.big * pow10(scale - decimal.scale), scale: scale }
699
+ }
700
+
701
+ let negative = decimal.big < ZERO;
702
+ let drop = pow10(decimal.scale - scale);
703
+
704
+ let q = abs(decimal.big) / drop;
705
+ let r = abs(decimal.big) % drop;
706
+
707
+ q = roundQuotient(q, r, drop, negative, rounding);
708
+
709
+ return normalize(negative ? -q : q, scale)
710
+ }
711
+
712
+ /**
713
+ * Digits 内部工具
714
+ */
715
+
716
+ function fixedString(decimal, scale) {
717
+ let str = toStr(decimal);
718
+ let dotIndex = str.indexOf(".");
719
+
720
+ if (dotIndex === -1) {
721
+ return scale === 0 ? str : str + "." + "0".repeat(scale)
722
+ }
723
+
724
+ let current = str.length - dotIndex - 1;
725
+ if (current >= scale) return str
726
+
727
+ return str + "0".repeat(scale - current)
728
+ }
729
+
730
+ function thousands(str) {
731
+ let negative = str.charAt(0) === "-";
732
+ let body = negative ? str.substring(1) : str;
733
+ let dotIndex = body.indexOf(".");
734
+
735
+ let integerPart = dotIndex === -1 ? body : body.substring(0, dotIndex);
736
+ let decimalPart = dotIndex === -1 ? "" : body.substring(dotIndex);
737
+
738
+ return (negative ? "-" : "") + integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + decimalPart
739
+ }
740
+
741
+ /**
742
+ * Digits 格式化输出
743
+ */
744
+
745
+ function useFormat(Digits) {
746
+ /**
747
+ * 返回格式化后的数字,默认保留 2 位小数、四舍五入、带千分位
748
+ *
749
+ * @param {number} scale 小数位数,默认 2
750
+ * @param {object} options
751
+ * @param {string} options.rounding 舍入模式:half-up、half-even、ceil、floor、trunc,默认 half-up
752
+ * @param {boolean} options.thousands 是否加千分位,默认 true
753
+ */
754
+ Digits.prototype.format = function (scale, options) {
755
+ scale = scale === undefined ? 2 : scale;
756
+ options = options || {};
757
+
758
+ let rounded = round(this._decimal, scale, options.rounding || "half-up");
759
+ let str = fixedString(rounded, scale);
760
+
761
+ return options.thousands === false ? str : thousands(str)
762
+ };
763
+
764
+ /**
765
+ * 当前值的精确字符串表示(不受浮点精度影响)
766
+ */
767
+ Digits.prototype.toString = function () {
768
+ return toStr(this._decimal)
769
+ };
770
+
771
+ Digits.prototype.valueOf = function () {
772
+ return this.value
773
+ };
774
+
775
+ Digits.prototype.toJSON = function () {
776
+ return this.value
777
+ };
778
+
779
+ /**
780
+ * 取当前值(等价于 digits.value)
781
+ */
782
+ Digits.prototype.getValue = function () {
783
+ return this.value
784
+ };
785
+
786
+ /**
787
+ * 返回保留 scale 位小数的字符串
788
+ */
789
+ Digits.prototype.toFixed = function (scale, rounding) {
790
+ scale = scale === undefined ? 2 : scale;
791
+ return fixedString(round(this._decimal, scale, rounding), scale)
792
+ };
793
+ }
794
+
795
+ /**
796
+ * Digits 运算
797
+ */
798
+
799
+ function useMath(Digits) {
800
+ /**
801
+ * 高精度加法
802
+ */
803
+ Digits.prototype.add = function (value) {
804
+ this._decimal = add(this._decimal, value);
805
+ return this
806
+ };
807
+
808
+ /**
809
+ * 高精度减法
810
+ */
811
+ Digits.prototype.subtract = function (value) {
812
+ this._decimal = subtract(this._decimal, value);
813
+ return this
814
+ };
815
+
816
+ /**
817
+ * 高精度乘法
818
+ */
819
+ Digits.prototype.multiply = function (value) {
820
+ this._decimal = multiply(this._decimal, value);
821
+ return this
822
+ };
823
+
824
+ /**
825
+ * 高精度除法
826
+ *
827
+ * @param {number|string} value 除数,为 0 时抛错
828
+ * @param {object} options
829
+ * @param {number} options.scale 结果保留的小数位,默认 16
830
+ * @param {string} options.rounding 舍入模式,默认 half-up
831
+ */
832
+ Digits.prototype.divide = function (value, options) {
833
+ options = options || {};
834
+ this._decimal = divide(
835
+ this._decimal,
836
+ value,
837
+ options.scale === undefined ? 16 : options.scale,
838
+ options.rounding
839
+ );
840
+ return this
841
+ };
842
+
843
+ /**
844
+ * 就地四舍五入到 scale 位小数
845
+ */
846
+ Digits.prototype.round = function (scale, rounding) {
847
+ this._decimal = round(this._decimal, scale, rounding);
848
+ return this
849
+ };
850
+
851
+ /**
852
+ * 取绝对值
853
+ */
854
+ Digits.prototype.abs = function () {
855
+ if (this._decimal.big < BigInt(0)) {
856
+ this._decimal = { big: -this._decimal.big, scale: this._decimal.scale };
857
+ }
858
+ return this
859
+ };
860
+
861
+ /**
862
+ * 取相反数
863
+ */
864
+ Digits.prototype.negate = function () {
865
+ this._decimal = { big: -this._decimal.big, scale: this._decimal.scale };
866
+ return this
867
+ };
868
+ }
869
+
870
+ /**
871
+ * Digits 比较
872
+ */
873
+
874
+ function useCompare(Digits) {
875
+ /**
876
+ * 比较大小:大于返回 1,相等返回 0,小于返回 -1
877
+ */
878
+ Digits.prototype.compare = function (value) {
879
+ return compare(this._decimal, value)
880
+ };
881
+
882
+ Digits.prototype.eq = function (value) {
883
+ return this.compare(value) === 0
884
+ };
885
+
886
+ Digits.prototype.gt = function (value) {
887
+ return this.compare(value) > 0
888
+ };
889
+
890
+ Digits.prototype.gte = function (value) {
891
+ return this.compare(value) >= 0
892
+ };
893
+
894
+ Digits.prototype.lt = function (value) {
895
+ return this.compare(value) < 0
896
+ };
897
+
898
+ Digits.prototype.lte = function (value) {
899
+ return this.compare(value) <= 0
900
+ };
901
+ }
902
+
903
+ /**
904
+ * 数字对象:内部用 BigInt 定点表示,加减乘除都不经过浮点
905
+ *
906
+ * @param {number|string} value 初始值,默认 0
907
+ */
908
+ function Digits(value = 0) {
909
+
910
+ Object.defineProperty(this, "_decimal", {
911
+ value: toDecimal(value),
912
+ writable: true,
913
+ enumerable: false
914
+ });
915
+
916
+ Object.defineProperty(this, "value", {
917
+ enumerable: true,
918
+ get: function () {
919
+ return toNumber(this._decimal)
920
+ },
921
+ set: function (value) {
922
+ this._decimal = toDecimal(value);
923
+ }
924
+ });
925
+ }
926
+
927
+ useFormat(Digits);
928
+ useMath(Digits);
929
+ useCompare(Digits);
930
+
931
+ /**
932
+ * String 宽度与字符
933
+ */
934
+
935
+ const WIDE_RE = /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6]/;
936
+
937
+ function toChars(str) {
938
+ return Array.from(String(str))
939
+ }
940
+
941
+ /**
942
+ * 单个字符的显示宽度:中文等宽字符算 2,其余算 1
943
+ */
944
+ function widthOf(char) {
945
+ return WIDE_RE.test(char) ? 2 : 1
946
+ }
947
+
948
+ /**
949
+ * 字符串的显示宽度
950
+ */
951
+ function width(str) {
952
+ let total = 0;
953
+ toChars(str).forEach(function (char) {
954
+ total += widthOf(char);
955
+ });
956
+ return total
957
+ }
958
+
959
+ /**
960
+ * String 命名与反转
961
+ */
962
+
963
+ /**
964
+ * 转为小驼峰:foo-bar、foo_bar、foo bar 都转成 fooBar
965
+ */
966
+ function camelCase(str) {
967
+ let words = String(str).split(/[\s\-_./]+/).filter(Boolean);
968
+ return words.map(function (word, index) {
969
+ let lower = word.toLowerCase();
970
+ if (index === 0) return lower
971
+ return lower.charAt(0).toUpperCase() + lower.substring(1)
972
+ }).join("")
973
+ }
974
+
975
+ /**
976
+ * 转为短横线命名:fooBar 转成 foo-bar
977
+ */
978
+ function kebabCase(str) {
979
+ return String(str)
980
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
981
+ .replace(/[\s_./]+/g, "-")
982
+ .replace(/-+/g, "-")
983
+ .replace(/^-|-$/g, "")
984
+ .toLowerCase()
985
+ }
986
+
987
+ /**
988
+ * 反向字符串(按 Unicode 码位切分,不会拆坏 emoji 等代理对)
989
+ */
990
+ function reverse(str) {
991
+ return toChars(str).reverse().join("")
992
+ }
993
+
994
+ /**
995
+ * String HTML 转义
996
+ */
997
+
998
+ const ESCAPE_MAP = {
999
+ "&": "&amp;",
1000
+ "<": "&lt;",
1001
+ ">": "&gt;",
1002
+ '"': "&quot;",
1003
+ "'": "&#39;"
1004
+ };
1005
+
1006
+ const UNESCAPE_MAP = {
1007
+ "&amp;": "&",
1008
+ "&lt;": "<",
1009
+ "&gt;": ">",
1010
+ "&quot;": '"',
1011
+ "&#39;": "'",
1012
+ "&#x27;": "'"
1013
+ };
1014
+
1015
+ /**
1016
+ * 转义 HTML 特殊字符,用于把用户输入拼进页面
1017
+ */
1018
+ function escapeHTML(str) {
1019
+ return String(str).replace(/[&<>"']/g, function (char) {
1020
+ return ESCAPE_MAP[char]
1021
+ })
1022
+ }
1023
+
1024
+ /**
1025
+ * 还原 HTML 实体
1026
+ */
1027
+ function unescapeHTML(str) {
1028
+ return String(str).replace(/&(amp|lt|gt|quot|#39|#x27);/g, function (entity) {
1029
+ return UNESCAPE_MAP[entity] || entity
1030
+ })
1031
+ }
1032
+
1033
+ // 用命名空间对象导出,避免在本文件内遮蔽原生 String
1034
+
1035
+ /**
1036
+ * String 脱敏
1037
+ */
1038
+
1039
+ /**
1040
+ * 按 head/tail 保留首尾,中间用 char 替代
1041
+ */
1042
+ function maskMiddle(str, head, tail, char) {
1043
+ char = char === undefined ? "*" : String(char);
1044
+ let chars = toChars(str);
1045
+ head = Math.max(0, head || 0);
1046
+ tail = Math.max(0, tail || 0);
1047
+
1048
+ if (chars.length <= head + tail) {
1049
+ return char.repeat(chars.length)
1050
+ }
1051
+
1052
+ return chars.slice(0, head).join("")
1053
+ + char.repeat(chars.length - head - tail)
1054
+ + chars.slice(chars.length - tail).join("")
1055
+ }
1056
+
1057
+ /**
1058
+ * 常用脱敏
1059
+ *
1060
+ * @param {string} type mobile、idcard、bankcard、email、name,或 custom
1061
+ * @param {object} option custom 时的配置:head、tail、char
1062
+ */
1063
+ function mask(str, type, option) {
1064
+ str = String(str === undefined || str === null ? "" : str);
1065
+ if (!str) return ""
1066
+
1067
+ option = option || {};
1068
+ let char = option.char || "*";
1069
+
1070
+ switch (type) {
1071
+ case "mobile":
1072
+ return maskMiddle(str, 3, 4, char)
1073
+
1074
+ case "idcard":
1075
+ return maskMiddle(str, 6, 4, char)
1076
+
1077
+ case "bankcard": {
1078
+ let last = toChars(str).slice(-4).join("");
1079
+ let groups = [];
1080
+ for (let i = 0; i < 3; i++) groups.push(char.repeat(4));
1081
+ return groups.join(" ") + " " + last
1082
+ }
1083
+
1084
+ case "email": {
1085
+ let atIndex = str.indexOf("@");
1086
+ if (atIndex <= 0) return maskMiddle(str, 2, 2, char)
1087
+ let local = str.substring(0, atIndex);
1088
+ let host = str.substring(atIndex);
1089
+ if (local.length <= 2) return char.repeat(local.length) + host
1090
+ return local.substring(0, 2) + char.repeat(3) + host
1091
+ }
1092
+
1093
+ case "name": {
1094
+ let chars = toChars(str);
1095
+ if (chars.length === 1) return char
1096
+ if (chars.length === 2) return chars[0] + char
1097
+ return chars[0] + char.repeat(chars.length - 2) + chars[chars.length - 1]
1098
+ }
1099
+
1100
+ default:
1101
+ return maskMiddle(str, option.head || 0, option.tail || 0, char)
1102
+ }
1103
+ }
1104
+
1105
+ /**
1106
+ * String 补位
1107
+ */
1108
+
1109
+ /**
1110
+ * 补齐到指定显示宽度
1111
+ *
1112
+ * @param {string} position 补在左边用 "start",补在右边用 "end",默认 "end"
1113
+ */
1114
+ function pad(str, length, char, position) {
1115
+ str = String(str);
1116
+ char = char === undefined ? " " : String(char);
1117
+ let current = width(str);
1118
+ if (current >= length) return str
1119
+
1120
+ let fill = "";
1121
+ while (current + width(fill) + width(char) <= length) {
1122
+ fill += char;
1123
+ }
1124
+
1125
+ return position === "start" ? fill + str : str + fill
1126
+ }
1127
+
1128
+ /**
1129
+ * String 去空白
1130
+ */
1131
+
1132
+ /**
1133
+ * 去掉首尾空白,包含全角空格与不换行空格
1134
+ */
1135
+ function trim(str) {
1136
+ return String(str).replace(/^[\s\u00A0\u3000]+|[\s\u00A0\u3000]+$/g, "")
1137
+ }
1138
+
1139
+ /**
1140
+ * String 截断
1141
+ */
1142
+
1143
+ /**
1144
+ * 按字符数截断,超出部分用 suffix 替代
1145
+ */
1146
+ function truncate(str, maxLength, suffix) {
1147
+ suffix = suffix === undefined ? "..." : suffix;
1148
+ let chars = toChars(str);
1149
+ if (chars.length <= maxLength) return String(str)
1150
+ return chars.slice(0, Math.max(0, maxLength - Array.from(String(suffix)).length)).join("") + suffix
1151
+ }
1152
+
1153
+ /**
1154
+ * 按显示宽度截断(中文按 2 个宽度),超出部分用 suffix 替代
1155
+ */
1156
+ function cutByWidth(str, maxWidth, suffix) {
1157
+ suffix = suffix === undefined ? "..." : suffix;
1158
+ let suffixWidth = width(suffix);
1159
+ if (width(str) <= maxWidth) return String(str)
1160
+
1161
+ let total = 0;
1162
+ let result = [];
1163
+ let chars = toChars(str);
1164
+
1165
+ for (let i = 0; i < chars.length; i++) {
1166
+ let current = widthOf(chars[i]);
1167
+ if (total + current > maxWidth - suffixWidth) break
1168
+ total += current;
1169
+ result.push(chars[i]);
1170
+ }
1171
+
1172
+ return result.join("") + suffix
1173
+ }
1174
+
1175
+ /**
1176
+ * String 对外入口
1177
+ */
1178
+
1179
+ const StringUtil = {
1180
+ trim: trim,
1181
+ width: width,
1182
+ widthOf: widthOf,
1183
+ truncate: truncate,
1184
+ cutByWidth: cutByWidth,
1185
+ pad: pad,
1186
+ camelCase: camelCase,
1187
+ kebabCase: kebabCase,
1188
+ reverse: reverse,
1189
+ mask: mask,
1190
+ maskMiddle: maskMiddle,
1191
+ escapeHTML: escapeHTML,
1192
+ unescapeHTML: unescapeHTML
1193
+ };
1194
+
1195
+ /**
1196
+ * Validate 联系方式
1197
+ */
1198
+
1199
+ /**
1200
+ * 中国大陆手机号(含 13-19 号段)
1201
+ */
1202
+ function isMobile(value) {
1203
+ return /^1[3-9]\d{9}$/.test(String(value))
1204
+ }
1205
+
1206
+ function isEmail(value) {
1207
+ return /^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}$/.test(String(value))
1208
+ }
1209
+
1210
+ /**
1211
+ * Validate 证件与银行卡
1212
+ */
1213
+
1214
+ /**
1215
+ * 身份证号:15 位或 18 位,会校验出生日期与末位校验码
1216
+ */
1217
+ function isIdCard(value) {
1218
+ let str = String(value);
1219
+
1220
+ if (!/^\d{15}$/.test(str) && !/^\d{17}[\dXx]$/.test(str)) return false
1221
+
1222
+ let year, month, day;
1223
+ if (str.length === 15) {
1224
+ year = 1900 + (+str.substring(6, 8));
1225
+ month = +str.substring(8, 10);
1226
+ day = +str.substring(10, 12);
1227
+ } else {
1228
+ year = +str.substring(6, 10);
1229
+ month = +str.substring(10, 12);
1230
+ day = +str.substring(12, 14);
1231
+ }
1232
+
1233
+ if (!isValidDate(year, month, day)) return false
1234
+ if (str.length === 15) return true
1235
+
1236
+ let weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
1237
+ let codes = "10X98765432";
1238
+ let total = 0;
1239
+
1240
+ for (let i = 0; i < 17; i++) {
1241
+ total += (+str.charAt(i)) * weights[i];
1242
+ }
1243
+
1244
+ return codes.charAt(total % 11) === str.charAt(17).toUpperCase()
1245
+ }
1246
+
1247
+ /**
1248
+ * 银行卡号:12-19 位数字,且通过 Luhn 校验
1249
+ */
1250
+ function isBankCard(value) {
1251
+ let str = String(value).replace(/\s/g, "");
1252
+ if (!/^\d{12,19}$/.test(str)) return false
1253
+
1254
+ let total = 0;
1255
+ for (let i = 0; i < str.length; i++) {
1256
+ let digit = +str.charAt(str.length - 1 - i);
1257
+ if (i % 2 === 1) {
1258
+ digit *= 2;
1259
+ if (digit > 9) digit -= 9;
1260
+ }
1261
+ total += digit;
1262
+ }
1263
+
1264
+ return total % 10 === 0
1265
+ }
1266
+
1267
+ /**
1268
+ * Validate 网络地址
1269
+ */
1270
+
1271
+ function isUrl(value) {
1272
+ return /^((https?|ftp):\/\/)([\w-]+\.)*[\w-]+(:\d+)?(\/[\w\-./?%&=#+~:@!$'()*,;]*)?$/.test(String(value))
1273
+ }
1274
+
1275
+ /**
1276
+ * IPv4,要求每一段都在 0-255 之间
1277
+ */
1278
+ function isIPv4(value) {
1279
+ let parts = String(value).split(".");
1280
+ if (parts.length !== 4) return false
1281
+
1282
+ for (let i = 0; i < parts.length; i++) {
1283
+ if (!/^\d{1,3}$/.test(parts[i])) return false
1284
+ if (+parts[i] > 255) return false
1285
+ }
1286
+
1287
+ return true
1288
+ }
1289
+
1290
+ function isHexGroups(list) {
1291
+ return list.every(function (group) {
1292
+ return /^[0-9a-fA-F]{1,4}$/.test(group)
1293
+ })
1294
+ }
1295
+
1296
+ function isIPv6(value) {
1297
+ let str = String(value);
1298
+ if (!str) return false
1299
+
1300
+ let index = str.indexOf("::");
1301
+
1302
+ // 完整写法:8 组
1303
+ if (index === -1) {
1304
+ let groups = str.split(":");
1305
+ return groups.length === 8 && isHexGroups(groups)
1306
+ }
1307
+
1308
+ // 压缩写法只允许出现一次 ::
1309
+ if (str.indexOf("::", index + 2) !== -1) return false
1310
+
1311
+ let left = str.substring(0, index);
1312
+ let right = str.substring(index + 2);
1313
+
1314
+ let leftGroups = left ? left.split(":") : [];
1315
+ let rightGroups = right ? right.split(":") : [];
1316
+
1317
+ // :: 至少代表一组,因此两侧合计不能超过 7 组
1318
+ if (leftGroups.length + rightGroups.length > 7) return false
1319
+
1320
+ return isHexGroups(leftGroups) && isHexGroups(rightGroups)
1321
+ }
1322
+
1323
+ function isIp(value) {
1324
+ return isIPv4(value) || isIPv6(value)
1325
+ }
1326
+
1327
+ /**
1328
+ * Validate 数字与文本
1329
+ */
1330
+
1331
+ function isInteger(value) {
1332
+ if (typeof value === "number") {
1333
+ return isFinite(value) && Math.floor(value) === value
1334
+ }
1335
+ return /^[+-]?\d+$/.test(String(value).trim())
1336
+ }
1337
+
1338
+ /**
1339
+ * 小数(允许负号,不接受科学计数法)
1340
+ */
1341
+ function isDecimal(value) {
1342
+ return /^[+-]?(\d+\.?\d*|\.\d+)$/.test(String(value))
1343
+ }
1344
+
1345
+ function isChinese(value) {
1346
+ return /^[\u4E00-\u9FA5]+$/.test(String(value))
1347
+ }
1348
+
1349
+ /**
1350
+ * 中国大陆邮编
1351
+ */
1352
+ function isPostCode(value) {
1353
+ return /^[1-9]\d{5}$/.test(String(value))
1354
+ }
1355
+
1356
+ /**
1357
+ * Validate 对外入口
1358
+ */
1359
+
1360
+ const Valid = {
1361
+ isMobile: isMobile,
1362
+ isEmail: isEmail,
1363
+ isIdCard: isIdCard,
1364
+ isUrl: isUrl,
1365
+ isIPv4: isIPv4,
1366
+ isIPv6: isIPv6,
1367
+ isIp: isIp,
1368
+ isBankCard: isBankCard,
1369
+ isInteger: isInteger,
1370
+ isDecimal: isDecimal,
1371
+ isChinese: isChinese,
1372
+ isPostCode: isPostCode
1373
+ };
1374
+
1375
+ /**
1376
+ * Object 判空
1377
+ */
1378
+
1379
+ /**
1380
+ * 是否为空:null、undefined、空字符串、空数组、空 Map/Set、无键对象都算空
1381
+ */
1382
+ function isEmpty(value) {
1383
+ if (isNil(value)) return true
1384
+ if (typeof value === "string" || Array.isArray(value)) return value.length === 0
1385
+ if (isMap(value) || isSet(value)) return value.size === 0
1386
+ if (isPlainObject(value)) return Object.keys(value).length === 0
1387
+ return false
1388
+ }
1389
+
1390
+ /**
1391
+ * Object 路径读写
1392
+ */
1393
+
1394
+ /**
1395
+ * 把 a.b[0].c 这类路径转成键名数组
1396
+ */
1397
+ function toPath(path) {
1398
+ if (Array.isArray(path)) return path.map(String)
1399
+
1400
+ return String(path)
1401
+ .replace(/\[(?:"([^"]*)"|'([^']*)'|(\d+)|(\w+))\]/g, function (matched, dq, sq, index, word) {
1402
+ return "." + (dq || sq || index || word)
1403
+ })
1404
+ .split(".")
1405
+ .filter(function (key) {
1406
+ return key !== ""
1407
+ })
1408
+ }
1409
+
1410
+ /**
1411
+ * 按路径读取,路径不存在时返回 defaultValue
1412
+ */
1413
+ function get(target, path, defaultValue) {
1414
+ let keys = toPath(path);
1415
+ let current = target;
1416
+
1417
+ for (let i = 0; i < keys.length; i++) {
1418
+ if (isNil(current)) return defaultValue
1419
+ current = current[keys[i]];
1420
+ }
1421
+
1422
+ return current === undefined ? defaultValue : current
1423
+ }
1424
+
1425
+ /**
1426
+ * 按路径写入,路径中间不存在时自动创建对象或数组
1427
+ */
1428
+ function set(target, path, value) {
1429
+ if (typeof target !== "object" || target === null) {
1430
+ throw new TypeError("set 的目标必须是对象或数组")
1431
+ }
1432
+
1433
+ let keys = toPath(path);
1434
+ let current = target;
1435
+
1436
+ for (let i = 0; i < keys.length - 1; i++) {
1437
+ let key = keys[i];
1438
+ if (typeof current[key] !== "object" || current[key] === null) {
1439
+ current[key] = /^\d+$/.test(keys[i + 1]) ? [] : {};
1440
+ }
1441
+ current = current[key];
1442
+ }
1443
+
1444
+ current[keys[keys.length - 1]] = value;
1445
+ return target
1446
+ }
1447
+
1448
+ /**
1449
+ * Object 深拷贝
1450
+ */
1451
+
1452
+ /**
1453
+ * 深拷贝,支持 Date、RegExp、Map、Set、ArrayBuffer、普通对象与数组,能处理循环引用
1454
+ * 其它类型(如 DOM 节点、类实例)按引用返回
1455
+ */
1456
+ function deepClone(value, seen) {
1457
+ if (typeof value !== "object" || value === null) return value
1458
+
1459
+ seen = seen || new WeakMap();
1460
+ if (seen.has(value)) return seen.get(value)
1461
+
1462
+ if (isDate(value)) return new Date(value.getTime())
1463
+
1464
+ if (isRegExp(value)) {
1465
+ let reg = new RegExp(value.source, value.flags);
1466
+ reg.lastIndex = value.lastIndex;
1467
+ return reg
1468
+ }
1469
+
1470
+ if (isArrayBuffer(value)) return value.slice(0)
1471
+
1472
+ let result;
1473
+
1474
+ if (isMap(value)) {
1475
+ result = new Map();
1476
+ seen.set(value, result);
1477
+ value.forEach(function (item, key) {
1478
+ result.set(deepClone(key, seen), deepClone(item, seen));
1479
+ });
1480
+ return result
1481
+ }
1482
+
1483
+ if (isSet(value)) {
1484
+ result = new Set();
1485
+ seen.set(value, result);
1486
+ value.forEach(function (item) {
1487
+ result.add(deepClone(item, seen));
1488
+ });
1489
+ return result
1490
+ }
1491
+
1492
+ if (Array.isArray(value)) {
1493
+ result = [];
1494
+ seen.set(value, result);
1495
+ for (let i = 0; i < value.length; i++) {
1496
+ result[i] = deepClone(value[i], seen);
1497
+ }
1498
+ return result
1499
+ }
1500
+
1501
+ if (isPlainObject(value)) {
1502
+ result = Object.create(Object.getPrototypeOf(value));
1503
+ seen.set(value, result);
1504
+ Object.keys(value).forEach(function (key) {
1505
+ result[key] = deepClone(value[key], seen);
1506
+ });
1507
+ return result
1508
+ }
1509
+
1510
+ return value
1511
+ }
1512
+
1513
+ /**
1514
+ * Object 深比较
1515
+ */
1516
+
1517
+ function compareValue$1(a, b, pairs) {
1518
+ if (Object.is(a, b)) return true
1519
+
1520
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false
1521
+
1522
+ for (let i = 0; i < pairs.length; i++) {
1523
+ if (pairs[i][0] === a && pairs[i][1] === b) return true
1524
+ }
1525
+ pairs.push([a, b]);
1526
+
1527
+ if (isDate(a) || isDate(b)) {
1528
+ return isDate(a) && isDate(b) && a.getTime() === b.getTime()
1529
+ }
1530
+
1531
+ if (isRegExp(a) || isRegExp(b)) {
1532
+ return isRegExp(a) && isRegExp(b) && a.toString() === b.toString()
1533
+ }
1534
+
1535
+ if (isMap(a) || isMap(b)) {
1536
+ if (!isMap(a) || !isMap(b) || a.size !== b.size) return false
1537
+ let result = true;
1538
+ a.forEach(function (value, key) {
1539
+ if (!b.has(key) || !compareValue$1(value, b.get(key), pairs)) result = false;
1540
+ });
1541
+ return result
1542
+ }
1543
+
1544
+ if (isSet(a) || isSet(b)) {
1545
+ if (!isSet(a) || !isSet(b) || a.size !== b.size) return false
1546
+ let result = true;
1547
+ a.forEach(function (value) {
1548
+ if (!b.has(value)) result = false;
1549
+ });
1550
+ return result
1551
+ }
1552
+
1553
+ if (Array.isArray(a) !== Array.isArray(b)) return false
1554
+
1555
+ let keysA = Object.keys(a);
1556
+ let keysB = Object.keys(b);
1557
+
1558
+ if (keysA.length !== keysB.length) return false
1559
+
1560
+ for (let i = 0; i < keysA.length; i++) {
1561
+ if (!Object.prototype.hasOwnProperty.call(b, keysA[i])) return false
1562
+ if (!compareValue$1(a[keysA[i]], b[keysA[i]], pairs)) return false
1563
+ }
1564
+
1565
+ return true
1566
+ }
1567
+
1568
+ /**
1569
+ * 深比较
1570
+ */
1571
+ function equal(a, b) {
1572
+ return compareValue$1(a, b, [])
1573
+ }
1574
+
1575
+ /**
1576
+ * Object 深合并
1577
+ */
1578
+
1579
+ function mergeTwo(target, source, options) {
1580
+ Object.keys(source).forEach(function (key) {
1581
+ let sourceValue = source[key];
1582
+ let targetValue = target[key];
1583
+
1584
+ if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {
1585
+ target[key] = mergeTwo(deepClone(targetValue), sourceValue, options);
1586
+ } else if (Array.isArray(sourceValue) && Array.isArray(targetValue) && options.array === "concat") {
1587
+ target[key] = targetValue.concat(deepClone(sourceValue));
1588
+ } else {
1589
+ target[key] = deepClone(sourceValue);
1590
+ }
1591
+ });
1592
+
1593
+ return target
1594
+ }
1595
+
1596
+ /**
1597
+ * 深合并,返回合并后的新对象
1598
+ *
1599
+ * @param {object} target 目标对象
1600
+ * @param {object} source 来源对象
1601
+ * @param {object} options
1602
+ * @param {string} options.array 数组合并策略:replace(默认)或 concat
1603
+ */
1604
+ function deepMerge(target, source, options) {
1605
+ options = options || {};
1606
+ return mergeTwo(deepClone(target === undefined ? {} : target), source || {}, options)
1607
+ }
1608
+
1609
+ /**
1610
+ * Object 字段筛选
1611
+ */
1612
+
1613
+ /**
1614
+ * 只保留指定键
1615
+ */
1616
+ function pick(target, keys) {
1617
+ keys = Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments, 1);
1618
+ let result = {};
1619
+
1620
+ keys.forEach(function (key) {
1621
+ if (target !== null && target !== undefined && key in Object(target)) {
1622
+ result[key] = target[key];
1623
+ }
1624
+ });
1625
+
1626
+ return result
1627
+ }
1628
+
1629
+ /**
1630
+ * 排除指定键
1631
+ */
1632
+ function omit(target, keys) {
1633
+ keys = Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments, 1);
1634
+ let result = {};
1635
+ let excluded = keys.map(String);
1636
+
1637
+ Object.keys(Object(target)).forEach(function (key) {
1638
+ if (excluded.indexOf(key) === -1) result[key] = target[key];
1639
+ });
1640
+
1641
+ return result
1642
+ }
1643
+
1644
+ /**
1645
+ * Object 对外入口
1646
+ */
1647
+
1648
+ const ObjectUtil = {
1649
+ deepClone: deepClone,
1650
+ deepMerge: deepMerge,
1651
+ get: get,
1652
+ set: set,
1653
+ toPath: toPath,
1654
+ pick: pick,
1655
+ omit: omit,
1656
+ isEmpty: isEmpty,
1657
+ isPlainObject: isPlainObject,
1658
+ equal: equal
1659
+ };
1660
+
1661
+ /**
1662
+ * Array 内部工具
1663
+ */
1664
+
1665
+ /**
1666
+ * Array:数组处理
1667
+ * 全部返回新数组,不修改入参
1668
+ */
1669
+
1670
+ function toIteratee(iteratee) {
1671
+ if (typeof iteratee === "function") return iteratee
1672
+ if (typeof iteratee === "string" || typeof iteratee === "number") {
1673
+ return function (item) {
1674
+ return item === null || item === undefined ? undefined : item[iteratee]
1675
+ }
1676
+ }
1677
+ return function (item) {
1678
+ return item
1679
+ }
1680
+ }
1681
+
1682
+ /**
1683
+ * Array 分组
1684
+ */
1685
+
1686
+ /**
1687
+ * 分组,返回以分组键为属性的普通对象
1688
+ */
1689
+ function groupBy(list, iteratee) {
1690
+ let fn = toIteratee(iteratee);
1691
+ let result = {};
1692
+
1693
+ list.forEach(function (item) {
1694
+ let key = fn(item);
1695
+ if (!Object.prototype.hasOwnProperty.call(result, key)) result[key] = [];
1696
+ result[key].push(item);
1697
+ });
1698
+
1699
+ return result
1700
+ }
1701
+
1702
+ function normalizeKey(key) {
1703
+ if (typeof key === "function") return { fn: key, desc: false }
1704
+
1705
+ if (Array.isArray(key)) {
1706
+ return { fn: toIteratee(key[0]), desc: String(key[1]).toLowerCase() === "desc" }
1707
+ }
1708
+
1709
+ let str = String(key);
1710
+ if (str.charAt(0) === "-") {
1711
+ return { fn: toIteratee(str.substring(1)), desc: true }
1712
+ }
1713
+
1714
+ return { fn: toIteratee(str), desc: false }
1715
+ }
1716
+
1717
+ /**
1718
+ * Array 结构处理
1719
+ */
1720
+
1721
+ /**
1722
+ * 拍平数组
1723
+ *
1724
+ * @param {number} depth 拍平深度,默认 Infinity
1725
+ */
1726
+ function flatten(list, depth) {
1727
+ depth = depth === undefined ? Infinity : depth;
1728
+
1729
+ let result = [];
1730
+ list.forEach(function (item) {
1731
+ if (Array.isArray(item) && depth > 0) {
1732
+ result = result.concat(flatten(item, depth - 1));
1733
+ } else {
1734
+ result.push(item);
1735
+ }
1736
+ });
1737
+
1738
+ return result
1739
+ }
1740
+
1741
+ /**
1742
+ * 按长度切分
1743
+ */
1744
+ function chunk(list, size) {
1745
+ if (!(size > 0)) throw new TypeError("chunk 的 size 必须大于 0")
1746
+
1747
+ let result = [];
1748
+ for (let i = 0; i < list.length; i += size) {
1749
+ result.push(list.slice(i, i + size));
1750
+ }
1751
+
1752
+ return result
1753
+ }
1754
+
1755
+ /**
1756
+ * 去掉 falsey 值(false、0、""、null、undefined、NaN)
1757
+ */
1758
+ function compact(list) {
1759
+ return list.filter(Boolean)
1760
+ }
1761
+
1762
+ /**
1763
+ * 随机打乱(Fisher-Yates)
1764
+ */
1765
+ function shuffle(list) {
1766
+ let result = list.slice();
1767
+ for (let i = result.length - 1; i > 0; i--) {
1768
+ let index = Math.floor(Math.random() * (i + 1));
1769
+ let temp = result[i];
1770
+ result[i] = result[index];
1771
+ result[index] = temp;
1772
+ }
1773
+ return result
1774
+ }
1775
+
1776
+ /**
1777
+ * 生成数字序列,左闭右开
1778
+ */
1779
+ function range(start, end, step) {
1780
+ if (end === undefined) {
1781
+ end = start;
1782
+ start = 0;
1783
+ }
1784
+ step = step === undefined ? (start <= end ? 1 : -1) : step;
1785
+ if (step === 0) throw new TypeError("range 的 step 不能为 0")
1786
+
1787
+ let result = [];
1788
+ if (step > 0) {
1789
+ for (let i = start; i < end; i += step) result.push(i);
1790
+ } else {
1791
+ for (let i = start; i > end; i += step) result.push(i);
1792
+ }
1793
+
1794
+ return result
1795
+ }
1796
+
1797
+ /**
1798
+ * Array 排序
1799
+ */
1800
+
1801
+ function compareValue(a, b) {
1802
+ let aEmpty = a === null || a === undefined;
1803
+ let bEmpty = b === null || b === undefined;
1804
+
1805
+ if (aEmpty && bEmpty) return 0
1806
+ if (aEmpty) return 1 // 空值统一排后面
1807
+ if (bEmpty) return -1
1808
+
1809
+ if (a instanceof Date) a = a.getTime();
1810
+ if (b instanceof Date) b = b.getTime();
1811
+
1812
+ if (typeof a === "number" && typeof b === "number") return a - b
1813
+
1814
+ a = String(a);
1815
+ b = String(b);
1816
+
1817
+ return a < b ? -1 : (a > b ? 1 : 0)
1818
+ }
1819
+
1820
+ /**
1821
+ * 多字段排序,返回新数组
1822
+ *
1823
+ * @param {Array} keys 排序键,字符串("-" 前缀表示倒序)、函数,或 [键, "desc"]
1824
+ */
1825
+ function sortBy(list, keys) {
1826
+ let rules = (Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments, 1)).map(normalizeKey);
1827
+
1828
+ return list.slice().sort(function (a, b) {
1829
+ for (let i = 0; i < rules.length; i++) {
1830
+ let result = compareValue(rules[i].fn(a), rules[i].fn(b));
1831
+ if (result !== 0) return rules[i].desc ? -result : result
1832
+ }
1833
+ return 0
1834
+ })
1835
+ }
1836
+
1837
+ /**
1838
+ * Array 去重
1839
+ */
1840
+
1841
+ /**
1842
+ * 去重,使用 SameValueZero 语义(NaN 会被正确去重,对象按引用比较)
1843
+ */
1844
+ function unique(list) {
1845
+ return Array.from(new Set(list))
1846
+ }
1847
+
1848
+ /**
1849
+ * 按字段或函数去重,保留第一次出现的元素
1850
+ */
1851
+ function uniqueBy(list, iteratee) {
1852
+ let fn = toIteratee(iteratee);
1853
+ let seen = new Set();
1854
+ let result = [];
1855
+
1856
+ list.forEach(function (item) {
1857
+ let key = fn(item);
1858
+ if (!seen.has(key)) {
1859
+ seen.add(key);
1860
+ result.push(item);
1861
+ }
1862
+ });
1863
+
1864
+ return result
1865
+ }
1866
+
1867
+ /**
1868
+ * Array 对外入口
1869
+ */
1870
+
1871
+ const ArrayUtil = {
1872
+ unique: unique,
1873
+ uniqueBy: uniqueBy,
1874
+ groupBy: groupBy,
1875
+ sortBy: sortBy,
1876
+ flatten: flatten,
1877
+ chunk: chunk,
1878
+ compact: compact,
1879
+ shuffle: shuffle,
1880
+ range: range
1881
+ };
1882
+
1883
+ /**
1884
+ * Query 编解码与内部工具
1885
+ */
1886
+
1887
+ /**
1888
+ * Query:URL 查询参数与地址解析
1889
+ */
1890
+
1891
+ function decode(value) {
1892
+ let str = String(value).replace(/\+/g, " ");
1893
+ try {
1894
+ return decodeURIComponent(str)
1895
+ } catch (error) {
1896
+ return str // 非法转义时保留原样,不抛错
1897
+ }
1898
+ }
1899
+
1900
+ function encode(value) {
1901
+ return encodeURIComponent(String(value)).replace(/%5B/g, "[").replace(/%5D/g, "]")
1902
+ }
1903
+
1904
+ function buildPath(key) {
1905
+ let arrayFlag = /\[\]$/.test(key);
1906
+ let base = arrayFlag ? key.substring(0, key.length - 2) : key;
1907
+ let tokens = base.split(/\[|\]/).filter(function (token) {
1908
+ return token !== ""
1909
+ });
1910
+
1911
+ return { tokens: tokens, arrayFlag: arrayFlag }
1912
+ }
1913
+
1914
+ function assign(target, tokens, value, arrayFlag) {
1915
+ let current = target;
1916
+
1917
+ for (let i = 0; i < tokens.length - 1; i++) {
1918
+ let key = tokens[i];
1919
+ if (typeof current[key] !== "object" || current[key] === null) {
1920
+ current[key] = /^\d+$/.test(tokens[i + 1]) ? [] : {};
1921
+ }
1922
+ current = current[key];
1923
+ }
1924
+
1925
+ let last = tokens[tokens.length - 1];
1926
+
1927
+ if (arrayFlag) {
1928
+ if (!Array.isArray(current[last])) current[last] = [];
1929
+ current[last].push(value);
1930
+ return
1931
+ }
1932
+
1933
+ if (current[last] === undefined) {
1934
+ current[last] = value;
1935
+ } else if (Array.isArray(current[last])) {
1936
+ current[last].push(value);
1937
+ } else {
1938
+ current[last] = [current[last], value];
1939
+ }
1940
+ }
1941
+
1942
+ /**
1943
+ * Query 查询串解析
1944
+ */
1945
+
1946
+ /**
1947
+ * 解析查询字符串,支持 a=1&a=2、a[]=1、a[b]=1 三种写法
1948
+ *
1949
+ * @param {string} query 可以带 ? 前缀,也可以直接是完整 URL
1950
+ */
1951
+ function parseQuery(query) {
1952
+ let result = {};
1953
+ let str = String(query === undefined || query === null ? "" : query);
1954
+
1955
+ let questionIndex = str.indexOf("?");
1956
+ if (questionIndex !== -1) str = str.substring(questionIndex + 1);
1957
+
1958
+ let hashIndex = str.indexOf("#");
1959
+ if (hashIndex !== -1) str = str.substring(0, hashIndex);
1960
+
1961
+ if (!str) return result
1962
+
1963
+ str.split("&").forEach(function (pair) {
1964
+ if (!pair) return
1965
+
1966
+ let equalIndex = pair.indexOf("=");
1967
+ let rawKey = equalIndex === -1 ? pair : pair.substring(0, equalIndex);
1968
+ let rawValue = equalIndex === -1 ? "" : pair.substring(equalIndex + 1);
1969
+
1970
+ let key = decode(rawKey);
1971
+ if (!key) return
1972
+
1973
+ let path = buildPath(key);
1974
+ if (!path.tokens.length) return
1975
+
1976
+ assign(result, path.tokens, decode(rawValue), path.arrayFlag);
1977
+ });
1978
+
1979
+ return result
1980
+ }
1981
+
1982
+ /**
1983
+ * Query 查询串序列化
1984
+ */
1985
+
1986
+ /**
1987
+ * 把对象序列化成查询字符串,与 parseQuery 可逆
1988
+ */
1989
+ function stringifyQuery(target) {
1990
+ let parts = [];
1991
+
1992
+ function walk(value, key) {
1993
+ if (value === undefined) return
1994
+
1995
+ if (value === null) {
1996
+ parts.push(encode(key) + "=");
1997
+ return
1998
+ }
1999
+
2000
+ if (Array.isArray(value)) {
2001
+ value.forEach(function (item) {
2002
+ if (item !== undefined) walk(item, key);
2003
+ });
2004
+ return
2005
+ }
2006
+
2007
+ if (typeof value === "object" && !(value instanceof Date)) {
2008
+ Object.keys(value).forEach(function (childKey) {
2009
+ walk(value[childKey], key + "[" + childKey + "]");
2010
+ });
2011
+ return
2012
+ }
2013
+
2014
+ parts.push(encode(key) + "=" + encode(value));
2015
+ }
2016
+
2017
+ if (target && typeof target === "object") {
2018
+ Object.keys(target).forEach(function (key) {
2019
+ walk(target[key], key);
2020
+ });
2021
+ }
2022
+
2023
+ return parts.join("&")
2024
+ }
2025
+
2026
+ /**
2027
+ * Query URL 解析
2028
+ */
2029
+
2030
+ /**
2031
+ * 解析 URL,返回协议、主机、端口、路径、查询串、hash 与查询参数对象
2032
+ */
2033
+ function parseUrl(url) {
2034
+ let matched = /^([a-zA-Z][a-zA-Z0-9+.\-]*:)?(?:\/\/([^/?#]*))?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(String(url));
2035
+
2036
+ if (!matched) throw new TypeError("非法的 URL:" + url)
2037
+
2038
+ let protocol = matched[1] ? matched[1].substring(0, matched[1].length - 1).toLowerCase() : "";
2039
+ let authority = matched[2] || "";
2040
+
2041
+ let username = "";
2042
+ let password = "";
2043
+ let atIndex = authority.lastIndexOf("@");
2044
+ if (atIndex !== -1) {
2045
+ let userinfo = authority.substring(0, atIndex);
2046
+ authority = authority.substring(atIndex + 1);
2047
+
2048
+ let colonIndex = userinfo.indexOf(":");
2049
+ if (colonIndex === -1) {
2050
+ username = userinfo;
2051
+ } else {
2052
+ username = userinfo.substring(0, colonIndex);
2053
+ password = userinfo.substring(colonIndex + 1);
2054
+ }
2055
+ }
2056
+
2057
+ let hostname = authority;
2058
+ let port = "";
2059
+
2060
+ let portIndex = authority.lastIndexOf(":");
2061
+ if (portIndex !== -1 && portIndex > authority.lastIndexOf("]")) {
2062
+ hostname = authority.substring(0, portIndex);
2063
+ port = authority.substring(portIndex + 1);
2064
+ }
2065
+
2066
+ let query = matched[4] ? matched[4].substring(1) : "";
2067
+ let hash = matched[5] ? matched[5].substring(1) : "";
2068
+
2069
+ let result = {
2070
+ protocol: protocol,
2071
+ host: authority,
2072
+ hostname: hostname,
2073
+ port: port,
2074
+ username: username,
2075
+ password: password,
2076
+ path: matched[3] || "",
2077
+ query: query,
2078
+ hash: hash
2079
+ };
2080
+
2081
+ Object.defineProperty(result, "params", {
2082
+ value: parseQuery(query),
2083
+ enumerable: false
2084
+ });
2085
+
2086
+ return result
2087
+ }
2088
+
2089
+ /**
2090
+ * Query 对外入口
2091
+ */
2092
+
2093
+ const QueryUtil = {
2094
+ parseQuery: parseQuery,
2095
+ stringifyQuery: stringifyQuery,
2096
+ parseUrl: parseUrl
2097
+ };
2098
+
2099
+ /**
2100
+ * Id 随机源
2101
+ */
2102
+
2103
+ /**
2104
+ * Id:随机标识生成
2105
+ * 优先使用 crypto.getRandomValues,环境不支持时退回 Math.random(安全性较弱,仅适合展示类场景)
2106
+ */
2107
+
2108
+ const DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";
2109
+
2110
+ function getCrypto() {
2111
+ if (typeof globalThis !== "undefined" && globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
2112
+ return globalThis.crypto
2113
+ }
2114
+ return null
2115
+ }
2116
+
2117
+ function randomBytes(size) {
2118
+ let bytes = new Array(size);
2119
+ let cryptoObj = getCrypto();
2120
+
2121
+ if (cryptoObj) {
2122
+ let array = new Uint8Array(size);
2123
+ cryptoObj.getRandomValues(array);
2124
+ for (let i = 0; i < size; i++) bytes[i] = array[i];
2125
+ } else {
2126
+ for (let i = 0; i < size; i++) bytes[i] = Math.floor(Math.random() * 256);
2127
+ }
2128
+
2129
+ return bytes
2130
+ }
2131
+
2132
+ // 是否为加密安全随机源
2133
+
2134
+ function isSecure() {
2135
+ return getCrypto() !== null
2136
+ }
2137
+
2138
+ /**
2139
+ * Id 短 ID
2140
+ */
2141
+
2142
+ /**
2143
+ * 生成短 ID,默认 21 位、64 个字符的字母表
2144
+ */
2145
+ function nanoid(size, alphabet) {
2146
+ size = size === undefined ? 21 : size;
2147
+ alphabet = alphabet || DEFAULT_ALPHABET;
2148
+
2149
+ if (!(size > 0)) throw new TypeError("nanoid 的 size 必须大于 0")
2150
+ if (alphabet.length < 2) throw new TypeError("nanoid 的 alphabet 至少需要 2 个字符")
2151
+
2152
+ let bytes = randomBytes(size);
2153
+ let result = "";
2154
+
2155
+ for (let i = 0; i < size; i++) {
2156
+ result += alphabet.charAt(bytes[i] % alphabet.length);
2157
+ }
2158
+
2159
+ return result
2160
+ }
2161
+
2162
+ /**
2163
+ * Id 随机数与随机串
2164
+ */
2165
+
2166
+ /**
2167
+ * 生成 [min, max] 之间的随机整数(含两端)
2168
+ */
2169
+ function randomInt(min, max) {
2170
+ if (max === undefined) {
2171
+ max = min;
2172
+ min = 0;
2173
+ }
2174
+
2175
+ min = Math.ceil(min);
2176
+ max = Math.floor(max);
2177
+
2178
+ if (max < min) throw new TypeError("randomInt 的 max 不能小于 min")
2179
+
2180
+ return min + Math.floor(Math.random() * (max - min + 1))
2181
+ }
2182
+
2183
+ /**
2184
+ * 生成随机字符串
2185
+ */
2186
+ function randomString(size, alphabet) {
2187
+ size = size === undefined ? 8 : size;
2188
+ alphabet = alphabet || DEFAULT_ALPHABET;
2189
+
2190
+ if (!(size > 0)) throw new TypeError("randomString 的 size 必须大于 0")
2191
+
2192
+ let bytes = randomBytes(size);
2193
+ let result = "";
2194
+
2195
+ for (let i = 0; i < size; i++) {
2196
+ result += alphabet.charAt(bytes[i] % alphabet.length);
2197
+ }
2198
+
2199
+ return result
2200
+ }
2201
+
2202
+ /**
2203
+ * Id UUID
2204
+ */
2205
+
2206
+ /**
2207
+ * UUID v4
2208
+ */
2209
+ function uuid() {
2210
+ let bytes = randomBytes(16);
2211
+
2212
+ bytes[6] = (bytes[6] & 0x0f) | 0x40; // 版本号 4
2213
+ bytes[8] = (bytes[8] & 0x3f) | 0x80; // 变体位 10
2214
+
2215
+ let hex = bytes.map(function (byte) {
2216
+ return (byte + 0x100).toString(16).substring(1)
2217
+ }).join("");
2218
+
2219
+ return hex.substring(0, 8) + "-" + hex.substring(8, 12) + "-" + hex.substring(12, 16)
2220
+ + "-" + hex.substring(16, 20) + "-" + hex.substring(20)
2221
+ }
2222
+
2223
+ /**
2224
+ * Id 对外入口
2225
+ */
2226
+
2227
+ const IdUtil = {
2228
+ uuid: uuid,
2229
+ nanoid: nanoid,
2230
+ randomInt: randomInt,
2231
+ randomString: randomString,
2232
+ isSecure: isSecure
2233
+ };
2234
+
2235
+ /**
2236
+ * Color 内部工具
2237
+ */
2238
+
2239
+ /**
2240
+ * Color:颜色换算与调色
2241
+ * 输入输出统一使用 #rrggbb(必要时带 alpha),内部按 0-255 / 0-360 计算
2242
+ */
2243
+
2244
+ function clamp(value, min, max) {
2245
+ return value < min ? min : (value > max ? max : value)
2246
+ }
2247
+
2248
+ function pad2(value) {
2249
+ let str = Math.round(clamp(value, 0, 255)).toString(16);
2250
+ return str.length === 1 ? "0" + str : str
2251
+ }
2252
+
2253
+ function normalizeHex(hex) {
2254
+ let str = String(hex === undefined || hex === null ? "" : hex).trim().replace(/^#/, "");
2255
+
2256
+ if (/^[0-9a-fA-F]{3}$/.test(str)) {
2257
+ str = str.split("").map(function (char) {
2258
+ return char + char
2259
+ }).join("");
2260
+ }
2261
+
2262
+ if (/^[0-9a-fA-F]{4}$/.test(str)) {
2263
+ str = str.split("").map(function (char) {
2264
+ return char + char
2265
+ }).join("");
2266
+ }
2267
+
2268
+ if (!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(str)) {
2269
+ throw new TypeError("非法的颜色值:" + hex)
2270
+ }
2271
+
2272
+ return "#" + str.toLowerCase()
2273
+ }
2274
+
2275
+ /**
2276
+ * Color 格式互转
2277
+ */
2278
+
2279
+ /**
2280
+ * #rrggbb / #rgb / #rrggbbaa 转 { r, g, b, a }
2281
+ */
2282
+ function hex2rgb(hex) {
2283
+ let str = normalizeHex(hex).substring(1);
2284
+
2285
+ let result = {
2286
+ r: parseInt(str.substring(0, 2), 16),
2287
+ g: parseInt(str.substring(2, 4), 16),
2288
+ b: parseInt(str.substring(4, 6), 16),
2289
+ a: 1
2290
+ };
2291
+
2292
+ if (str.length === 8) {
2293
+ result.a = Math.round(parseInt(str.substring(6, 8), 16) / 255 * 100) / 100;
2294
+ }
2295
+
2296
+ return result
2297
+ }
2298
+
2299
+ /**
2300
+ * { r, g, b, a } 转 #rrggbb,alpha 小于 1 时输出 #rrggbbaa
2301
+ */
2302
+ function rgb2hex(rgb) {
2303
+ if (!rgb || typeof rgb !== "object") throw new TypeError("rgb2hex 需要一个 { r, g, b } 对象")
2304
+
2305
+ let alpha = rgb.a === undefined ? 1 : clamp(rgb.a, 0, 1);
2306
+ let hex = "#" + pad2(rgb.r) + pad2(rgb.g) + pad2(rgb.b);
2307
+
2308
+ return alpha < 1 ? hex + pad2(alpha * 255) : hex
2309
+ }
2310
+
2311
+ /**
2312
+ * { r, g, b } 转 { h, s, l }
2313
+ */
2314
+ function rgb2hsl(rgb) {
2315
+ let r = clamp(rgb.r, 0, 255) / 255;
2316
+ let g = clamp(rgb.g, 0, 255) / 255;
2317
+ let b = clamp(rgb.b, 0, 255) / 255;
2318
+
2319
+ let max = Math.max(r, g, b);
2320
+ let min = Math.min(r, g, b);
2321
+ let delta = max - min;
2322
+ let l = (max + min) / 2;
2323
+
2324
+ let h = 0;
2325
+ let s = 0;
2326
+
2327
+ if (delta !== 0) {
2328
+ s = delta / (1 - Math.abs(2 * l - 1));
2329
+
2330
+ switch (max) {
2331
+ case r: h = ((g - b) / delta) % 6; break
2332
+ case g: h = (b - r) / delta + 2; break
2333
+ default: h = (r - g) / delta + 4;
2334
+ }
2335
+
2336
+ h *= 60;
2337
+ if (h < 0) h += 360;
2338
+ }
2339
+
2340
+ return {
2341
+ h: Math.round(h * 100) / 100,
2342
+ s: Math.round(s * 10000) / 100,
2343
+ l: Math.round(l * 10000) / 100
2344
+ }
2345
+ }
2346
+
2347
+ /**
2348
+ * { h, s, l } 转 { r, g, b },h 单位是度,s/l 单位是百分比
2349
+ */
2350
+ function hsl2rgb(hsl) {
2351
+ let h = ((hsl.h % 360) + 360) % 360;
2352
+ let s = clamp(hsl.s, 0, 100) / 100;
2353
+ let l = clamp(hsl.l, 0, 100) / 100;
2354
+
2355
+ let c = (1 - Math.abs(2 * l - 1)) * s;
2356
+ let x = c * (1 - Math.abs((h / 60) % 2 - 1));
2357
+ let m = l - c / 2;
2358
+
2359
+ let rgb;
2360
+
2361
+ if (h < 60) rgb = [c, x, 0];
2362
+ else if (h < 120) rgb = [x, c, 0];
2363
+ else if (h < 180) rgb = [0, c, x];
2364
+ else if (h < 240) rgb = [0, x, c];
2365
+ else if (h < 300) rgb = [x, 0, c];
2366
+ else rgb = [c, 0, x];
2367
+
2368
+ return {
2369
+ r: Math.round((rgb[0] + m) * 255),
2370
+ g: Math.round((rgb[1] + m) * 255),
2371
+ b: Math.round((rgb[2] + m) * 255)
2372
+ }
2373
+ }
2374
+
2375
+ /**
2376
+ * Color 调色
2377
+ */
2378
+
2379
+ /**
2380
+ * 按权重混合两个颜色
2381
+ *
2382
+ * @param {number} weight 第二个颜色的权重,0-1
2383
+ */
2384
+ function mix(color1, color2, weight) {
2385
+ weight = weight === undefined ? 0.5 : clamp(weight, 0, 1);
2386
+
2387
+ let a = hex2rgb(color1);
2388
+ let b = hex2rgb(color2);
2389
+
2390
+ return rgb2hex({
2391
+ r: Math.round(a.r * (1 - weight) + b.r * weight),
2392
+ g: Math.round(a.g * (1 - weight) + b.g * weight),
2393
+ b: Math.round(a.b * (1 - weight) + b.b * weight)
2394
+ })
2395
+ }
2396
+
2397
+ /**
2398
+ * 变亮:与白色混合
2399
+ *
2400
+ * @param {number} amount 0-1
2401
+ */
2402
+ function lighten(color, amount) {
2403
+ return mix(color, "#ffffff", amount === undefined ? 0.3 : amount)
2404
+ }
2405
+
2406
+ /**
2407
+ * 变暗:与黑色混合
2408
+ *
2409
+ * @param {number} amount 0-1
2410
+ */
2411
+ function darken(color, amount) {
2412
+ return mix(color, "#000000", amount === undefined ? 0.3 : amount)
2413
+ }
2414
+
2415
+ /**
2416
+ * 根据背景色返回可读的前景色(纯黑或纯白)
2417
+ */
2418
+ function contrast(color) {
2419
+ let rgb = hex2rgb(color);
2420
+
2421
+ // W3C 相对亮度
2422
+ let channel = function (value) {
2423
+ let ratio = value / 255;
2424
+ return ratio <= 0.03928 ? ratio / 12.92 : Math.pow((ratio + 0.055) / 1.055, 2.4)
2425
+ };
2426
+
2427
+ let luminance = 0.2126 * channel(rgb.r) + 0.7152 * channel(rgb.g) + 0.0722 * channel(rgb.b);
2428
+
2429
+ return luminance > 0.5 ? "#000000" : "#ffffff"
2430
+ }
2431
+
2432
+ /**
2433
+ * 转成 rgba() 字符串
2434
+ */
2435
+ function toRgba(color, alpha) {
2436
+ let rgb = hex2rgb(color);
2437
+ alpha = alpha === undefined ? 1 : clamp(alpha, 0, 1);
2438
+ return "rgba(" + rgb.r + ", " + rgb.g + ", " + rgb.b + ", " + alpha + ")"
2439
+ }
2440
+
2441
+ /**
2442
+ * Color 对外入口
2443
+ */
2444
+
2445
+ const ColorUtil = {
2446
+ hex2rgb: hex2rgb,
2447
+ rgb2hex: rgb2hex,
2448
+ rgb2hsl: rgb2hsl,
2449
+ hsl2rgb: hsl2rgb,
2450
+ mix: mix,
2451
+ lighten: lighten,
2452
+ darken: darken,
2453
+ contrast: contrast,
2454
+ toRgba: toRgba
2455
+ };
2456
+
2457
+ /**
2458
+ * Cache 存储驱动
2459
+ */
2460
+
2461
+ /**
2462
+ * Cache:带过期时间的键值存储
2463
+ * 默认优先用 localStorage,其次 sessionStorage,都没有(如 Node 环境)时退回内存
2464
+ */
2465
+
2466
+ function createStorageDriver(storage) {
2467
+ return {
2468
+ getItem: function (key) {
2469
+ return storage.getItem(key)
2470
+ },
2471
+ setItem: function (key, value) {
2472
+ storage.setItem(key, value);
2473
+ },
2474
+ removeItem: function (key) {
2475
+ storage.removeItem(key);
2476
+ },
2477
+ keys: function () {
2478
+ let result = [];
2479
+ for (let i = 0; i < storage.length; i++) result.push(storage.key(i));
2480
+ return result
2481
+ }
2482
+ }
2483
+ }
2484
+
2485
+ function createMemoryDriver() {
2486
+ let store = new Map();
2487
+
2488
+ return {
2489
+ getItem: function (key) {
2490
+ return store.has(key) ? store.get(key) : null
2491
+ },
2492
+ setItem: function (key, value) {
2493
+ store.set(key, value);
2494
+ },
2495
+ removeItem: function (key) {
2496
+ store.delete(key);
2497
+ },
2498
+ keys: function () {
2499
+ return Array.from(store.keys())
2500
+ }
2501
+ }
2502
+ }
2503
+
2504
+ function tryStorage(name) {
2505
+ try {
2506
+ if (typeof globalThis !== "undefined" && globalThis[name]) {
2507
+ let storage = globalThis[name];
2508
+ let probe = "__corejs_probe__";
2509
+ storage.setItem(probe, "1");
2510
+ storage.removeItem(probe);
2511
+ return createStorageDriver(storage)
2512
+ }
2513
+ } catch (error) {
2514
+ // 隐私模式等场景写入会抛错,直接降级
2515
+ }
2516
+ return null
2517
+ }
2518
+
2519
+ function resolveDriver(driver) {
2520
+ if (driver && typeof driver === "object"
2521
+ && typeof driver.getItem === "function"
2522
+ && typeof driver.setItem === "function"
2523
+ && typeof driver.removeItem === "function") {
2524
+ return driver
2525
+ }
2526
+
2527
+ if (driver === "memory") return createMemoryDriver()
2528
+
2529
+ if (driver === "local") {
2530
+ let local = tryStorage("localStorage");
2531
+ if (local) return local
2532
+ return createMemoryDriver()
2533
+ }
2534
+
2535
+ if (driver === "session") {
2536
+ let session = tryStorage("sessionStorage");
2537
+ if (session) return session
2538
+ return createMemoryDriver()
2539
+ }
2540
+
2541
+ return tryStorage("localStorage") || tryStorage("sessionStorage") || createMemoryDriver()
2542
+ }
2543
+
2544
+ /**
2545
+ * Cache 过期时间
2546
+ */
2547
+
2548
+ function toExpire(expire) {
2549
+ if (expire === undefined || expire === null || expire === 0) return 0
2550
+
2551
+ if (expire instanceof Date) {
2552
+ let stamp = expire.getTime();
2553
+ if (!isFinite(stamp)) throw new TypeError("非法的过期时间")
2554
+ return stamp
2555
+ }
2556
+
2557
+ if (typeof expire === "number") {
2558
+ if (!isFinite(expire) || expire < 0) throw new TypeError("非法的过期时间:" + expire)
2559
+ // 小于 1e11 的按“相对毫秒”处理,否则按“绝对时间戳”处理
2560
+ return expire < 100000000000 ? Date.now() + expire : expire
2561
+ }
2562
+
2563
+ throw new TypeError("非法的过期时间:" + expire)
2564
+ }
2565
+
2566
+ /**
2567
+ * Cache 读写
2568
+ */
2569
+
2570
+ function useStore(Cache) {
2571
+ /**
2572
+ * 写入缓存
2573
+ *
2574
+ * @param {string} key 键
2575
+ * @param {*} value 值,会被 JSON 序列化
2576
+ * @param {number|Date} expire 过期时间:毫秒(相对)或时间戳 / Date(绝对),不传表示不过期
2577
+ */
2578
+ Cache.prototype.set = function (key, value, expire) {
2579
+ let data = {
2580
+ v: value,
2581
+ e: toExpire(expire)
2582
+ };
2583
+
2584
+ this._driver.setItem(this._key(key), JSON.stringify(data));
2585
+ return this
2586
+ };
2587
+
2588
+ /**
2589
+ * 读取缓存,过期或不存在时返回 defaultValue
2590
+ */
2591
+ Cache.prototype.get = function (key, defaultValue) {
2592
+ let str = this._driver.getItem(this._key(key));
2593
+ if (str === null || str === undefined) return defaultValue
2594
+
2595
+ let data;
2596
+ try {
2597
+ data = JSON.parse(str);
2598
+ } catch (error) {
2599
+ this.remove(key);
2600
+ return defaultValue
2601
+ }
2602
+
2603
+ if (!data || typeof data !== "object" || !Object.prototype.hasOwnProperty.call(data, "v")) {
2604
+ this.remove(key);
2605
+ return defaultValue
2606
+ }
2607
+
2608
+ if (data.e && data.e <= Date.now()) {
2609
+ this.remove(key);
2610
+ return defaultValue
2611
+ }
2612
+
2613
+ return data.v
2614
+ };
2615
+
2616
+ Cache.prototype.has = function (key) {
2617
+ let str = this._driver.getItem(this._key(key));
2618
+ if (str === null || str === undefined) return false
2619
+
2620
+ let data;
2621
+ try {
2622
+ data = JSON.parse(str);
2623
+ } catch (error) {
2624
+ this.remove(key);
2625
+ return false
2626
+ }
2627
+
2628
+ if (!data || typeof data !== "object") {
2629
+ this.remove(key);
2630
+ return false
2631
+ }
2632
+
2633
+ if (data.e && data.e <= Date.now()) {
2634
+ this.remove(key);
2635
+ return false
2636
+ }
2637
+
2638
+ return true
2639
+ };
2640
+
2641
+ Cache.prototype.remove = function (key) {
2642
+ this._driver.removeItem(this._key(key));
2643
+ return this
2644
+ };
2645
+
2646
+ /**
2647
+ * 当前命名空间下仍然有效的键
2648
+ */
2649
+ Cache.prototype.keys = function () {
2650
+ let prefix = this.namespace + ":";
2651
+ let result = [];
2652
+
2653
+ this._driver.keys().forEach(function (fullKey) {
2654
+ if (fullKey.indexOf(prefix) === 0) result.push(fullKey.substring(prefix.length));
2655
+ });
2656
+
2657
+ let self = this;
2658
+ return result.filter(function (key) {
2659
+ return self.has(key)
2660
+ })
2661
+ };
2662
+
2663
+ Cache.prototype.size = function () {
2664
+ return this.keys().length
2665
+ };
2666
+
2667
+ /**
2668
+ * 清空当前命名空间(不会影响其它命名空间的数据)
2669
+ */
2670
+ Cache.prototype.clear = function () {
2671
+ let self = this;
2672
+ this.keys().forEach(function (key) {
2673
+ self.remove(key);
2674
+ });
2675
+ return this
2676
+ };
2677
+ }
2678
+
2679
+ /**
2680
+ * Cache:带过期时间的键值存储
2681
+ * 默认优先用 localStorage,其次 sessionStorage,都没有(如 Node 环境)时退回内存
2682
+ */
2683
+
2684
+ /**
2685
+ * @param {string} namespace 命名空间,默认 corejs
2686
+ * @param {object} options
2687
+ * @param {string|object} options.driver local、session、memory,或自定义 { getItem, setItem, removeItem }
2688
+ */
2689
+ function Cache(namespace, options) {
2690
+ if (typeof namespace === "object" && namespace !== null && options === undefined) {
2691
+ options = namespace;
2692
+ namespace = undefined;
2693
+ }
2694
+
2695
+ options = options || {};
2696
+
2697
+ this.namespace = namespace || "corejs";
2698
+
2699
+ Object.defineProperty(this, "_driver", {
2700
+ value: resolveDriver(options.driver),
2701
+ enumerable: false
2702
+ });
2703
+ }
2704
+
2705
+ Cache.prototype._key = function (key) {
2706
+ return this.namespace + ":" + key
2707
+ };
2708
+
2709
+ useStore(Cache);
2710
+
2711
+ export { ArrayUtil as Array, Cache, ColorUtil as Color, Digits, IdUtil as Id, ObjectUtil as Object, QueryUtil as Query, StringUtil as String, Time, Valid as Validate };