@codady/utils 0.0.38 → 0.0.40

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 (58) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/utils.cjs.js +576 -24
  3. package/dist/utils.cjs.min.js +3 -3
  4. package/dist/utils.esm.js +576 -24
  5. package/dist/utils.esm.min.js +3 -3
  6. package/dist/utils.umd.js +576 -24
  7. package/dist/utils.umd.min.js +3 -3
  8. package/dist.zip +0 -0
  9. package/examples/ajax-download.html +94 -0
  10. package/examples/ajax-get.html +59 -0
  11. package/examples/ajax-hook.html +55 -0
  12. package/examples/ajax-method.html +36 -0
  13. package/examples/ajax-post.html +37 -0
  14. package/examples/ajax-signal.html +91 -0
  15. package/examples/ajax-timeout.html +85 -0
  16. package/examples/buildUrl.html +99 -0
  17. package/examples/getUrlHash.html +71 -0
  18. package/examples/stringToEncodings-collision-test-registry.html +117 -0
  19. package/examples/stringToEncodings-collision-test.html +71 -0
  20. package/examples/stringToEncodings.html +138 -0
  21. package/examples/unicodeToEncodings.html +195 -0
  22. package/modules.js +17 -1
  23. package/modules.ts +17 -1
  24. package/package.json +1 -1
  25. package/src/ajax.js +380 -0
  26. package/src/ajax.ts +470 -0
  27. package/src/buildUrl.js +64 -0
  28. package/src/buildUrl.ts +86 -0
  29. package/src/capitalize.js +19 -0
  30. package/src/capitalize.ts +20 -0
  31. package/src/cleanQueryString.js +19 -0
  32. package/src/cleanQueryString.ts +20 -0
  33. package/src/getBodyHTML.js +53 -0
  34. package/src/getBodyHTML.ts +61 -0
  35. package/src/getEl.js +1 -1
  36. package/src/getEl.ts +6 -5
  37. package/src/getEls.js +1 -1
  38. package/src/getEls.ts +5 -5
  39. package/src/getUrlHash.js +37 -0
  40. package/src/getUrlHash.ts +39 -0
  41. package/src/isEmpty.js +24 -23
  42. package/src/isEmpty.ts +26 -23
  43. package/src/sliceStrEnd.js +63 -0
  44. package/src/sliceStrEnd.ts +60 -0
  45. package/src/stringToEncodings.js +56 -0
  46. package/src/stringToEncodings.ts +110 -0
  47. package/src/unicodeToEncodings.js +51 -0
  48. package/src/unicodeToEncodings.ts +55 -0
  49. package/src/arrayMutableMethods - /345/211/257/346/234/254.js" +0 -5
  50. package/src/comma - /345/211/257/346/234/254.js" +0 -2
  51. package/src/deepCloneToJSON - /345/211/257/346/234/254.js" +0 -47
  52. package/src/deepMergeMaps - /345/211/257/346/234/254.js" +0 -78
  53. package/src/escapeHTML - /345/211/257/346/234/254.js" +0 -29
  54. package/src/getDataType - /345/211/257/346/234/254.js" +0 -38
  55. package/src/isEmpty - /345/211/257/346/234/254.js" +0 -45
  56. package/src/mapMutableMethods - /345/211/257/346/234/254.js" +0 -5
  57. package/src/setMutableMethods - /345/211/257/346/234/254.js" +0 -5
  58. package/src/wrapMap - /345/211/257/346/234/254.js" +0 -119
package/dist/utils.esm.js CHANGED
@@ -1,8 +1,8 @@
1
1
 
2
2
  /*!
3
- * @since Last modified: 2026-1-16 15:18:30
3
+ * @since Last modified: 2026-2-5 17:4:41
4
4
  * @name Utils for web front-end.
5
- * @version 0.0.38
5
+ * @version 0.0.40
6
6
  * @author AXUI development team <3217728223@qq.com>
7
7
  * @description This is a set of general-purpose JavaScript utility functions developed by the AXUI team. All functions are pure and do not involve CSS or other third-party libraries. They are suitable for any web front-end environment.
8
8
  * @see {@link https://www.axui.cn|Official website}
@@ -941,30 +941,31 @@ const isEmpty = (data) => {
941
941
  let type = getDataType(data), flag;
942
942
  if (!data) {
943
943
  //0,'',false,undefined,null
944
- flag = true;
944
+ return true;
945
945
  }
946
- else {
947
- //function(){}|()=>{}
948
- //[null]|[undefined]|['']|[""]
949
- //[]|{}
950
- //Symbol()|Symbol.for()
951
- //Set,Map
952
- //Date/Regex
953
- flag = (type === 'Object') ? (Object.keys(data).length === 0) :
954
- (type === 'Array') ? data.join('') === '' :
955
- (type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
956
- (type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
957
- (type === 'Set' || type === 'Map') ? data.size === 0 :
958
- type === 'Date' ? isNaN(data.getTime()) :
959
- type === 'RegExp' ? data.source === '' :
960
- type === 'ArrayBuffer' ? data.byteLength === 0 :
961
- (type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
962
- ('length' in data && typeof data.length === 'number') ? data.length === 0 :
963
- ('size' in data && typeof data.size === 'number') ? data.size === 0 :
964
- (type === 'Error' || data instanceof Error) ? data.message === '' :
965
- (type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
966
- false;
946
+ if (['String', 'Number', 'Boolean'].includes(type)) {
947
+ return false;
967
948
  }
949
+ //function(){}|()=>{}
950
+ //[null]|[undefined]|['']|[""]
951
+ //[]|{}
952
+ //Symbol()|Symbol.for()
953
+ //Set,Map
954
+ //Date/Regex
955
+ flag = (type === 'Object') ? (Object.keys(data).length === 0) :
956
+ (type === 'Array') ? data.join('') === '' :
957
+ (type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
958
+ (type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
959
+ (type === 'Set' || type === 'Map') ? data.size === 0 :
960
+ type === 'Date' ? isNaN(data.getTime()) :
961
+ type === 'RegExp' ? data.source === '' :
962
+ type === 'ArrayBuffer' ? data.byteLength === 0 :
963
+ (type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
964
+ ('length' in data && typeof data.length === 'number') ? data.length === 0 :
965
+ ('size' in data && typeof data.size === 'number') ? data.size === 0 :
966
+ (type === 'Error' || data instanceof Error) ? data.message === '' :
967
+ (type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
968
+ false;
968
969
  return flag;
969
970
  };
970
971
 
@@ -1338,6 +1339,549 @@ const decodeHtmlEntities = (text) => {
1338
1339
  return textArea.value; // Get the decoded string from the text area
1339
1340
  };
1340
1341
 
1342
+ const getBodyHTML = (htmlText, selector) => {
1343
+ // Return early if the input is not a valid string or doesn't look like HTML
1344
+ if (!htmlText || typeof htmlText !== 'string') {
1345
+ return '';
1346
+ }
1347
+ try {
1348
+
1349
+ const parser = new DOMParser(),
1350
+
1351
+ doc = parser.parseFromString(htmlText, 'text/html'),
1352
+
1353
+ bodyContent = doc.body.innerHTML;
1354
+ if (selector) {
1355
+ // Normalize hash: ensure it's a valid ID selector
1356
+ const targetEl = doc.querySelector(selector);
1357
+ if (targetEl) {
1358
+ return targetEl.innerHTML;
1359
+ }
1360
+ // If hash is provided but element not found, we fallback to body or warn
1361
+ console.warn(`Element with selector "${selector}" not found in the HTML.`);
1362
+ }
1363
+ return bodyContent ? bodyContent.trim() : htmlText;
1364
+ }
1365
+ catch (error) {
1366
+
1367
+ console.error("Failed to parse HTML content using DOMParser:", error);
1368
+ return htmlText;
1369
+ }
1370
+ };
1371
+
1372
+ const getUrlHash = (url) => {
1373
+ // Return empty if input is null, undefined, or not a string
1374
+ if (!url || typeof url !== 'string') {
1375
+ return '';
1376
+ }
1377
+ try {
1378
+
1379
+ const baseUrl = window?.location?.origin || 'https://www.axui.cn', urlObj = new URL(url, baseUrl);
1380
+ return urlObj.hash;
1381
+ }
1382
+ catch (error) {
1383
+
1384
+ return '';
1385
+ }
1386
+ };
1387
+
1388
+ const cleanQueryString = (data) => {
1389
+ return typeof data === 'string' && (data.startsWith('?') || data.startsWith('&'))
1390
+ ? data.slice(1) // Remove the leading '?' or '&'
1391
+ : data; // Return the string as-is if no leading character is present
1392
+ };
1393
+
1394
+ const buildUrl = ({ url, data, cacheBustKey = '_t', appendCacheBust = true }) => {
1395
+ // 1. Extract and remove the hash (e.g., /page#section -> hash="#section")
1396
+ const hashIndex = url.indexOf('#');
1397
+ let hash = '', pureUrl = url;
1398
+ // If a hash exists, separate it from the base URL
1399
+ if (hashIndex !== -1) {
1400
+ hash = url.slice(hashIndex);
1401
+ pureUrl = url.slice(0, hashIndex);
1402
+ }
1403
+ // 2. Use the URL object to handle the base URL and existing query parameters.
1404
+ // `window.location.origin` ensures the support for relative paths (e.g., '/api/list').
1405
+ const urlObj = new URL(pureUrl, window.location.origin);
1406
+ // 3. Append business data (query parameters) to the URL if data is not empty
1407
+ if (!isEmpty(data)) {
1408
+ let params, dataType = getDataType(data);
1409
+ // If the data is a URLSearchParams object, directly use it
1410
+ if (dataType === 'URLSearchParams') {
1411
+ params = data;
1412
+ }
1413
+ else if (dataType === 'object') {
1414
+ // If the data is an object, convert it to URLSearchParams
1415
+ params = new URLSearchParams(data);
1416
+ }
1417
+ else {
1418
+ // If the data is a string, clean it up (remove leading '?' or '&')
1419
+ params = new URLSearchParams(cleanQueryString(data));
1420
+ }
1421
+ // Append new parameters to the existing URL search parameters
1422
+ params.forEach((value, key) => {
1423
+ urlObj.searchParams.append(key, value);
1424
+ });
1425
+ }
1426
+ // 4. Optionally add the cache-busting parameter if the flag is set
1427
+ appendCacheBust && cacheBustKey && urlObj.searchParams.set(cacheBustKey, Date.now().toString());
1428
+ // 5. Return the final URL: base URL + query parameters + original hash (if any)
1429
+ return urlObj.toString() + hash;
1430
+ };
1431
+
1432
+ const capitalize = (str) => {
1433
+ // Check if the input string is empty or undefined
1434
+ if (!str)
1435
+ return str;
1436
+ // Capitalize the first letter and return the new string
1437
+ return str.charAt(0).toUpperCase() + str.slice(1);
1438
+ };
1439
+
1440
+ const ajax = (options) => {
1441
+ // Validation
1442
+ if (isEmpty(options)) {
1443
+ return Promise.reject(new Error('Options are required'));
1444
+ }
1445
+ if (!options.url || typeof options.url !== 'string') {
1446
+ return Promise.reject(new Error('URL is required and must be a string'));
1447
+ }
1448
+ // Default configuration
1449
+ const config = {
1450
+ url: '',
1451
+ method: 'POST',
1452
+ async: true,
1453
+ selector: '',
1454
+ data: null,
1455
+ timeout: 3600000,
1456
+ headers: {},
1457
+ responseType: '',
1458
+ catchError: false,
1459
+ signal: null,
1460
+ xhrFields: {},
1461
+ cacheBustKey: '_t',
1462
+ precision: 2,
1463
+ //
1464
+ onAbort: null,
1465
+ onTimeout: null,
1466
+ //
1467
+ onBeforeSend: null,
1468
+ //
1469
+ onCreated: null,
1470
+ onOpened: null,
1471
+ onHeadersReceived: null,
1472
+ onLoading: null,
1473
+ //
1474
+ onSuccess: null,
1475
+ onFailure: null,
1476
+ onInformation: null,
1477
+ onRedirection: null,
1478
+ onClientError: null,
1479
+ onServerError: null,
1480
+ onUnknownError: null,
1481
+ onError: null,
1482
+ onFinish: null,
1483
+ //
1484
+ onDownload: null,
1485
+ onUpload: null,
1486
+ onComplete: null,
1487
+ };
1488
+ //合并参数
1489
+ Object.assign(config, options);
1490
+ //
1491
+ const method = config.method.toUpperCase() || 'POST', methodsWithoutBody = ['GET', 'HEAD', 'TRACE'];
1492
+ //创建XMLHttpRequest
1493
+ let xhr = new XMLHttpRequest(),
1494
+ //设置发送数据和预设请求头
1495
+ requestData = null, headerContentType = config?.headers?.['Content-Type'] || config?.headers?.['content-type'], removeHeader = () => {
1496
+ if (headerContentType) {
1497
+ delete config.headers['Content-Type'];
1498
+ delete config.headers['content-type'];
1499
+ }
1500
+ };
1501
+ if (!isEmpty(config.data)) {
1502
+ let dataType = getDataType(config.data);
1503
+ if (dataType === 'FormData') {
1504
+ //如果是new FormData格式,直接相等
1505
+ requestData = config.data;
1506
+ // 不需要手动设置Content-Type,浏览器会自动设置
1507
+ //config.contType = 'multipart/form-data';
1508
+ removeHeader();
1509
+ }
1510
+ else if (dataType === 'Object') {
1511
+ //如果是对象格式{name:'',age:''}
1512
+ //并且此时已经设置了contType
1513
+ if (!headerContentType) {
1514
+ //如果未设置则默认设为如下contType
1515
+ //Content-Type=application/x-www-form-urlencoded
1516
+
1517
+ requestData = new URLSearchParams(config.data).toString();
1518
+ //URLSearchParams.toString => `a=1&b=3`
1519
+ //非get、head方法修正content-type
1520
+ if (!methodsWithoutBody.includes(method)) {
1521
+ config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
1522
+ }
1523
+ }
1524
+ else if (headerContentType?.includes('application/json')) {
1525
+ //Content-Type=application/json或contentType=application/json
1526
+ requestData = JSON.stringify(config.data);
1527
+ }
1528
+ else {
1529
+ requestData = config.data;
1530
+ }
1531
+ }
1532
+ else if (dataType === 'String') {
1533
+ //未设置或,已经设置了Content-Type=application/x-www-form-urlencoded
1534
+ if (!headerContentType || headerContentType.includes('urlencoded')) {
1535
+ //如果是name=''&age=''字符串
1536
+ //?name=''&age=''或&name=''&age=''统一去掉第一个&/?
1537
+ requestData = cleanQueryString(config.data.trim());
1538
+ //非get、head方法修正content-type
1539
+ if (!methodsWithoutBody.includes(method) && !headerContentType) {
1540
+ config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
1541
+ }
1542
+ }
1543
+ else {
1544
+ requestData = config.data;
1545
+ }
1546
+ }
1547
+ else {
1548
+ requestData = config.data;
1549
+ }
1550
+ }
1551
+ //设置超时时间
1552
+ xhr.timeout = config.timeout;
1553
+ // 响应类型
1554
+ if (config.responseType) {
1555
+ xhr.responseType = config.responseType;
1556
+ }
1557
+ //返回promise
1558
+ const result = new Promise((resolve, reject) => {
1559
+ //超时监听
1560
+ const timeoutHandler = () => {
1561
+ cleanup();
1562
+ let resp = { ...context, status: xhr.status, content: xhr.response, type: 'timeout' };
1563
+ //回调,status和content在此确认
1564
+ config?.onTimeout?.(resp);
1565
+ //reject只能接受一个参数
1566
+ config.catchError ? reject(resp) : resolve(resp);
1567
+ //超时也是不能获得数据的行为,定义为failure
1568
+ config?.onFailure?.(resp);
1569
+ //timeout会经过onreadystatechange,但是被及时的return了,所以这里多加一行
1570
+ config?.onFinish?.(resp);
1571
+ },
1572
+ //报错监听
1573
+ errorHandler = (resp) => {
1574
+ //这几个错误来自xhr.onreadystatechange
1575
+ if (resp.type === 'client-error') {
1576
+ config?.onClientError?.({ ...context });
1577
+ }
1578
+ else if (resp.type === 'server-error') {
1579
+ config?.onServerError?.({ ...context });
1580
+ }
1581
+ else if (resp.type === 'unknown-error') {
1582
+ config?.onUnknownError?.({ ...context });
1583
+ }
1584
+ //此外还会有xhr.onerror的错误,所以需要统一使用onError监听
1585
+ config?.onError?.(resp);
1586
+ //reject只能接受一个参数
1587
+ config.catchError ? reject(resp) : resolve(resp);
1588
+ },
1589
+ //取消监听
1590
+ abortHandler = () => {
1591
+ cleanup();
1592
+ const resp = { ...context, status: xhr.status, type: 'abort' };
1593
+ config.catchError ? reject(resp) : resolve(resp);
1594
+ //回调,status和content在此确认
1595
+ config?.onAbort?.(resp);
1596
+ //abort行为不会经过onreadystatechange,这里需要多这一行以表示xhr的完成(结束)
1597
+ config?.onFinish?.(resp);
1598
+ }, abortHandlerWithSignal = () => {
1599
+ //先中止请求,防止触发其他 readystate 事件
1600
+ xhr.abort();
1601
+ abortHandler();
1602
+ },
1603
+ //成功监听
1604
+ successHandler = (resp) => {
1605
+ //成功回调
1606
+ config?.onSuccess?.(resp);
1607
+ //resolve只能接受一个参数
1608
+ resolve(resp);
1609
+ },
1610
+ //统一处理abort
1611
+ cleanup = () => {
1612
+ // 如果使用了AbortSignal,则移除它的事件监听器
1613
+ config.signal && config.signal.removeEventListener('abort', abortHandlerWithSignal);
1614
+ // 移除各类事件监听器
1615
+ config.onError && xhr.removeEventListener('error', errorHandler);
1616
+ config.onTimeout && xhr.removeEventListener('timeout', timeoutHandler);
1617
+ // 解绑上传/下载进度事件
1618
+ config.onUpload && xhr.upload.removeEventListener('progress', uploadProgressHandler);
1619
+ config.onDownload && xhr.removeEventListener('progress', downloadProgressHandler);
1620
+ //销毁
1621
+ xhr.onreadystatechange = null;
1622
+ },
1623
+ // Context object to track state
1624
+ context = {
1625
+ //原始xhr
1626
+ xhr,
1627
+ //发送的数据
1628
+ data: requestData,
1629
+ //可取消的函数
1630
+ abort: abortHandler,
1631
+ //xhr.status
1632
+ status: '',
1633
+ //响应的内容
1634
+ content: null,
1635
+ //0~4阶段编号
1636
+ stage: 0,
1637
+ //阶段名称
1638
+ type: 'unset',
1639
+ //上传和下载进度
1640
+ progress: {}
1641
+ }, getProgressValues = (ratio) => {
1642
+ let text = (ratio * 100).toFixed(config.precision);
1643
+ return { percent: parseFloat(text), text };
1644
+ },
1645
+ //定义进度函数
1646
+ progressHandler = (name, data, callback) => {
1647
+ if (data.lengthComputable) {
1648
+ const resp = { ...context, status: xhr.status }, ratio = data.loaded / data.total, { percent, text } = getProgressValues(ratio);
1649
+ resp.progress = {
1650
+ name,
1651
+ loaded: data.loaded,
1652
+ total: data.total,
1653
+ timestamp: (new Date(data.timeStamp)).getTime(),
1654
+ ratio,
1655
+ percent,
1656
+ text,
1657
+ };
1658
+ callback?.(resp);
1659
+ if (ratio >= 1) {
1660
+ Object.assign(resp.progress, getProgressValues(1));
1661
+ config?.onComplete?.(resp);
1662
+ }
1663
+ }
1664
+ }, uploadProgressHandler = (data) => {
1665
+ progressHandler('upload', data, (resp) => config.onUpload(resp));
1666
+ }, downloadProgressHandler = (data) => {
1667
+ progressHandler('download', data, (resp) => config.onDownload(resp));
1668
+ };
1669
+ //使用AbortSignal
1670
+ if (config.signal) {
1671
+ if (config.signal.aborted)
1672
+ return abortHandlerWithSignal();
1673
+ config.signal.addEventListener('abort', abortHandlerWithSignal);
1674
+ }
1675
+ //监听上传进度
1676
+ config.onUpload && xhr.upload.addEventListener('progress', uploadProgressHandler);
1677
+ //监听下载进度
1678
+ config.onDownload && xhr.addEventListener('progress', downloadProgressHandler);
1679
+ // 事件监听器
1680
+ config.onError && xhr.addEventListener('error', errorHandler);
1681
+ config.onTimeout && xhr.addEventListener('timeout', timeoutHandler);
1682
+ config.onAbort && xhr.addEventListener('abort', abortHandler);
1683
+ // 手动触发 Created 状态
1684
+ config.onCreated?.({ ...context, type: 'created' });
1685
+ //状态判断
1686
+ xhr.onreadystatechange = function () {
1687
+ context.stage = xhr.readyState;
1688
+ context.status = xhr.status;
1689
+ const statusMap = { 1: 'opened', 2: 'headersReceived', 3: 'loading' };
1690
+ //0=created放在外侧确保能触发,如果放在.onreadystatechange可能触发不了
1691
+ if (xhr.readyState < 4) {
1692
+ if (!xhr.readyState)
1693
+ return;
1694
+ context.type = statusMap[xhr.readyState];
1695
+ config[`on${capitalize(context.type)}`]?.({ ...context });
1696
+ return;
1697
+ }
1698
+ //tiemeout事件也会执行这里,此时需要让它触发onTimeout事件
1699
+ //abort和timeout行为的status是0
1700
+ //不过abort行为不会执行到这里
1701
+ if (xhr.status === 0 && context.type !== 'abort') {
1702
+ return;
1703
+ }
1704
+ //已经请求成功,不会有timeout事件,也不需要abort了,所以移除abort事件
1705
+ cleanup();
1706
+ //根据状态码判断响应结果
1707
+ const isInformation = xhr.status >= 100 && xhr.status < 200, isSuccess = (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304, isRedirection = xhr.status >= 300 && xhr.status < 400, isClientError = xhr.status >= 400 && xhr.status < 500, isServerError = xhr.status >= 500 && xhr.status < 600;
1708
+ //已经获得返回数据
1709
+ if (isSuccess) {
1710
+ if (!config.responseType || xhr.responseType === 'text') {
1711
+ //可能返回字符串类型的对象,wordpress的REST API
1712
+ let trim = xhr.responseText.trim(), content = '';
1713
+ if ((trim.startsWith('[') && trim.endsWith(']')) || (trim.startsWith('{') && trim.endsWith('}'))) {
1714
+ //通过判断开头字符是{或[来确定异步页面是否是JSON内容,如果是则转成JSON对象
1715
+ try {
1716
+ content = JSON.parse(trim);
1717
+ }
1718
+ catch {
1719
+ console.warn('Malformed JSON detected, falling back to text.');
1720
+ content = xhr.responseText;
1721
+ }
1722
+ }
1723
+ else if (/(<\/html>|<\/body>)/i.test(trim)) {
1724
+ //请求了一个HTML页面
1725
+ //返回文本类型DOMstring
1726
+ let urlHash = getUrlHash(config.url);
1727
+ content = getBodyHTML(trim, config.selector || urlHash);
1728
+ }
1729
+ else {
1730
+ //普通文本,不做任何处理
1731
+ content = xhr.responseText;
1732
+ }
1733
+ //content=文本字符串/json
1734
+ context.content = content;
1735
+ }
1736
+ else {
1737
+ //content=json、blob、document、arraybuffer等类型,如果知道服务器返回的XML, xhr.responseType应该为document
1738
+ context.content = xhr.response;
1739
+ }
1740
+ context.type = 'success';
1741
+ successHandler({ ...context });
1742
+ }
1743
+ else {
1744
+ //失败回调
1745
+ context.content = xhr.response;
1746
+ context.type = isInformation ? 'infomation' : isRedirection ? 'redirection' : isClientError ? 'client-error' : isServerError ? 'server-error' : 'unknown-error';
1747
+ //
1748
+ if (isInformation) {
1749
+ config?.onInformation?.({ ...context });
1750
+ }
1751
+ else if (isRedirection) {
1752
+ config?.onRedirection?.({ ...context });
1753
+ }
1754
+ else {
1755
+ errorHandler({ ...context });
1756
+ }
1757
+ //
1758
+ config?.onFailure?.({ ...context });
1759
+ }
1760
+ config?.onFinish?.({ ...context });
1761
+ };
1762
+ //发送异步请求
1763
+ let openParams = [method, config.url, config.async];
1764
+ if (methodsWithoutBody.includes(method)) {
1765
+ // 拼接url => xxx.com?a=0&b=1#hello
1766
+ const url = buildUrl({
1767
+ url: config.url,
1768
+ data: requestData,
1769
+ cacheBustKey: config.cacheBustKey,
1770
+ appendCacheBust: true,
1771
+ });
1772
+ openParams = [method, url, config.async];
1773
+ }
1774
+ //设置xhr其他字段
1775
+ for (let k in config.xhrFields) {
1776
+ config.xhrFields.hasOwnProperty(k) && (xhr[k] = config.xhrFields[k]);
1777
+ }
1778
+ //与服务器建立连接
1779
+ xhr.open(...openParams);
1780
+ //有则设置,仅跳过空内容
1781
+ for (let k in config.headers) {
1782
+ config.headers.hasOwnProperty(k) && !isEmpty(config.headers[k]) && xhr.setRequestHeader(k, config.headers[k]);
1783
+ }
1784
+ config?.onBeforeSend?.(({ ...context, status: xhr.status, type: 'beforeSend' }));
1785
+ //发送请求,get和head不需要发送数据
1786
+ xhr.send(methodsWithoutBody.includes(method) ? null : (requestData || null));
1787
+ //open和send阶段已经是异步了,无法使用try+catch捕获错误
1788
+ });
1789
+ //绑定xhr和abort
1790
+ result.xhr = xhr;
1791
+ result.abort = () => xhr.abort();
1792
+ return result;
1793
+ };
1794
+ // Static Helper Methods
1795
+ //get、head、trace是不需要发送数据的,data将被转为url参数处理
1796
+ ['post', 'put', 'delete', 'patch', 'options', 'get', 'head', 'trace'].forEach(method => {
1797
+ ajax[method] = (url, data, options = { url: '' }) => ajax({ ...options, method, url, data });
1798
+ });
1799
+ ajax.all = (requests) => Promise.all(requests.map(ajax));
1800
+
1801
+ const stringToEncodings = (name, options = {}) => {
1802
+ // Default: Supplementary Private Use Area (Plane 15 and Plane 16)
1803
+ //1,114,110 places,5000 strings => 0 collision
1804
+ const start = options.start ?? 0xF0000, end = options.end ?? 0x10FFFD, range = BigInt(end - start + 1), registry = options.registryMap,
1805
+
1806
+ formatResult = (name, codePoint, hash, collision) => {
1807
+ const hex = codePoint.toString(16).toUpperCase();
1808
+ return {
1809
+ name,
1810
+ unicode: `U+${hex}`,
1811
+ htmlDec: `&#${codePoint};`,
1812
+ htmlHex: `&#x${hex};`,
1813
+ hex,
1814
+ codePoint,
1815
+ hash,
1816
+ collision,
1817
+ };
1818
+ };
1819
+ // -----------------------------
1820
+ // 1. Compute FNV-1a 64-bit hash
1821
+ // -----------------------------
1822
+ let hash = BigInt("0xcbf29ce484222325");
1823
+ const prime = BigInt("0x100000001b3");
1824
+ for (const ch of name) {
1825
+ hash ^= BigInt(ch.codePointAt(0));
1826
+ hash *= prime;
1827
+ }
1828
+ const hashHex = hash.toString(16).toUpperCase();
1829
+ // -----------------------------
1830
+ // 2. Stateless mode (no registry)
1831
+ // -----------------------------
1832
+ if (!registry) {
1833
+ const offset = Number(hash % range), codePoint = start + offset;
1834
+ return formatResult(name, codePoint, hashHex, false);
1835
+ }
1836
+ // -----------------------------
1837
+ // 3. Registry mode (0 collision)
1838
+ // -----------------------------
1839
+ // Already assigned → return stable mapping
1840
+ if (registry.has(name)) {
1841
+ return formatResult(name, registry.get(name), hashHex, false);
1842
+ }
1843
+ // Initial candidate from hash
1844
+ let offset = Number(hash % range), codePoint = start + offset, collision = false;
1845
+ const used = new Set(registry.values());
1846
+ // Linear probing to resolve collisions
1847
+ while (used.has(codePoint)) {
1848
+ collision = true;
1849
+ offset = (offset + 1) % Number(range);
1850
+ codePoint = start + offset;
1851
+ }
1852
+ // Commit allocation
1853
+ registry.set(name, codePoint);
1854
+ return formatResult(name, codePoint, hashHex, collision);
1855
+ };
1856
+
1857
+ const unicodeToEncodings = (input) => {
1858
+ let codePoint;
1859
+ if (typeof input === "number") {
1860
+ codePoint = input;
1861
+ }
1862
+ else {
1863
+ const cleaned = input.trim()
1864
+ .replace(/^U\+/i, "")
1865
+ .replace(/^0x/i, "");
1866
+ codePoint = /^[0-9A-F]+$/i.test(cleaned)
1867
+ ? parseInt(cleaned, 16)
1868
+ : parseInt(cleaned, 10);
1869
+ }
1870
+ // Validate parsed code point
1871
+ if (!Number.isFinite(codePoint)) {
1872
+ throw new Error("Invalid Unicode input");
1873
+ }
1874
+ // Convert code point to uppercase hexadecimal representation
1875
+ const hex = codePoint.toString(16).toUpperCase();
1876
+ return {
1877
+ unicode: `U+${hex}`,
1878
+ hex,
1879
+ codePoint,
1880
+ htmlDec: `&#${codePoint};`,
1881
+ htmlHex: `&#x${hex};`,
1882
+ };
1883
+ };
1884
+
1341
1885
  const utils = {
1342
1886
  //executeStr,
1343
1887
  getDataType,
@@ -1381,6 +1925,14 @@ const utils = {
1381
1925
  escapeHTML,
1382
1926
  toSingleLine,
1383
1927
  renderTpl,
1928
+ getBodyHTML,
1929
+ getUrlHash,
1930
+ buildUrl,
1931
+ ajax,
1932
+ capitalize,
1933
+ cleanQueryString,
1934
+ stringToEncodings,
1935
+ unicodeToEncodings,
1384
1936
  };
1385
1937
 
1386
1938
  export { utils as default };