@rzl-zone/utils-js 3.12.0 → 3.12.1-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{LICENSE.md → LICENSE} +3 -3
- package/README.md +69 -96
- package/dist/.references/index.d.cts +25 -0
- package/dist/.references/index.d.ts +25 -0
- package/dist/assertIsArray-DJXkjHZs.cjs +26 -0
- package/dist/assertIsArray-DJXkjHZs.cjs.map +1 -0
- package/dist/assertIsArray-bTA3XLjq.js +20 -0
- package/dist/assertIsArray-bTA3XLjq.js.map +1 -0
- package/dist/assertIsBoolean-C8WEXVr2.cjs +1283 -0
- package/dist/assertIsBoolean-C8WEXVr2.cjs.map +1 -0
- package/dist/assertIsBoolean-DR1SaXPD.js +1073 -0
- package/dist/assertIsBoolean-DR1SaXPD.js.map +1 -0
- package/dist/assertIsString-BiHQSrB2.cjs +26 -0
- package/dist/assertIsString-BiHQSrB2.cjs.map +1 -0
- package/dist/assertIsString-CEB07_83.js +20 -0
- package/dist/assertIsString-CEB07_83.js.map +1 -0
- package/dist/assertions/index.cjs +37 -40
- package/dist/assertions/index.cjs.map +1 -0
- package/dist/assertions/index.d.cts +12 -0
- package/dist/assertions/index.d.ts +10 -824
- package/dist/assertions/index.js +30 -13
- package/dist/assertions/index.js.map +1 -0
- package/dist/conversions/index.cjs +34 -103
- package/dist/conversions/index.d.cts +12 -0
- package/dist/conversions/index.d.ts +10 -1791
- package/dist/conversions/index.js +14 -24
- package/dist/conversions-BNIh_tCH.js +380 -0
- package/dist/conversions-BNIh_tCH.js.map +1 -0
- package/dist/conversions-D_Kh0a_C.cjs +446 -0
- package/dist/conversions-D_Kh0a_C.cjs.map +1 -0
- package/dist/events/index.cjs +55 -31
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.d.cts +176 -0
- package/dist/events/index.d.ts +164 -166
- package/dist/events/index.js +50 -12
- package/dist/events/index.js.map +1 -0
- package/dist/formatEnvPort-B3OLxQk9.cjs +171 -0
- package/dist/formatEnvPort-B3OLxQk9.cjs.map +1 -0
- package/dist/formatEnvPort-ByFVLjSV.js +159 -0
- package/dist/formatEnvPort-ByFVLjSV.js.map +1 -0
- package/dist/formatters/index.cjs +21 -61
- package/dist/formatters/index.d.cts +12 -0
- package/dist/formatters/index.d.ts +10 -2152
- package/dist/formatters/index.js +10 -18
- package/dist/formatters--1m_vpE8.js +369 -0
- package/dist/formatters--1m_vpE8.js.map +1 -0
- package/dist/formatters-Cbij0XLU.cjs +429 -0
- package/dist/formatters-Cbij0XLU.cjs.map +1 -0
- package/dist/generators/index.cjs +165 -41
- package/dist/generators/index.cjs.map +1 -0
- package/dist/generators/index.d.cts +12 -0
- package/dist/generators/index.d.ts +10 -338
- package/dist/generators/index.js +158 -14
- package/dist/generators/index.js.map +1 -0
- package/dist/index-59zbLcPr.d.ts +340 -0
- package/dist/index-B6tawc8L.d.cts +1716 -0
- package/dist/index-C267akkJ.d.ts +2158 -0
- package/dist/index-CeBC2Vvl.d.cts +2361 -0
- package/dist/index-CgRDTI6f.d.ts +822 -0
- package/dist/index-CoiUBVmr.d.ts +720 -0
- package/dist/index-D4fcasfZ.d.cts +720 -0
- package/dist/index-DDrSQKIc.d.ts +1716 -0
- package/dist/index-DsGxO31H.d.cts +765 -0
- package/dist/index-Hg1qJkjl.d.ts +765 -0
- package/dist/index-Qm3iFwd0.d.cts +2158 -0
- package/dist/index-UPp94Agr.d.ts +2361 -0
- package/dist/index-gBA_8SuF.d.cts +340 -0
- package/dist/index-jyDqzicx.d.cts +822 -0
- package/dist/isBigInt-C4krUeAw.cjs +20 -0
- package/dist/isBigInt-C4krUeAw.cjs.map +1 -0
- package/dist/isBigInt-DKe0M6hp.js +14 -0
- package/dist/isBigInt-DKe0M6hp.js.map +1 -0
- package/dist/isEmptyObject-DCipFwxJ.js +25 -0
- package/dist/isEmptyObject-DCipFwxJ.js.map +1 -0
- package/dist/isEmptyObject-ZkSwRC_D.cjs +37 -0
- package/dist/isEmptyObject-ZkSwRC_D.cjs.map +1 -0
- package/dist/isEmptyString-BXzKAC2j.js +15 -0
- package/dist/isEmptyString-BXzKAC2j.js.map +1 -0
- package/dist/isEmptyString-UiiUsSQj.cjs +21 -0
- package/dist/isEmptyString-UiiUsSQj.cjs.map +1 -0
- package/dist/isEmptyValue-BQzcjVaL.cjs +30 -0
- package/dist/isEmptyValue-BQzcjVaL.cjs.map +1 -0
- package/dist/isEmptyValue-jqOr7OHD.js +24 -0
- package/dist/isEmptyValue-jqOr7OHD.js.map +1 -0
- package/dist/isEqual-BX49cF9m.js +87 -0
- package/dist/isEqual-BX49cF9m.js.map +1 -0
- package/dist/isEqual-BvumA3RA.cjs +111 -0
- package/dist/isEqual-BvumA3RA.cjs.map +1 -0
- package/dist/isFinite-BCnaDpod.js +15 -0
- package/dist/isFinite-BCnaDpod.js.map +1 -0
- package/dist/isFinite-D24ZaE6c.cjs +21 -0
- package/dist/isFinite-D24ZaE6c.cjs.map +1 -0
- package/dist/isInteger-Caeuz0rB.cjs +20 -0
- package/dist/isInteger-Caeuz0rB.cjs.map +1 -0
- package/dist/isInteger-naMbJsxJ.js +14 -0
- package/dist/isInteger-naMbJsxJ.js.map +1 -0
- package/dist/isPlainObject-BF-2-phb.d.cts +339 -0
- package/dist/isPlainObject-DxNDL8XU.d.ts +339 -0
- package/dist/isServer-BJHVnixd.cjs +20 -0
- package/dist/isServer-BJHVnixd.cjs.map +1 -0
- package/dist/isServer-Da3o3XSs.js +14 -0
- package/dist/isServer-Da3o3XSs.js.map +1 -0
- package/dist/isTypedArray-DuNA8tK6.js +31 -0
- package/dist/isTypedArray-DuNA8tK6.js.map +1 -0
- package/dist/isTypedArray-TJptiw2b.cjs +43 -0
- package/dist/isTypedArray-TJptiw2b.cjs.map +1 -0
- package/dist/isURL-C-kSk6KJ.js +14 -0
- package/dist/isURL-C-kSk6KJ.js.map +1 -0
- package/dist/isURL-DeUPO_oR.cjs +20 -0
- package/dist/isURL-DeUPO_oR.cjs.map +1 -0
- package/dist/isValidDomain-BB9IGhJs.cjs +1845 -0
- package/dist/isValidDomain-BB9IGhJs.cjs.map +1 -0
- package/dist/isValidDomain-DoE98yhJ.js +1827 -0
- package/dist/isValidDomain-DoE98yhJ.js.map +1 -0
- package/dist/next/index.cjs +119 -214
- package/dist/next/index.cjs.map +1 -0
- package/dist/next/index.d.cts +220 -0
- package/dist/next/index.d.ts +203 -214
- package/dist/next/index.js +117 -212
- package/dist/next/index.js.map +1 -0
- package/dist/next/server/index.cjs +25 -40
- package/dist/next/server/index.cjs.map +1 -0
- package/dist/next/server/index.d.cts +39 -0
- package/dist/next/server/index.d.ts +34 -35
- package/dist/next/server/index.js +23 -38
- package/dist/next/server/index.js.map +1 -0
- package/dist/noop-B13_ii35.cjs +18 -0
- package/dist/noop-B13_ii35.cjs.map +1 -0
- package/dist/noop-ubqAIbHD.js +12 -0
- package/dist/noop-ubqAIbHD.js.map +1 -0
- package/dist/normalizeSpaces-Bg2IZW7W.js +23 -0
- package/dist/normalizeSpaces-Bg2IZW7W.js.map +1 -0
- package/dist/normalizeSpaces-ZXnR4Qzp.cjs +29 -0
- package/dist/normalizeSpaces-ZXnR4Qzp.cjs.map +1 -0
- package/dist/normalizeString-BDdkaXui.js +15 -0
- package/dist/normalizeString-BDdkaXui.js.map +1 -0
- package/dist/normalizeString-BE6ELqEb.cjs +21 -0
- package/dist/normalizeString-BE6ELqEb.cjs.map +1 -0
- package/dist/operations/index.cjs +65 -32
- package/dist/operations/index.cjs.map +1 -0
- package/dist/operations/index.d.cts +139 -0
- package/dist/operations/index.d.ts +129 -134
- package/dist/operations/index.js +61 -17
- package/dist/operations/index.js.map +1 -0
- package/dist/parsers/index.cjs +12 -19
- package/dist/parsers/index.d.cts +239 -0
- package/dist/parsers/index.d.ts +234 -235
- package/dist/parsers/index.js +10 -12
- package/dist/parsers-BSBPgvsq.js +643 -0
- package/dist/parsers-BSBPgvsq.js.map +1 -0
- package/dist/parsers-OqDeffqc.cjs +649 -0
- package/dist/parsers-OqDeffqc.cjs.map +1 -0
- package/dist/parsing-Cao8b358.js +50 -0
- package/dist/parsing-Cao8b358.js.map +1 -0
- package/dist/parsing-DOGSCH6N.cjs +56 -0
- package/dist/parsing-DOGSCH6N.cjs.map +1 -0
- package/dist/predicates/index.cjs +91 -296
- package/dist/predicates/index.d.cts +13 -0
- package/dist/predicates/index.d.ts +12 -2482
- package/dist/predicates/index.js +23 -25
- package/dist/predicates-Bj6meyXV.js +256 -0
- package/dist/predicates-Bj6meyXV.js.map +1 -0
- package/dist/predicates-D0ubqgqy.cjs +412 -0
- package/dist/predicates-D0ubqgqy.cjs.map +1 -0
- package/dist/promises/index.cjs +76 -24
- package/dist/promises/index.cjs.map +1 -0
- package/dist/promises/index.d.cts +123 -0
- package/dist/promises/index.d.ts +116 -119
- package/dist/promises/index.js +73 -13
- package/dist/promises/index.js.map +1 -0
- package/dist/punyCode-8SrbMWfM.js +179 -0
- package/dist/punyCode-8SrbMWfM.js.map +1 -0
- package/dist/punyCode-D-Qu6nj6.cjs +185 -0
- package/dist/punyCode-D-Qu6nj6.cjs.map +1 -0
- package/dist/removeSpaces-Bmc5DX4F.js +19 -0
- package/dist/removeSpaces-Bmc5DX4F.js.map +1 -0
- package/dist/removeSpaces-CWIvhZHg.cjs +25 -0
- package/dist/removeSpaces-CWIvhZHg.cjs.map +1 -0
- package/dist/rzl-utils.global.js +20 -9
- package/dist/safeJsonParse-BP38mwlj.js +184 -0
- package/dist/safeJsonParse-BP38mwlj.js.map +1 -0
- package/dist/safeJsonParse-Sms2CJf4.cjs +208 -0
- package/dist/safeJsonParse-Sms2CJf4.cjs.map +1 -0
- package/dist/safeStableStringify-CJtP89qn.cjs +106 -0
- package/dist/safeStableStringify-CJtP89qn.cjs.map +1 -0
- package/dist/safeStableStringify-CXOZ9Ub8.js +88 -0
- package/dist/safeStableStringify-CXOZ9Ub8.js.map +1 -0
- package/dist/strings/index.cjs +79 -81
- package/dist/strings/index.cjs.map +1 -0
- package/dist/strings/index.d.cts +12 -0
- package/dist/strings/index.d.ts +10 -775
- package/dist/strings/index.js +62 -14
- package/dist/strings/index.js.map +1 -0
- package/dist/tailwind/index.cjs +19 -47
- package/dist/tailwind/index.d.cts +12 -0
- package/dist/tailwind/index.d.ts +11 -712
- package/dist/tailwind/index.js +10 -12
- package/dist/tailwind-B2ssevxq.js +199 -0
- package/dist/tailwind-B2ssevxq.js.map +1 -0
- package/dist/tailwind-CHIx9uxu.cjs +247 -0
- package/dist/tailwind-CHIx9uxu.cjs.map +1 -0
- package/dist/toStringArrayUnRecursive-C4zYCja7.cjs +51 -0
- package/dist/toStringArrayUnRecursive-C4zYCja7.cjs.map +1 -0
- package/dist/toStringArrayUnRecursive-DJGtPsFb.js +39 -0
- package/dist/toStringArrayUnRecursive-DJGtPsFb.js.map +1 -0
- package/dist/urls/index.cjs +130 -57
- package/dist/urls/index.cjs.map +1 -0
- package/dist/urls/index.d.cts +737 -0
- package/dist/urls/index.d.ts +699 -708
- package/dist/urls/index.js +122 -26
- package/dist/urls/index.js.map +1 -0
- package/package.json +203 -194
- package/dist/chunk-2AFQ33D3.cjs +0 -64
- package/dist/chunk-2CYDJVGM.js +0 -246
- package/dist/chunk-2MW4JDQ2.cjs +0 -598
- package/dist/chunk-2VTDXC3N.cjs +0 -1825
- package/dist/chunk-44XX2P34.js +0 -209
- package/dist/chunk-4YLBKLGS.cjs +0 -18
- package/dist/chunk-566CXQW7.cjs +0 -560
- package/dist/chunk-57EPKYID.cjs +0 -397
- package/dist/chunk-5MGEC3YG.js +0 -63
- package/dist/chunk-6EF52423.cjs +0 -249
- package/dist/chunk-6SCOKU3S.js +0 -109
- package/dist/chunk-6VUXD3CF.js +0 -119
- package/dist/chunk-7B76BSNK.cjs +0 -118
- package/dist/chunk-7Y6I2DSU.cjs +0 -101
- package/dist/chunk-A7S7E2EE.cjs +0 -308
- package/dist/chunk-AJZ6PMMZ.js +0 -16
- package/dist/chunk-AXGBL2IO.cjs +0 -251
- package/dist/chunk-B4TC6FBV.cjs +0 -678
- package/dist/chunk-BAV5T2E3.cjs +0 -15
- package/dist/chunk-BKIJBNIE.js +0 -21
- package/dist/chunk-BNIMTFK5.js +0 -59
- package/dist/chunk-BXW7YXB7.js +0 -1823
- package/dist/chunk-CFYZC4S6.js +0 -53
- package/dist/chunk-CSG4SCL3.js +0 -1587
- package/dist/chunk-CWQW7AKK.js +0 -676
- package/dist/chunk-DVMHRLKP.cjs +0 -16
- package/dist/chunk-EN7LVZBZ.js +0 -548
- package/dist/chunk-EV4Y7HCY.cjs +0 -26
- package/dist/chunk-F66VDYIZ.cjs +0 -18
- package/dist/chunk-FLJX37EL.cjs +0 -30
- package/dist/chunk-GKC3UDMC.cjs +0 -1623
- package/dist/chunk-H65I3GRZ.cjs +0 -106
- package/dist/chunk-HHYWB7VZ.js +0 -24
- package/dist/chunk-HNGGISFL.cjs +0 -65
- package/dist/chunk-HNSQAVSZ.cjs +0 -35
- package/dist/chunk-HSP6IWZK.js +0 -17
- package/dist/chunk-IDZS7J6T.js +0 -242
- package/dist/chunk-JS6R55VL.js +0 -302
- package/dist/chunk-JZVT5FK7.js +0 -232
- package/dist/chunk-KHO2SBNA.cjs +0 -16
- package/dist/chunk-KIDJCMNJ.js +0 -33
- package/dist/chunk-KOLEURVT.cjs +0 -38
- package/dist/chunk-L4V53MQK.cjs +0 -269
- package/dist/chunk-L5RDAVVH.js +0 -14
- package/dist/chunk-NODTV4F3.js +0 -16
- package/dist/chunk-NYK5K3V2.cjs +0 -211
- package/dist/chunk-ODUO3RTL.cjs +0 -113
- package/dist/chunk-ONZFBJVW.js +0 -14
- package/dist/chunk-PFXCTE37.js +0 -28
- package/dist/chunk-PPST7QAQ.js +0 -587
- package/dist/chunk-Q5IMYDFL.cjs +0 -33
- package/dist/chunk-QFFBIOJ4.js +0 -31
- package/dist/chunk-QNKGP5DY.js +0 -14
- package/dist/chunk-RRQHMOPE.cjs +0 -19
- package/dist/chunk-RU5OSRBU.js +0 -95
- package/dist/chunk-SDMPEJ4F.js +0 -35
- package/dist/chunk-SYNL5IKP.js +0 -115
- package/dist/chunk-TCDOWZQE.js +0 -16
- package/dist/chunk-TQPGXGKB.cjs +0 -123
- package/dist/chunk-TULOI4GL.js +0 -370
- package/dist/chunk-UBHCP4N5.cjs +0 -36
- package/dist/chunk-UCHF3M34.cjs +0 -56
- package/dist/chunk-UDA26MCU.cjs +0 -16
- package/dist/chunk-V3C4FYZL.cjs +0 -18
- package/dist/chunk-VAAHZFBF.js +0 -32
- package/dist/chunk-VJDDGRIK.cjs +0 -16
- package/dist/chunk-WVSPXFTY.js +0 -14
- package/dist/chunk-WYP76WXB.js +0 -101
- package/dist/chunk-YDE4ZBB7.cjs +0 -237
- package/dist/chunk-YKQEOO7C.cjs +0 -23
- package/dist/chunk-YSZC56SZ.js +0 -264
- package/dist/chunk-YWHHVDT4.js +0 -13
- package/dist/index.d.ts +0 -24
- package/dist/isPlainObject-DTJVV2Kf.d.ts +0 -536
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* ========================================================================
|
|
3
|
+
* @rzl-zone/utils-js
|
|
4
|
+
* ------------------------------------------------------------------------
|
|
5
|
+
* Version: `3.12.1-beta.1`
|
|
6
|
+
* Author: `Rizalvin Dwiky <rizalvindwiky@gmail.com>`
|
|
7
|
+
* Repository: `https://github.com/rzl-zone/rzl-zone/tree/main/packages/utils-js`
|
|
8
|
+
* ========================================================================
|
|
9
|
+
*/
|
|
10
|
+
"use strict";
|
|
11
|
+
const require_assertIsBoolean = require('./assertIsBoolean-C8WEXVr2.cjs');
|
|
12
|
+
const require_isBigInt = require('./isBigInt-C4krUeAw.cjs');
|
|
13
|
+
function isMap(value) {
|
|
14
|
+
return Object.prototype.toString.call(value) === "[object Map]" || value instanceof Map;
|
|
15
|
+
}
|
|
16
|
+
const isDate = (value, options = {}) => {
|
|
17
|
+
require_assertIsBoolean.assertIsPlainObject(options, { message: ({ currentType, validType }) => `Second parameter (\`options\`) must be of type \`${validType}\`, but received: \`${currentType}\`.` });
|
|
18
|
+
const skipInvalidDate = require_assertIsBoolean.isPlainObject(options) && require_assertIsBoolean.isBoolean(options.skipInvalidDate) ? options.skipInvalidDate : false;
|
|
19
|
+
const instanceDate = value instanceof Date;
|
|
20
|
+
if (skipInvalidDate) return instanceDate;
|
|
21
|
+
return instanceDate && !require_assertIsBoolean.isNaN(value.getTime());
|
|
22
|
+
};
|
|
23
|
+
const safeStableStringify = (value, options = {}) => {
|
|
24
|
+
require_assertIsBoolean.assertIsPlainObject(options, { message: ({ currentType, validType }) => `Second parameter (\`options\`) must be of type \`${validType}\`, but received: \`${currentType}\`.` });
|
|
25
|
+
const pretty = require_assertIsBoolean.hasOwnProp(options, "pretty") ? options.pretty : false;
|
|
26
|
+
const sortKeys = require_assertIsBoolean.hasOwnProp(options, "sortKeys") ? options.sortKeys : true;
|
|
27
|
+
const sortArray = require_assertIsBoolean.hasOwnProp(options, "sortArray") ? options.sortArray : false;
|
|
28
|
+
const keepUndefined = require_assertIsBoolean.hasOwnProp(options, "keepUndefined") ? options.keepUndefined : false;
|
|
29
|
+
if (!require_assertIsBoolean.isBoolean(sortKeys) || !require_assertIsBoolean.isBoolean(sortArray) || !require_assertIsBoolean.isBoolean(pretty) || !require_assertIsBoolean.isBoolean(keepUndefined)) throw new TypeError(`Parameters \`sortKeys\`, \`sortArray\`, \`keepUndefined\` and \`pretty\` property of the \`options\` (second parameter) must be of type \`boolean\`, but received: "['sortKeys': \`${require_assertIsBoolean.getPreciseType(sortKeys)}\`, 'sortArray': \`${require_assertIsBoolean.getPreciseType(sortArray)}\`, 'keepUndefined': \`${require_assertIsBoolean.getPreciseType(keepUndefined)}\`, 'pretty': \`${require_assertIsBoolean.getPreciseType(pretty)}\`]".`);
|
|
30
|
+
if (require_assertIsBoolean.isUndefined(value)) return keepUndefined ? "undefined" : "null";
|
|
31
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
32
|
+
const isPrimitive = (val) => require_assertIsBoolean.isNull(val) || !require_assertIsBoolean.isObjectOrArray(val) && !require_assertIsBoolean.isFunction(val);
|
|
33
|
+
const deepProcess = (val) => {
|
|
34
|
+
if (require_assertIsBoolean.isNumberObject(val)) {
|
|
35
|
+
const valOf = val.valueOf();
|
|
36
|
+
return require_assertIsBoolean.isNaN(valOf) || require_assertIsBoolean.isInfinityNumber(valOf) ? null : valOf;
|
|
37
|
+
}
|
|
38
|
+
if (require_assertIsBoolean.isStringObject(val)) return val.valueOf();
|
|
39
|
+
if (require_assertIsBoolean.isBooleanObject(val)) return val.valueOf();
|
|
40
|
+
if (require_assertIsBoolean.isFunction(val) || require_assertIsBoolean.isSymbol(val)) return void 0;
|
|
41
|
+
if (require_isBigInt.isBigInt(val)) return val.toString();
|
|
42
|
+
if (require_assertIsBoolean.isNaN(val) || require_assertIsBoolean.isInfinityNumber(val)) return null;
|
|
43
|
+
if (require_assertIsBoolean.isUndefined(val)) return keepUndefined ? void 0 : null;
|
|
44
|
+
if (require_assertIsBoolean.isObjectOrArray(val)) {
|
|
45
|
+
if (seen.has(val)) return "[Circular]";
|
|
46
|
+
seen.add(val);
|
|
47
|
+
if (isDate(val)) return val.toISOString();
|
|
48
|
+
if (isMap(val)) return { map: Array.from(val.entries()).map(([k, v]) => [k, deepProcess(v)]) };
|
|
49
|
+
if (require_assertIsBoolean.isSet(val)) return { set: Array.from(val.values()).map(deepProcess) };
|
|
50
|
+
if (require_assertIsBoolean.isArray(val)) {
|
|
51
|
+
const processedArr = val.map(deepProcess);
|
|
52
|
+
if (sortArray) {
|
|
53
|
+
const primitives = [];
|
|
54
|
+
const nonPrimitives = [];
|
|
55
|
+
for (const item of processedArr) if (isPrimitive(item)) primitives.push(item);
|
|
56
|
+
else nonPrimitives.push(item);
|
|
57
|
+
primitives.sort((a, b) => {
|
|
58
|
+
if (require_assertIsBoolean.isNumber(a) && require_assertIsBoolean.isNumber(b)) return a - b;
|
|
59
|
+
return String(a).localeCompare(String(b));
|
|
60
|
+
});
|
|
61
|
+
return [...primitives, ...nonPrimitives];
|
|
62
|
+
}
|
|
63
|
+
return processedArr;
|
|
64
|
+
}
|
|
65
|
+
const keys = Object.keys(val);
|
|
66
|
+
if (sortKeys) keys.sort((a, b) => {
|
|
67
|
+
const na = Number(a);
|
|
68
|
+
const nb = Number(b);
|
|
69
|
+
if (!require_assertIsBoolean.isNaN(na) && !require_assertIsBoolean.isNaN(nb)) return na - nb;
|
|
70
|
+
return a.localeCompare(b);
|
|
71
|
+
});
|
|
72
|
+
const result = {};
|
|
73
|
+
if (require_assertIsBoolean.isObject(val)) for (const k of keys) {
|
|
74
|
+
const v = deepProcess(val[k]);
|
|
75
|
+
if (!require_assertIsBoolean.isUndefined(v)) result[k] = v;
|
|
76
|
+
}
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
79
|
+
return val;
|
|
80
|
+
};
|
|
81
|
+
try {
|
|
82
|
+
return JSON.stringify(deepProcess(value), null, pretty ? 2 : 0);
|
|
83
|
+
} catch (err) {
|
|
84
|
+
console.warn("Error in safeStableStringify:", err);
|
|
85
|
+
return "{}";
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
Object.defineProperty(exports, 'isDate', {
|
|
89
|
+
enumerable: true,
|
|
90
|
+
get: function () {
|
|
91
|
+
return isDate;
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
Object.defineProperty(exports, 'isMap', {
|
|
95
|
+
enumerable: true,
|
|
96
|
+
get: function () {
|
|
97
|
+
return isMap;
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
Object.defineProperty(exports, 'safeStableStringify', {
|
|
101
|
+
enumerable: true,
|
|
102
|
+
get: function () {
|
|
103
|
+
return safeStableStringify;
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
//# sourceMappingURL=safeStableStringify-CJtP89qn.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"safeStableStringify-CJtP89qn.cjs","names":["isPlainObject","isBoolean","isNaN","hasOwnProp","isBoolean","getPreciseType","isUndefined","isNull","isObjectOrArray","isFunction","isNumberObject","isNaN","isInfinityNumber","isStringObject","isBooleanObject","isSymbol","isBigInt","isSet","isArray","isNumber","isObject"],"sources":["../src/predicates/is/isMap.ts","../src/predicates/is/isDate.ts","../src/conversions/stringify/safeStableStringify.ts"],"sourcesContent":["/** --------------------------------------------------\n * * ***Type guard: `isMap`.***\n * ----------------------------------------------------------\n * **Checks whether the given value is a **[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) object**.**\n * - **Behavior:**\n * - Ensures that the provided value is an instance of **[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)**.\n * - Useful in TypeScript for narrowing types when working with collections.\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is instance of **[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)**, else `false`.\n * @example\n * isMap(new Map());\n * // ➔ true\n * isMap(new WeakMap());\n * // ➔ false\n * isMap({});\n * // ➔ false\n */\nexport function isMap<K = unknown, V = unknown>(\n value: Map<K, V>\n): value is Map<K, V>;\nexport function isMap(value: unknown): value is Map<unknown, unknown>;\nexport function isMap(value: unknown): boolean {\n return (\n Object.prototype.toString.call(value) === \"[object Map]\" ||\n value instanceof Map\n );\n}\n","import { assertIsPlainObject } from \"@/assertions/objects/assertIsPlainObject\";\n\nimport { isNaN } from \"./isNaN\";\nimport { isPlainObject } from \"./isPlainObject\";\nimport { isBoolean } from \"./isBoolean\";\n\ntype isDateOptions = {\n /** * ***Skip the validity check (`!isNaN(date.getTime())`).***\n *\n * When `true`, the function only checks that the value is an\n * instance of `Date` without verifying that it represents a valid\n * date value, default: `false`.\n *\n * @default false\n */\n skipInvalidDate?: boolean;\n};\n\n/** ----------------------------------------------------------\n * * ***Type guard: `isDate`.***\n * ----------------------------------------------------------\n * **Determines whether the given `value` is a real, valid JavaScript\n * **[`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)** object.**\n * - **Behavior:**\n * - Returns **true** only if:\n * - `value` is an instance of `Date`.\n * - and, unless `options.skipInvalidDate` is `true`,\n * the underlying time value is valid (`!isNaN(value.getTime())`).\n * - Returns **false** for:\n * - non-Date values (strings, numbers, etc.).\n * - `Date` instances that represent an invalid time value\n * (e.g. `new Date(\"bad\")`), unless skipping is enabled.\n * @param {*} value - The value to check.\n * @param {isDateOptions} [options] - Optional settings.\n * @returns {boolean} Return `true` if value is a valid Date object.\n * @example\n * isDate(new Date());\n * // ➜ true\n * isDate(new Date(\"invalid\"));\n * // ➜ false\n * isDate(\"2024-01-01\");\n * // ➜ false\n *\n * // Skipping validity check:\n * isDate(new Date(\"invalid\"), { skipInvalidDate: true });\n * // ➜ true\n */\nexport const isDate = (\n value: unknown,\n options: isDateOptions = {}\n): value is Date => {\n assertIsPlainObject(options, {\n message: ({ currentType, validType }) =>\n `Second parameter (\\`options\\`) must be of type \\`${validType}\\`, but received: \\`${currentType}\\`.`\n });\n\n const skipInvalidDate =\n isPlainObject(options) && isBoolean(options.skipInvalidDate)\n ? options.skipInvalidDate\n : false;\n\n const instanceDate = value instanceof Date;\n\n if (skipInvalidDate) return instanceDate;\n return instanceDate && !isNaN(value.getTime());\n};\n","import { assertIsPlainObject } from \"@/assertions/objects/assertIsPlainObject\";\n\nimport { isSet } from \"@/predicates/is/isSet\";\nimport { isMap } from \"@/predicates/is/isMap\";\nimport { isNaN } from \"@/predicates/is/isNaN\";\nimport { isDate } from \"@/predicates/is/isDate\";\nimport { isNull } from \"@/predicates/is/isNull\";\nimport { isArray } from \"@/predicates/is/isArray\";\nimport { isSymbol } from \"@/predicates/is/isSymbol\";\nimport { isNumber } from \"@/predicates/is/isNumber\";\nimport { isObject } from \"@/predicates/is/isObject\";\nimport { isBigInt } from \"@/predicates/is/isBigInt\";\nimport { isBoolean } from \"@/predicates/is/isBoolean\";\nimport { isFunction } from \"@/predicates/is/isFunction\";\nimport { hasOwnProp } from \"@/predicates/has/hasOwnProp\";\nimport { isUndefined } from \"@/predicates/is/isUndefined\";\nimport { isNumberObject } from \"@/predicates/is/isNumberObject\";\nimport { isStringObject } from \"@/predicates/is/isStringObject\";\nimport { isBooleanObject } from \"@/predicates/is/isBooleanObject\";\nimport { isObjectOrArray } from \"@/predicates/is/isObjectOrArray\";\nimport { getPreciseType } from \"@/predicates/type/getPreciseType\";\nimport { isInfinityNumber } from \"@/predicates/is/isInfinityNumber\";\n\n/** -------------------------------------------------\n * * ***Type Options for **{@link safeStableStringify | `safeStableStringify`}**.***\n * -------------------------------------------------\n */\ntype SafeStableStringifyOptions = {\n /** -------------------------------------------------\n * * ***Whether to sort **object keys** alphabetically (recursively).***\n * -------------------------------------------------\n *\n * - `true` (default): object keys are sorted to ensure stable output.\n * - `false`: preserves original insertion order of keys.\n *\n * @default true\n */\n sortKeys?: boolean;\n /** -------------------------------------------------\n * * ***Whether to sort **primitive values inside arrays**.***\n * -------------------------------------------------\n *\n * - `true`: primitive values in arrays are sorted to ensure stable output.\n * - `false` (default): arrays retain their original order; objects and nested arrays are not reordered.\n *\n * @default false\n */\n sortArray?: boolean;\n /** -------------------------------------------------\n * * ***Whether to pretty-print JSON output with 2-space indentation.***\n * -------------------------------------------------\n *\n * - `true`: output is formatted with indentation and newlines.\n * - `false` (default): produces compact single-line JSON.\n *\n * @default false\n */\n pretty?: boolean;\n /** -------------------------------------------------\n * * ***Preserve `undefined` values instead of converting them to `null`.***\n * -------------------------------------------------\n * **Controls how the internal `deepProcess` step rewrites values\n * **before** the final `JSON.stringify` call.**\n * - **Default (`false`):**\n * * Every `undefined` value (object properties **and** array elements)\n * is replaced with `null` **before** serialization, because this happens\n * first, the key is **not removed** by `JSON.stringify`.\n * - **`true`** – Leaves `undefined` untouched so the final\n * `JSON.stringify` call behaves natively:\n * * Object properties with `undefined` are **removed**.\n * * Array elements that are `undefined` become `null`.\n * @default false\n * @example\n * // ✅ keepUndefined = true: behaves like native JSON.stringify\n * safeStableStringify({ a: undefined }, { keepUndefined: true });\n * // ➔ '{}' // key removed\n *\n * // ✅ Default (false): convert undefined to null, key kept\n * safeStableStringify({ a: undefined });\n * // ➔ '{\"a\":null}' // key present, value null\n *\n * // Arrays\n * safeStableStringify([undefined]);\n * // ➔ '[null]' // same, but via pre-replacement\n * safeStableStringify([undefined], { keepUndefined: true });\n * // ➔ '[null]' // element becomes null\n */\n keepUndefined?: boolean;\n};\n\n/** --------------------------------------------\n * * ***Utility: `safeStableStringify`.***\n * ---------------------------------------------\n * **Safely converts a JavaScript value into a stable, JSON-compatible string.**\n * - **This function is an enhanced version of `JSON.stringify` with additional guarantees:**\n * - ***Features:***\n * - Recursively sorts object keys **only if** `sortKeys` is `true` (default: `true`), to ensure stable\n * key order.\n * - If `sortKeys` is `false`, preserves the original insertion order of object keys.\n * - Optionally sorts array primitive values **only if** `sortArray` is `true` (default: `false`).\n * - Only primitive values in arrays are sorted.\n * - Objects and nested arrays keep their original position and are appended after sorted primitives.\n * - If `sortArray` is `false`, arrays retain their original order.\n * - Converts JavaScript special values for JSON safety:\n * - `undefined`, `NaN`, `Infinity`, `-Infinity` ➔ `null`.\n * - `BigInt` ➔ string (JSON does not support BigInt).\n * - Converts boxed primitives box into their primitive equivalents:\n * - `new Number(42)` ➔ `Number(42)` ➔ `42`.\n * - `new String(\"hi\")` ➔ `String(\"hi\")` ➔ `\"hi\"`.\n * - `new Boolean(true)` ➔ `Boolean(true)` ➔ `true`.\n * - Functions and Symbols are removed.\n * - Circular references are replaced with the string `\"[Circular]\"`.\n * - Serializes:\n * - `Date` ➔ ISO string (`date.toISOString()`).\n * - `Set` ➔ `{ set: [values...] }` (values are recursively processed).\n * - `Map` ➔ `{ map: [ [key, value], ... ] }` (values are recursively processed).\n * - Compared to `JSON.stringify`, this ensures **stable output**:\n * - Same object structure always produces the same string.\n * - Useful for deep equality checks, hashing, caching keys, or snapshot tests.\n * - Controls how `undefined` is handled **before** the final `JSON.stringify` call, by `keepUndefined`\n * options, default: `false`.\n * - **false**: All `undefined` values (object properties and array elements) are replaced\n * with `null`, so object keys remain.\n * - **true**: Leaves `undefined` values as-is, and handling by native `JSON.stringify` then:\n * 1. Removes object properties that are `undefined`.\n * 2. Converts `undefined` array elements to `null`.\n * - Use `true` when you need native removal of keys or to preserve sparse arrays\n * exactly as `JSON.stringify` would.\n * @param {*} value\n * ***Any JavaScript value to serialize, can be:***\n * - Primitives (`number`, `string`, `boolean`, `bigint`, `null`, `undefined`).\n * - Boxed primitives (`new Number()`, `new String()`, `new Boolean()`).\n * - Arrays, plain objects, nested structures.\n * - Date, Map, Set.\n * - Circular structures.\n * @param {SafeStableStringifyOptions} [options]\n * ***Configuration options for `safeStableStringify`:***\n * - `keepUndefined` (boolean) – Control how `undefined` is handled **before** the final `JSON.stringify`\n * call, default: `false`.\n * - `sortKeys` (boolean) – Whether to sort object keys alphabetically (recursively), default: `true`.\n * - `sortArray` (boolean) – Whether to sort primitive values inside arrays, default: `false`.\n * - `pretty` (boolean) – Whether to pretty-print JSON output with 2-space indentation, default: `false`.\n * @returns {string}\n * A stable JSON string representation of the input value.\n * @throws **{@link TypeError | `TypeError`}** if `sortKeys`, `sortArray`, or `pretty` are not strictly boolean.\n * @example\n * ```ts\n * // Basic object key sorting\n * safeStableStringify({ b: 2, a: 1 });\n * // ➔ '{\"a\":1,\"b\":2}'\n *\n * // Disable key sorting (preserve insertion order)\n * safeStableStringify({ b: 2, a: 1 }, {\n * sortKeys:false\n * });\n * // ➔ '{\"b\":2,\"a\":1}'\n *\n * // Sorting arrays with sortArray\n * safeStableStringify([3, 1, 2], {\n * sortArray:true\n * });\n * // ➔ '[1,2,3]'\n *\n * // keepUndefined = true (native removal of keys)\n * safeStableStringify({ a: undefined }, { keepUndefined: true });\n * // ➔ '{}' // key `a` is removed, like native JSON.stringify\n *\n * // Default keepUndefined = false (convert to null, keep key)\n * safeStableStringify({ a: undefined });\n * // ➔ '{\"a\":null}'\n *\n * // Nested object + sortArray=true\n * safeStableStringify({ z: [3, 1, 2], x: { d: 4, c: 3 } }, {\n * sortKeys:true,\n * sortArray:true\n * });\n * // ➔ '{\"x\":{\"c\":3,\"d\":4},\"z\":[1,2,3]}'\n *\n * // sortKeys=false and sortArray=true\n * safeStableStringify({ z: [3, 1, 2], x: { d: 4, c: 3 } }, {\n * sortKeys:false,\n * sortArray:true\n * });\n * // ➔ '{\"z\":[1,2,3],\"x\":{\"d\":4,\"c\":3}}'\n *\n * // Pretty print output\n * safeStableStringify([3, 1, 2], {\n * sortArray:true,\n * pretty:true\n * });\n * // ➔ `[\n * // 1,\n * // 2,\n * // 3\n * // ]`\n *\n * // Boxed primitives converted to primitive\n * safeStableStringify({ n: new Number(42), s: new String(\"hi\"), b: new Boolean(true) });\n * // ➔ '{\"n\":42,\"s\":\"hi\",\"b\":true}'\n *\n * // Handles Date, BigInt, Map and Set\n * safeStableStringify({\n * time: new Date(\"2025-01-01\"),\n * big: BigInt(9007199254740991),\n * data: new Map([[\"key\", new Set([1, 2])]])\n * });\n * // ➔ '{\"big\":\"9007199254740991\",\"data\":{\"map\":[[\"key\",{\"set\":[1,2]}]]},\"time\":\"2025-01-01T00:00:00.000Z\"}'\n *\n * // Functions and symbols are removed\n * safeStableStringify({ f: () => {}, s: Symbol(\"wow\") });\n * // ➔ '{}'\n *\n * // undefined, NaN, Infinity convert to null (keepUndefined = false or keepUndefined = true)\n * safeStableStringify([undefined, NaN, Infinity, -Infinity]);\n * // ➔ '[null,null,null,null]'\n *\n * // Circular reference\n * const obj = { name: \"A\" };\n * obj.self = obj;\n * safeStableStringify(obj);\n * // ➔ '{\"name\":\"A\",\"self\":\"[Circular]\"}'\n *\n * // Complex nested sortArray with objects\n * const arr = [9, 7, [4, 2, 3], { z: [5, 1, 6] }];\n * safeStableStringify(arr, { sortArray: true, sortKeys: true });\n * // ➔ '[7,9,[2,3,4],{\"z\":[1,5,6]}]'\n * ```\n */\nexport const safeStableStringify = (\n value: unknown,\n options: SafeStableStringifyOptions = {}\n): string => {\n assertIsPlainObject(options, {\n message: ({ currentType, validType }) =>\n `Second parameter (\\`options\\`) must be of type \\`${validType}\\`, but received: \\`${currentType}\\`.`\n });\n\n const pretty = hasOwnProp(options, \"pretty\") ? options.pretty : false;\n const sortKeys = hasOwnProp(options, \"sortKeys\") ? options.sortKeys : true;\n const sortArray = hasOwnProp(options, \"sortArray\")\n ? options.sortArray\n : false;\n const keepUndefined = hasOwnProp(options, \"keepUndefined\")\n ? options.keepUndefined\n : false;\n\n if (\n !isBoolean(sortKeys) ||\n !isBoolean(sortArray) ||\n !isBoolean(pretty) ||\n !isBoolean(keepUndefined)\n ) {\n throw new TypeError(\n `Parameters \\`sortKeys\\`, \\`sortArray\\`, \\`keepUndefined\\` and \\`pretty\\` property of the \\`options\\` (second parameter) must be of type \\`boolean\\`, but received: \"['sortKeys': \\`${getPreciseType(\n sortKeys\n )}\\`, 'sortArray': \\`${getPreciseType(\n sortArray\n )}\\`, 'keepUndefined': \\`${getPreciseType(\n keepUndefined\n )}\\`, 'pretty': \\`${getPreciseType(pretty)}\\`]\".`\n );\n }\n\n if (isUndefined(value)) {\n return keepUndefined ? \"undefined\" : \"null\";\n }\n\n const seen = new WeakSet();\n\n const isPrimitive = (val: unknown): boolean =>\n isNull(val) || (!isObjectOrArray(val) && !isFunction(val));\n\n const deepProcess = (val: unknown): unknown => {\n if (isNumberObject(val)) {\n const valOf = val.valueOf();\n return isNaN(valOf) || isInfinityNumber(valOf) ? null : valOf;\n }\n if (isStringObject(val)) return val.valueOf();\n if (isBooleanObject(val)) return val.valueOf();\n if (isFunction(val) || isSymbol(val)) return undefined;\n if (isBigInt(val)) return val.toString();\n if (isNaN(val) || isInfinityNumber(val)) return null;\n if (isUndefined(val)) {\n return keepUndefined ? undefined : null;\n }\n\n if (isObjectOrArray(val)) {\n if (seen.has(val)) return \"[Circular]\";\n seen.add(val);\n\n if (isDate(val)) return val.toISOString();\n if (isMap(val)) {\n return {\n map: Array.from(val.entries()).map(([k, v]) => [k, deepProcess(v)])\n };\n }\n if (isSet(val)) return { set: Array.from(val.values()).map(deepProcess) };\n\n if (isArray(val)) {\n const processedArr = val.map(deepProcess);\n if (sortArray) {\n const primitives: unknown[] = [];\n const nonPrimitives: unknown[] = [];\n\n for (const item of processedArr) {\n if (isPrimitive(item)) primitives.push(item);\n else nonPrimitives.push(item);\n }\n primitives.sort((a, b) => {\n if (isNumber(a) && isNumber(b)) return a - b;\n return String(a).localeCompare(String(b));\n });\n return [...primitives, ...nonPrimitives];\n }\n return processedArr;\n }\n\n const keys = Object.keys(val);\n if (sortKeys) {\n keys.sort((a, b) => {\n const na = Number(a);\n const nb = Number(b);\n if (!isNaN(na) && !isNaN(nb)) return na - nb;\n return a.localeCompare(b);\n });\n }\n\n const result: Record<string, unknown> = {};\n\n if (isObject(val)) {\n for (const k of keys) {\n const v = deepProcess(val[k]);\n if (!isUndefined(v)) result[k] = v;\n }\n }\n\n return result;\n }\n\n return val;\n };\n\n try {\n return JSON.stringify(deepProcess(value), null, pretty ? 2 : 0);\n } catch (err) {\n console.warn(\"Error in safeStableStringify:\", err);\n return \"{}\";\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAqBA,SAAgB,MAAM,OAAyB;CAC7C,OACE,OAAO,UAAU,SAAS,KAAK,MAAM,KAAK,kBAC1C,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuBrB,MAAa,UACX,OACA,UAAyB,EAAE,KACT;CAClB,4CAAoB,SAAS,EAC3B,UAAU,EAAE,aAAa,gBACvB,oDAAoD,UAAU,sBAAsB,YAAY,MACnG,CAAC;CAEF,MAAM,kBACJA,sCAAc,QAAQ,IAAIC,kCAAU,QAAQ,gBAAgB,GACxD,QAAQ,kBACR;CAEN,MAAM,eAAe,iBAAiB;CAEtC,IAAI,iBAAiB,OAAO;CAC5B,OAAO,gBAAgB,CAACC,8BAAM,MAAM,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AE,OAAO,KAAK;IAC1C,OAAO,EAAE,cAAc,EAAE;KACzB;GAGJ,MAAM,SAAkC,EAAE;GAE1C,IAAIS,iCAAS,IAAI,EACf,KAAK,MAAM,KAAK,MAAM;IACpB,MAAM,IAAI,YAAY,IAAI,GAAG;IAC7B,IAAI,CAACd,oCAAY,EAAE,EAAE,OAAO,KAAK;;GAIrC,OAAO;;EAGT,OAAO;;CAGT,IAAI;EACF,OAAO,KAAK,UAAU,YAAY,MAAM,EAAE,MAAM,SAAS,IAAI,EAAE;UACxD,KAAK;EACZ,QAAQ,KAAK,iCAAiC,IAAI;EAClD,OAAO"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* ========================================================================
|
|
3
|
+
* @rzl-zone/utils-js
|
|
4
|
+
* ------------------------------------------------------------------------
|
|
5
|
+
* Version: `3.12.1-beta.1`
|
|
6
|
+
* Author: `Rizalvin Dwiky <rizalvindwiky@gmail.com>`
|
|
7
|
+
* Repository: `https://github.com/rzl-zone/rzl-zone/tree/main/packages/utils-js`
|
|
8
|
+
* ========================================================================
|
|
9
|
+
*/
|
|
10
|
+
import { A as isPlainObject, C as isSymbol, D as isNaN, E as isNull, F as isBoolean, M as isArray, O as isNumberObject, P as isFunction, S as isUndefined, T as assertIsPlainObject, b as hasOwnProp, f as isSet, g as isStringObject, h as isBooleanObject, j as isObject, m as isInfinityNumber, r as getPreciseType, w as isNumber, x as isObjectOrArray } from "./assertIsBoolean-DR1SaXPD.js";
|
|
11
|
+
import { t as isBigInt } from "./isBigInt-DKe0M6hp.js";
|
|
12
|
+
function isMap(value) {
|
|
13
|
+
return Object.prototype.toString.call(value) === "[object Map]" || value instanceof Map;
|
|
14
|
+
}
|
|
15
|
+
const isDate = (value, options = {}) => {
|
|
16
|
+
assertIsPlainObject(options, { message: ({ currentType, validType }) => `Second parameter (\`options\`) must be of type \`${validType}\`, but received: \`${currentType}\`.` });
|
|
17
|
+
const skipInvalidDate = isPlainObject(options) && isBoolean(options.skipInvalidDate) ? options.skipInvalidDate : false;
|
|
18
|
+
const instanceDate = value instanceof Date;
|
|
19
|
+
if (skipInvalidDate) return instanceDate;
|
|
20
|
+
return instanceDate && !isNaN(value.getTime());
|
|
21
|
+
};
|
|
22
|
+
const safeStableStringify = (value, options = {}) => {
|
|
23
|
+
assertIsPlainObject(options, { message: ({ currentType, validType }) => `Second parameter (\`options\`) must be of type \`${validType}\`, but received: \`${currentType}\`.` });
|
|
24
|
+
const pretty = hasOwnProp(options, "pretty") ? options.pretty : false;
|
|
25
|
+
const sortKeys = hasOwnProp(options, "sortKeys") ? options.sortKeys : true;
|
|
26
|
+
const sortArray = hasOwnProp(options, "sortArray") ? options.sortArray : false;
|
|
27
|
+
const keepUndefined = hasOwnProp(options, "keepUndefined") ? options.keepUndefined : false;
|
|
28
|
+
if (!isBoolean(sortKeys) || !isBoolean(sortArray) || !isBoolean(pretty) || !isBoolean(keepUndefined)) throw new TypeError(`Parameters \`sortKeys\`, \`sortArray\`, \`keepUndefined\` and \`pretty\` property of the \`options\` (second parameter) must be of type \`boolean\`, but received: "['sortKeys': \`${getPreciseType(sortKeys)}\`, 'sortArray': \`${getPreciseType(sortArray)}\`, 'keepUndefined': \`${getPreciseType(keepUndefined)}\`, 'pretty': \`${getPreciseType(pretty)}\`]".`);
|
|
29
|
+
if (isUndefined(value)) return keepUndefined ? "undefined" : "null";
|
|
30
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
31
|
+
const isPrimitive = (val) => isNull(val) || !isObjectOrArray(val) && !isFunction(val);
|
|
32
|
+
const deepProcess = (val) => {
|
|
33
|
+
if (isNumberObject(val)) {
|
|
34
|
+
const valOf = val.valueOf();
|
|
35
|
+
return isNaN(valOf) || isInfinityNumber(valOf) ? null : valOf;
|
|
36
|
+
}
|
|
37
|
+
if (isStringObject(val)) return val.valueOf();
|
|
38
|
+
if (isBooleanObject(val)) return val.valueOf();
|
|
39
|
+
if (isFunction(val) || isSymbol(val)) return void 0;
|
|
40
|
+
if (isBigInt(val)) return val.toString();
|
|
41
|
+
if (isNaN(val) || isInfinityNumber(val)) return null;
|
|
42
|
+
if (isUndefined(val)) return keepUndefined ? void 0 : null;
|
|
43
|
+
if (isObjectOrArray(val)) {
|
|
44
|
+
if (seen.has(val)) return "[Circular]";
|
|
45
|
+
seen.add(val);
|
|
46
|
+
if (isDate(val)) return val.toISOString();
|
|
47
|
+
if (isMap(val)) return { map: Array.from(val.entries()).map(([k, v]) => [k, deepProcess(v)]) };
|
|
48
|
+
if (isSet(val)) return { set: Array.from(val.values()).map(deepProcess) };
|
|
49
|
+
if (isArray(val)) {
|
|
50
|
+
const processedArr = val.map(deepProcess);
|
|
51
|
+
if (sortArray) {
|
|
52
|
+
const primitives = [];
|
|
53
|
+
const nonPrimitives = [];
|
|
54
|
+
for (const item of processedArr) if (isPrimitive(item)) primitives.push(item);
|
|
55
|
+
else nonPrimitives.push(item);
|
|
56
|
+
primitives.sort((a, b) => {
|
|
57
|
+
if (isNumber(a) && isNumber(b)) return a - b;
|
|
58
|
+
return String(a).localeCompare(String(b));
|
|
59
|
+
});
|
|
60
|
+
return [...primitives, ...nonPrimitives];
|
|
61
|
+
}
|
|
62
|
+
return processedArr;
|
|
63
|
+
}
|
|
64
|
+
const keys = Object.keys(val);
|
|
65
|
+
if (sortKeys) keys.sort((a, b) => {
|
|
66
|
+
const na = Number(a);
|
|
67
|
+
const nb = Number(b);
|
|
68
|
+
if (!isNaN(na) && !isNaN(nb)) return na - nb;
|
|
69
|
+
return a.localeCompare(b);
|
|
70
|
+
});
|
|
71
|
+
const result = {};
|
|
72
|
+
if (isObject(val)) for (const k of keys) {
|
|
73
|
+
const v = deepProcess(val[k]);
|
|
74
|
+
if (!isUndefined(v)) result[k] = v;
|
|
75
|
+
}
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
return val;
|
|
79
|
+
};
|
|
80
|
+
try {
|
|
81
|
+
return JSON.stringify(deepProcess(value), null, pretty ? 2 : 0);
|
|
82
|
+
} catch (err) {
|
|
83
|
+
console.warn("Error in safeStableStringify:", err);
|
|
84
|
+
return "{}";
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
export { isDate as n, isMap as r, safeStableStringify as t };
|
|
88
|
+
//# sourceMappingURL=safeStableStringify-CXOZ9Ub8.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"safeStableStringify-CXOZ9Ub8.js","names":[],"sources":["../src/predicates/is/isMap.ts","../src/predicates/is/isDate.ts","../src/conversions/stringify/safeStableStringify.ts"],"sourcesContent":["/** --------------------------------------------------\n * * ***Type guard: `isMap`.***\n * ----------------------------------------------------------\n * **Checks whether the given value is a **[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) object**.**\n * - **Behavior:**\n * - Ensures that the provided value is an instance of **[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)**.\n * - Useful in TypeScript for narrowing types when working with collections.\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is instance of **[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)**, else `false`.\n * @example\n * isMap(new Map());\n * // ➔ true\n * isMap(new WeakMap());\n * // ➔ false\n * isMap({});\n * // ➔ false\n */\nexport function isMap<K = unknown, V = unknown>(\n value: Map<K, V>\n): value is Map<K, V>;\nexport function isMap(value: unknown): value is Map<unknown, unknown>;\nexport function isMap(value: unknown): boolean {\n return (\n Object.prototype.toString.call(value) === \"[object Map]\" ||\n value instanceof Map\n );\n}\n","import { assertIsPlainObject } from \"@/assertions/objects/assertIsPlainObject\";\n\nimport { isNaN } from \"./isNaN\";\nimport { isPlainObject } from \"./isPlainObject\";\nimport { isBoolean } from \"./isBoolean\";\n\ntype isDateOptions = {\n /** * ***Skip the validity check (`!isNaN(date.getTime())`).***\n *\n * When `true`, the function only checks that the value is an\n * instance of `Date` without verifying that it represents a valid\n * date value, default: `false`.\n *\n * @default false\n */\n skipInvalidDate?: boolean;\n};\n\n/** ----------------------------------------------------------\n * * ***Type guard: `isDate`.***\n * ----------------------------------------------------------\n * **Determines whether the given `value` is a real, valid JavaScript\n * **[`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)** object.**\n * - **Behavior:**\n * - Returns **true** only if:\n * - `value` is an instance of `Date`.\n * - and, unless `options.skipInvalidDate` is `true`,\n * the underlying time value is valid (`!isNaN(value.getTime())`).\n * - Returns **false** for:\n * - non-Date values (strings, numbers, etc.).\n * - `Date` instances that represent an invalid time value\n * (e.g. `new Date(\"bad\")`), unless skipping is enabled.\n * @param {*} value - The value to check.\n * @param {isDateOptions} [options] - Optional settings.\n * @returns {boolean} Return `true` if value is a valid Date object.\n * @example\n * isDate(new Date());\n * // ➜ true\n * isDate(new Date(\"invalid\"));\n * // ➜ false\n * isDate(\"2024-01-01\");\n * // ➜ false\n *\n * // Skipping validity check:\n * isDate(new Date(\"invalid\"), { skipInvalidDate: true });\n * // ➜ true\n */\nexport const isDate = (\n value: unknown,\n options: isDateOptions = {}\n): value is Date => {\n assertIsPlainObject(options, {\n message: ({ currentType, validType }) =>\n `Second parameter (\\`options\\`) must be of type \\`${validType}\\`, but received: \\`${currentType}\\`.`\n });\n\n const skipInvalidDate =\n isPlainObject(options) && isBoolean(options.skipInvalidDate)\n ? options.skipInvalidDate\n : false;\n\n const instanceDate = value instanceof Date;\n\n if (skipInvalidDate) return instanceDate;\n return instanceDate && !isNaN(value.getTime());\n};\n","import { assertIsPlainObject } from \"@/assertions/objects/assertIsPlainObject\";\n\nimport { isSet } from \"@/predicates/is/isSet\";\nimport { isMap } from \"@/predicates/is/isMap\";\nimport { isNaN } from \"@/predicates/is/isNaN\";\nimport { isDate } from \"@/predicates/is/isDate\";\nimport { isNull } from \"@/predicates/is/isNull\";\nimport { isArray } from \"@/predicates/is/isArray\";\nimport { isSymbol } from \"@/predicates/is/isSymbol\";\nimport { isNumber } from \"@/predicates/is/isNumber\";\nimport { isObject } from \"@/predicates/is/isObject\";\nimport { isBigInt } from \"@/predicates/is/isBigInt\";\nimport { isBoolean } from \"@/predicates/is/isBoolean\";\nimport { isFunction } from \"@/predicates/is/isFunction\";\nimport { hasOwnProp } from \"@/predicates/has/hasOwnProp\";\nimport { isUndefined } from \"@/predicates/is/isUndefined\";\nimport { isNumberObject } from \"@/predicates/is/isNumberObject\";\nimport { isStringObject } from \"@/predicates/is/isStringObject\";\nimport { isBooleanObject } from \"@/predicates/is/isBooleanObject\";\nimport { isObjectOrArray } from \"@/predicates/is/isObjectOrArray\";\nimport { getPreciseType } from \"@/predicates/type/getPreciseType\";\nimport { isInfinityNumber } from \"@/predicates/is/isInfinityNumber\";\n\n/** -------------------------------------------------\n * * ***Type Options for **{@link safeStableStringify | `safeStableStringify`}**.***\n * -------------------------------------------------\n */\ntype SafeStableStringifyOptions = {\n /** -------------------------------------------------\n * * ***Whether to sort **object keys** alphabetically (recursively).***\n * -------------------------------------------------\n *\n * - `true` (default): object keys are sorted to ensure stable output.\n * - `false`: preserves original insertion order of keys.\n *\n * @default true\n */\n sortKeys?: boolean;\n /** -------------------------------------------------\n * * ***Whether to sort **primitive values inside arrays**.***\n * -------------------------------------------------\n *\n * - `true`: primitive values in arrays are sorted to ensure stable output.\n * - `false` (default): arrays retain their original order; objects and nested arrays are not reordered.\n *\n * @default false\n */\n sortArray?: boolean;\n /** -------------------------------------------------\n * * ***Whether to pretty-print JSON output with 2-space indentation.***\n * -------------------------------------------------\n *\n * - `true`: output is formatted with indentation and newlines.\n * - `false` (default): produces compact single-line JSON.\n *\n * @default false\n */\n pretty?: boolean;\n /** -------------------------------------------------\n * * ***Preserve `undefined` values instead of converting them to `null`.***\n * -------------------------------------------------\n * **Controls how the internal `deepProcess` step rewrites values\n * **before** the final `JSON.stringify` call.**\n * - **Default (`false`):**\n * * Every `undefined` value (object properties **and** array elements)\n * is replaced with `null` **before** serialization, because this happens\n * first, the key is **not removed** by `JSON.stringify`.\n * - **`true`** – Leaves `undefined` untouched so the final\n * `JSON.stringify` call behaves natively:\n * * Object properties with `undefined` are **removed**.\n * * Array elements that are `undefined` become `null`.\n * @default false\n * @example\n * // ✅ keepUndefined = true: behaves like native JSON.stringify\n * safeStableStringify({ a: undefined }, { keepUndefined: true });\n * // ➔ '{}' // key removed\n *\n * // ✅ Default (false): convert undefined to null, key kept\n * safeStableStringify({ a: undefined });\n * // ➔ '{\"a\":null}' // key present, value null\n *\n * // Arrays\n * safeStableStringify([undefined]);\n * // ➔ '[null]' // same, but via pre-replacement\n * safeStableStringify([undefined], { keepUndefined: true });\n * // ➔ '[null]' // element becomes null\n */\n keepUndefined?: boolean;\n};\n\n/** --------------------------------------------\n * * ***Utility: `safeStableStringify`.***\n * ---------------------------------------------\n * **Safely converts a JavaScript value into a stable, JSON-compatible string.**\n * - **This function is an enhanced version of `JSON.stringify` with additional guarantees:**\n * - ***Features:***\n * - Recursively sorts object keys **only if** `sortKeys` is `true` (default: `true`), to ensure stable\n * key order.\n * - If `sortKeys` is `false`, preserves the original insertion order of object keys.\n * - Optionally sorts array primitive values **only if** `sortArray` is `true` (default: `false`).\n * - Only primitive values in arrays are sorted.\n * - Objects and nested arrays keep their original position and are appended after sorted primitives.\n * - If `sortArray` is `false`, arrays retain their original order.\n * - Converts JavaScript special values for JSON safety:\n * - `undefined`, `NaN`, `Infinity`, `-Infinity` ➔ `null`.\n * - `BigInt` ➔ string (JSON does not support BigInt).\n * - Converts boxed primitives box into their primitive equivalents:\n * - `new Number(42)` ➔ `Number(42)` ➔ `42`.\n * - `new String(\"hi\")` ➔ `String(\"hi\")` ➔ `\"hi\"`.\n * - `new Boolean(true)` ➔ `Boolean(true)` ➔ `true`.\n * - Functions and Symbols are removed.\n * - Circular references are replaced with the string `\"[Circular]\"`.\n * - Serializes:\n * - `Date` ➔ ISO string (`date.toISOString()`).\n * - `Set` ➔ `{ set: [values...] }` (values are recursively processed).\n * - `Map` ➔ `{ map: [ [key, value], ... ] }` (values are recursively processed).\n * - Compared to `JSON.stringify`, this ensures **stable output**:\n * - Same object structure always produces the same string.\n * - Useful for deep equality checks, hashing, caching keys, or snapshot tests.\n * - Controls how `undefined` is handled **before** the final `JSON.stringify` call, by `keepUndefined`\n * options, default: `false`.\n * - **false**: All `undefined` values (object properties and array elements) are replaced\n * with `null`, so object keys remain.\n * - **true**: Leaves `undefined` values as-is, and handling by native `JSON.stringify` then:\n * 1. Removes object properties that are `undefined`.\n * 2. Converts `undefined` array elements to `null`.\n * - Use `true` when you need native removal of keys or to preserve sparse arrays\n * exactly as `JSON.stringify` would.\n * @param {*} value\n * ***Any JavaScript value to serialize, can be:***\n * - Primitives (`number`, `string`, `boolean`, `bigint`, `null`, `undefined`).\n * - Boxed primitives (`new Number()`, `new String()`, `new Boolean()`).\n * - Arrays, plain objects, nested structures.\n * - Date, Map, Set.\n * - Circular structures.\n * @param {SafeStableStringifyOptions} [options]\n * ***Configuration options for `safeStableStringify`:***\n * - `keepUndefined` (boolean) – Control how `undefined` is handled **before** the final `JSON.stringify`\n * call, default: `false`.\n * - `sortKeys` (boolean) – Whether to sort object keys alphabetically (recursively), default: `true`.\n * - `sortArray` (boolean) – Whether to sort primitive values inside arrays, default: `false`.\n * - `pretty` (boolean) – Whether to pretty-print JSON output with 2-space indentation, default: `false`.\n * @returns {string}\n * A stable JSON string representation of the input value.\n * @throws **{@link TypeError | `TypeError`}** if `sortKeys`, `sortArray`, or `pretty` are not strictly boolean.\n * @example\n * ```ts\n * // Basic object key sorting\n * safeStableStringify({ b: 2, a: 1 });\n * // ➔ '{\"a\":1,\"b\":2}'\n *\n * // Disable key sorting (preserve insertion order)\n * safeStableStringify({ b: 2, a: 1 }, {\n * sortKeys:false\n * });\n * // ➔ '{\"b\":2,\"a\":1}'\n *\n * // Sorting arrays with sortArray\n * safeStableStringify([3, 1, 2], {\n * sortArray:true\n * });\n * // ➔ '[1,2,3]'\n *\n * // keepUndefined = true (native removal of keys)\n * safeStableStringify({ a: undefined }, { keepUndefined: true });\n * // ➔ '{}' // key `a` is removed, like native JSON.stringify\n *\n * // Default keepUndefined = false (convert to null, keep key)\n * safeStableStringify({ a: undefined });\n * // ➔ '{\"a\":null}'\n *\n * // Nested object + sortArray=true\n * safeStableStringify({ z: [3, 1, 2], x: { d: 4, c: 3 } }, {\n * sortKeys:true,\n * sortArray:true\n * });\n * // ➔ '{\"x\":{\"c\":3,\"d\":4},\"z\":[1,2,3]}'\n *\n * // sortKeys=false and sortArray=true\n * safeStableStringify({ z: [3, 1, 2], x: { d: 4, c: 3 } }, {\n * sortKeys:false,\n * sortArray:true\n * });\n * // ➔ '{\"z\":[1,2,3],\"x\":{\"d\":4,\"c\":3}}'\n *\n * // Pretty print output\n * safeStableStringify([3, 1, 2], {\n * sortArray:true,\n * pretty:true\n * });\n * // ➔ `[\n * // 1,\n * // 2,\n * // 3\n * // ]`\n *\n * // Boxed primitives converted to primitive\n * safeStableStringify({ n: new Number(42), s: new String(\"hi\"), b: new Boolean(true) });\n * // ➔ '{\"n\":42,\"s\":\"hi\",\"b\":true}'\n *\n * // Handles Date, BigInt, Map and Set\n * safeStableStringify({\n * time: new Date(\"2025-01-01\"),\n * big: BigInt(9007199254740991),\n * data: new Map([[\"key\", new Set([1, 2])]])\n * });\n * // ➔ '{\"big\":\"9007199254740991\",\"data\":{\"map\":[[\"key\",{\"set\":[1,2]}]]},\"time\":\"2025-01-01T00:00:00.000Z\"}'\n *\n * // Functions and symbols are removed\n * safeStableStringify({ f: () => {}, s: Symbol(\"wow\") });\n * // ➔ '{}'\n *\n * // undefined, NaN, Infinity convert to null (keepUndefined = false or keepUndefined = true)\n * safeStableStringify([undefined, NaN, Infinity, -Infinity]);\n * // ➔ '[null,null,null,null]'\n *\n * // Circular reference\n * const obj = { name: \"A\" };\n * obj.self = obj;\n * safeStableStringify(obj);\n * // ➔ '{\"name\":\"A\",\"self\":\"[Circular]\"}'\n *\n * // Complex nested sortArray with objects\n * const arr = [9, 7, [4, 2, 3], { z: [5, 1, 6] }];\n * safeStableStringify(arr, { sortArray: true, sortKeys: true });\n * // ➔ '[7,9,[2,3,4],{\"z\":[1,5,6]}]'\n * ```\n */\nexport const safeStableStringify = (\n value: unknown,\n options: SafeStableStringifyOptions = {}\n): string => {\n assertIsPlainObject(options, {\n message: ({ currentType, validType }) =>\n `Second parameter (\\`options\\`) must be of type \\`${validType}\\`, but received: \\`${currentType}\\`.`\n });\n\n const pretty = hasOwnProp(options, \"pretty\") ? options.pretty : false;\n const sortKeys = hasOwnProp(options, \"sortKeys\") ? options.sortKeys : true;\n const sortArray = hasOwnProp(options, \"sortArray\")\n ? options.sortArray\n : false;\n const keepUndefined = hasOwnProp(options, \"keepUndefined\")\n ? options.keepUndefined\n : false;\n\n if (\n !isBoolean(sortKeys) ||\n !isBoolean(sortArray) ||\n !isBoolean(pretty) ||\n !isBoolean(keepUndefined)\n ) {\n throw new TypeError(\n `Parameters \\`sortKeys\\`, \\`sortArray\\`, \\`keepUndefined\\` and \\`pretty\\` property of the \\`options\\` (second parameter) must be of type \\`boolean\\`, but received: \"['sortKeys': \\`${getPreciseType(\n sortKeys\n )}\\`, 'sortArray': \\`${getPreciseType(\n sortArray\n )}\\`, 'keepUndefined': \\`${getPreciseType(\n keepUndefined\n )}\\`, 'pretty': \\`${getPreciseType(pretty)}\\`]\".`\n );\n }\n\n if (isUndefined(value)) {\n return keepUndefined ? \"undefined\" : \"null\";\n }\n\n const seen = new WeakSet();\n\n const isPrimitive = (val: unknown): boolean =>\n isNull(val) || (!isObjectOrArray(val) && !isFunction(val));\n\n const deepProcess = (val: unknown): unknown => {\n if (isNumberObject(val)) {\n const valOf = val.valueOf();\n return isNaN(valOf) || isInfinityNumber(valOf) ? null : valOf;\n }\n if (isStringObject(val)) return val.valueOf();\n if (isBooleanObject(val)) return val.valueOf();\n if (isFunction(val) || isSymbol(val)) return undefined;\n if (isBigInt(val)) return val.toString();\n if (isNaN(val) || isInfinityNumber(val)) return null;\n if (isUndefined(val)) {\n return keepUndefined ? undefined : null;\n }\n\n if (isObjectOrArray(val)) {\n if (seen.has(val)) return \"[Circular]\";\n seen.add(val);\n\n if (isDate(val)) return val.toISOString();\n if (isMap(val)) {\n return {\n map: Array.from(val.entries()).map(([k, v]) => [k, deepProcess(v)])\n };\n }\n if (isSet(val)) return { set: Array.from(val.values()).map(deepProcess) };\n\n if (isArray(val)) {\n const processedArr = val.map(deepProcess);\n if (sortArray) {\n const primitives: unknown[] = [];\n const nonPrimitives: unknown[] = [];\n\n for (const item of processedArr) {\n if (isPrimitive(item)) primitives.push(item);\n else nonPrimitives.push(item);\n }\n primitives.sort((a, b) => {\n if (isNumber(a) && isNumber(b)) return a - b;\n return String(a).localeCompare(String(b));\n });\n return [...primitives, ...nonPrimitives];\n }\n return processedArr;\n }\n\n const keys = Object.keys(val);\n if (sortKeys) {\n keys.sort((a, b) => {\n const na = Number(a);\n const nb = Number(b);\n if (!isNaN(na) && !isNaN(nb)) return na - nb;\n return a.localeCompare(b);\n });\n }\n\n const result: Record<string, unknown> = {};\n\n if (isObject(val)) {\n for (const k of keys) {\n const v = deepProcess(val[k]);\n if (!isUndefined(v)) result[k] = v;\n }\n }\n\n return result;\n }\n\n return val;\n };\n\n try {\n return JSON.stringify(deepProcess(value), null, pretty ? 2 : 0);\n } catch (err) {\n console.warn(\"Error in safeStableStringify:\", err);\n return \"{}\";\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAqBA,SAAgB,MAAM,OAAyB;CAC7C,OACE,OAAO,UAAU,SAAS,KAAK,MAAM,KAAK,kBAC1C,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuBrB,MAAa,UACX,OACA,UAAyB,EAAE,KACT;CAClB,oBAAoB,SAAS,EAC3B,UAAU,EAAE,aAAa,gBACvB,oDAAoD,UAAU,sBAAsB,YAAY,MACnG,CAAC;CAEF,MAAM,kBACJ,cAAc,QAAQ,IAAI,UAAU,QAAQ,gBAAgB,GACxD,QAAQ,kBACR;CAE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
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
get: function () { return chunkGKC3UDMC_cjs.toSnakeCase; }
|
|
82
|
-
});
|
|
2
|
+
* ========================================================================
|
|
3
|
+
* @rzl-zone/utils-js
|
|
4
|
+
* ------------------------------------------------------------------------
|
|
5
|
+
* Version: `3.12.1-beta.1`
|
|
6
|
+
* Author: `Rizalvin Dwiky <rizalvindwiky@gmail.com>`
|
|
7
|
+
* Repository: `https://github.com/rzl-zone/rzl-zone/tree/main/packages/utils-js`
|
|
8
|
+
* ========================================================================
|
|
9
|
+
*/
|
|
10
|
+
"use strict";
|
|
11
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
12
|
+
const require_assertIsBoolean = require('../assertIsBoolean-C8WEXVr2.cjs');
|
|
13
|
+
const require_isEmptyString = require('../isEmptyString-UiiUsSQj.cjs');
|
|
14
|
+
const require_normalizeSpaces = require('../normalizeSpaces-ZXnR4Qzp.cjs');
|
|
15
|
+
const require_normalizeString = require('../normalizeString-BE6ELqEb.cjs');
|
|
16
|
+
const require_removeSpaces = require('../removeSpaces-CWIvhZHg.cjs');
|
|
17
|
+
const capitalizeFirst = (string, options = {
|
|
18
|
+
lowerCaseNextRest: true,
|
|
19
|
+
trim: false
|
|
20
|
+
}) => {
|
|
21
|
+
if (!require_assertIsBoolean.isNonEmptyString(string)) return "";
|
|
22
|
+
if (!require_assertIsBoolean.isPlainObject(options)) options = {};
|
|
23
|
+
const lowerCaseNextRest = options.lowerCaseNextRest !== false;
|
|
24
|
+
if (options.trim === true) string = string.trim();
|
|
25
|
+
return (string[0] ? string[0].toUpperCase() : "") + (lowerCaseNextRest ? string.slice(1).toLowerCase() : string.slice(1));
|
|
26
|
+
};
|
|
27
|
+
const capitalizeWords = (value, options = {
|
|
28
|
+
collapseSpaces: false,
|
|
29
|
+
trim: false
|
|
30
|
+
}) => {
|
|
31
|
+
if (!require_assertIsBoolean.isNonEmptyString(value)) return "";
|
|
32
|
+
let result = value;
|
|
33
|
+
if (!require_assertIsBoolean.isPlainObject(options)) options = {};
|
|
34
|
+
const collapseSpaces = options.collapseSpaces === true;
|
|
35
|
+
if (options.trim === true) result = result.trim();
|
|
36
|
+
if (collapseSpaces) {
|
|
37
|
+
const leadingSpaces = result.match(/^\s*/)?.[0] ?? "";
|
|
38
|
+
const trailingSpaces = result.match(/\s*$/)?.[0] ?? "";
|
|
39
|
+
result = result.trim().replace(/\s+/g, " ");
|
|
40
|
+
result = `${leadingSpaces}${result}${trailingSpaces}`;
|
|
41
|
+
}
|
|
42
|
+
return result.toLowerCase().split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
|
|
43
|
+
};
|
|
44
|
+
function stripHtmlTags(input) {
|
|
45
|
+
if (!require_assertIsBoolean.isString(input)) return;
|
|
46
|
+
if (require_isEmptyString.isEmptyString(input)) return "";
|
|
47
|
+
return input.replace(/<\/?[a-zA-Z][^<>]*\/?>/g, " ").trim().replace(/\s+/g, " ").trim();
|
|
48
|
+
}
|
|
49
|
+
const getInitialsName = (name) => {
|
|
50
|
+
if (!require_assertIsBoolean.isNonEmptyString(name)) return "";
|
|
51
|
+
name = name.replace(/\s+/g, " ").trim();
|
|
52
|
+
const nameParts = name.split(" ");
|
|
53
|
+
if (nameParts.length > 1) {
|
|
54
|
+
if (!(nameParts[0] && nameParts[1] && nameParts[1][0])) return "";
|
|
55
|
+
return (nameParts[0][0] + nameParts[1][0]).toUpperCase();
|
|
56
|
+
}
|
|
57
|
+
return name.length > 1 ? name.substring(0, 2).toUpperCase() : name[0]?.toUpperCase() ?? "";
|
|
58
|
+
};
|
|
59
|
+
const replaceAt = (index, originalString, replaceTo) => {
|
|
60
|
+
if (!require_assertIsBoolean.isNumber(index) || !require_assertIsBoolean.isString(replaceTo) || !require_assertIsBoolean.isString(originalString)) throw new TypeError(`First parameter (\`index\`) must be of type \`number\`, second parameter (\`originalString\`) and third parameter (\`replaceTo\`) must be of type \`string\`, but received: "['index': \`${require_assertIsBoolean.getPreciseType(index)}\`, 'originalString': \`${require_assertIsBoolean.getPreciseType(originalString)}\`, 'replaceTo': \`${require_assertIsBoolean.getPreciseType(replaceTo)}\`]".`);
|
|
61
|
+
if (index < 0 || index >= originalString.length) throw new RangeError("First parameter (`index`) is out of range from second parameter (`originalString`).");
|
|
62
|
+
return originalString.slice(0, index) + replaceTo + originalString.slice(index + 1);
|
|
63
|
+
};
|
|
64
|
+
exports.capitalizeFirst = capitalizeFirst;
|
|
65
|
+
exports.capitalizeWords = capitalizeWords;
|
|
66
|
+
exports.getInitialsName = getInitialsName;
|
|
67
|
+
exports.normalizeSpaces = require_normalizeSpaces.normalizeSpaces;
|
|
68
|
+
exports.normalizeString = require_normalizeString.normalizeString;
|
|
69
|
+
exports.removeSpaces = require_removeSpaces.removeSpaces;
|
|
70
|
+
exports.replaceAt = replaceAt;
|
|
71
|
+
exports.slugify = require_assertIsBoolean.slugify;
|
|
72
|
+
exports.stripHtmlTags = stripHtmlTags;
|
|
73
|
+
exports.toCamelCase = require_assertIsBoolean.toCamelCase;
|
|
74
|
+
exports.toDotCase = require_assertIsBoolean.toDotCase;
|
|
75
|
+
exports.toKebabCase = require_assertIsBoolean.toKebabCase;
|
|
76
|
+
exports.toLowerCase = require_assertIsBoolean.toLowerCase;
|
|
77
|
+
exports.toPascalCase = require_assertIsBoolean.toPascalCase;
|
|
78
|
+
exports.toPascalCaseSpace = require_assertIsBoolean.toPascalCaseSpace;
|
|
79
|
+
exports.toSnakeCase = require_assertIsBoolean.toSnakeCase;
|
|
80
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["isNonEmptyString","isPlainObject","isNonEmptyString","isPlainObject","isString","isEmptyString","isNonEmptyString","isNumber","isString","getPreciseType"],"sources":["../../src/strings/capitalizations/capitalizeFirst.ts","../../src/strings/capitalizations/capitalizeWords.ts","../../src/strings/sanitizations/stripHtmlTags.ts","../../src/strings/utils/getInitialsName.ts","../../src/strings/utils/replaceAt.ts"],"sourcesContent":["import { isPlainObject } from \"@/predicates/is/isPlainObject\";\nimport { isNonEmptyString } from \"@/predicates/is/isNonEmptyString\";\n\ntype CapitalizeFirstOptions = {\n /** If true **(default)**, the rest of the string will be converted to lowercase after capitalizing the first letter.\n *\n * @default true\n */\n lowerCaseNextRest?: boolean;\n /** If true, the string will trimmed, default: `false`.\n *\n * @default false\n */\n trim?: boolean;\n};\n\n/** ----------------------------------------------------------\n * * ***Utility: `capitalizeFirst`.***\n * ----------------------------------------------------------\n * **Capitalizes the first letter of a string, with optionally lowercases the rest and trims whitespace.**\n * @param {string | null | undefined} string - The string to be processed.\n * @param {CapitalizeFirstOptions} [options] - Options to control behavior.\n * @param {CapitalizeFirstOptions[\"lowerCaseNextRest\"]} [options.lowerCaseNextRest=true] - If true, lowercases the rest (next first letter), default: `true`.\n * @param {CapitalizeFirstOptions[\"trim\"]} [options.trim=false] - If true, trims the string before processing, default: `false`.\n * @returns {string} The processed string, returns `\"\"` if input is `null`, `undefined`, or `not a valid string`.\n * @example\n * ```ts\n * capitalizeFirst(\" hello WORLD \");\n * // ➔ \" Hello world\"\n * capitalizeFirst(\" hello WORLD \", { trim: true });\n * // ➔ \"Hello world\"\n * capitalizeFirst(\"FOO\", { lowerCaseNextRest: false });\n * // ➔ \"FOO\"\n * capitalizeFirst(\" foo BAR \", { trim: true, lowerCaseNextRest: false });\n * // ➔ \"Foo BAR\"\n * ```\n * #### ℹ️ If null, undefined, or not a valid string input, return `\"\"`.\n * ```ts\n * capitalizeFirst(123);\n * capitalizeFirst(null);\n * capitalizeFirst(undefined);\n * // ➔ \"\"\n * ```\n */\nexport const capitalizeFirst = (\n string: string | null | undefined,\n options: CapitalizeFirstOptions = {\n lowerCaseNextRest: true,\n trim: false\n }\n): string => {\n if (!isNonEmptyString(string)) return \"\";\n\n if (!isPlainObject(options)) {\n options = {};\n }\n\n const lowerCaseNextRest = options.lowerCaseNextRest !== false;\n const trim = options.trim === true;\n\n if (trim) string = string.trim();\n\n return (\n (string[0] ? string[0].toUpperCase() : \"\") +\n (lowerCaseNextRest ? string.slice(1).toLowerCase() : string.slice(1))\n );\n};\n","import { isPlainObject } from \"@/predicates/is/isPlainObject\";\nimport { isNonEmptyString } from \"@/predicates/is/isNonEmptyString\";\n\ntype CapitalizeWordsOptions = {\n /** If `true`, removes leading and trailing spaces, default `false`.\n *\n * @default false\n */\n trim?: boolean;\n /** If `true`, collapses multiple spaces **between words** into a single space (while preserving leading/trailing spaces), default `false`.\n *\n * @default false\n */\n collapseSpaces?: boolean;\n};\n\n/** ----------------------------------------------------------\n * * ***Utility: `capitalizeWords`.***\n * ----------------------------------------------------------\n * **Capitalizes the first letter of each word in a string while converting the rest to lowercase.**\n * @param {string | null | undefined} value\n * ***The input string to be processed.***\n * - If `null` or `undefined`, returns an empty-string (`\"\"`).\n * @param {CapitalizeWordsOptions} [options]\n * ***Optional settings to control the output:***\n * - `trim`: If `true`, removes leading and trailing spaces, defaultValue: `false`.\n * - `collapseSpaces`: If `true`, collapses multiple spaces **between words** into a single space (while preserving leading/trailing spaces), defaultValue: `false`.\n * @returns {string} A new string where each word starts with an uppercase letter\n * and the remaining letters are lowercase.\n * - If `value` is `empty`, `null`, or `undefined`, returns an `empty-string`.\n * @example\n * ```ts\n * capitalizeWords(\" hello world \");\n * // ➔ \" Hello World \"\n * capitalizeWords(\" hello world \", { trim: true });\n * // ➔ \"Hello World\"\n * capitalizeWords(\" hello world \", { collapseSpaces: true });\n * // ➔ \" Hello World \"\n * capitalizeWords(\" hello world \", { trim: true, collapseSpaces: true });\n * // ➔ \"Hello World\"\n * ```\n * #### ℹ️ If null, undefined, or not a valid string input, return \"\".\n * ```ts\n * capitalizeWords(123);\n * capitalizeWords(null);\n * capitalizeWords(undefined);\n * // ➔ \"\"\n * ```\n */\nexport const capitalizeWords = (\n value: string | null | undefined,\n options: CapitalizeWordsOptions = {\n collapseSpaces: false,\n trim: false\n }\n): string => {\n if (!isNonEmptyString(value)) return \"\";\n\n let result = value;\n\n if (!isPlainObject(options)) {\n options = {};\n }\n\n const collapseSpaces = options.collapseSpaces === true;\n const trim = options.trim === true;\n\n if (trim) {\n result = result.trim();\n }\n\n if (collapseSpaces) {\n const leadingSpaces = result.match(/^\\s*/)?.[0] ?? \"\";\n const trailingSpaces = result.match(/\\s*$/)?.[0] ?? \"\";\n result = result.trim().replace(/\\s+/g, \" \");\n result = `${leadingSpaces}${result}${trailingSpaces}`;\n }\n\n return result\n .toLowerCase()\n .split(\" \")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \");\n};\n","import type { Extends } from \"@rzl-zone/ts-types-plus\";\nimport { isString } from \"@/predicates/is/isString\";\nimport { isEmptyString } from \"@/predicates/is/isEmptyString\";\n\n/** ----------------------------------------------------------\n * * ***Utility: `stripHtmlTags`.***\n * ----------------------------------------------------------\n * **This function removes valid HTML tags (including nested and self-closing ones)\n * by replacing them with spaces, then collapses multiple whitespaces into a single space.**\n * - **It handles the following cases:**\n * - If the input is not a string (`null`, `undefined`, or any non-string), it is returned as undefined.\n * - If the input is an empty or whitespace-only string, it returns an empty string (`\"\"`).\n * - Otherwise, it returns the cleaned string with tags removed and normalized whitespace.\n * @template T - Input string type (string | null | undefined).\n * @param {string | null | undefined} input - A string potentially containing HTML tags.\n * @returns {string | undefined} Cleaned string if input is string, or original input otherwise.\n * @example\n * stripHtmlTags(\"<p>Hello</p>\");\n * // ➔ \"Hello\"\n * stripHtmlTags(\"<div><b>Bold</b> text</div>\");\n * // ➔ \"Bold text\"\n * stripHtmlTags(\"Line<br/>Break\");\n * // ➔ \"Line Break\"\n * stripHtmlTags(\"2 < 5 and 5 > 2\");\n * // ➔ \"2 < 5 and 5 > 2\"\n * stripHtmlTags(\"\");\n * // ➔ \"\"\n * stripHtmlTags(\" \");\n * // ➔ \"\"\n * stripHtmlTags(null);\n * // ➔ undefined\n * stripHtmlTags(undefined);\n * // ➔ undefined\n */\nexport function stripHtmlTags(input: string): string;\nexport function stripHtmlTags<T>(\n input: T\n): Extends<string, T> extends true ? string | undefined : undefined;\nexport function stripHtmlTags(input: unknown) {\n if (!isString(input)) {\n return undefined;\n }\n\n if (isEmptyString(input)) {\n return \"\";\n }\n\n // return input.replace(/<[^>]*>/g, \"\");\n const stripped = input.replace(/<\\/?[a-zA-Z][^<>]*\\/?>/g, \" \").trim();\n\n const cleaned = stripped.replace(/\\s+/g, \" \").trim();\n\n return cleaned;\n}\n","import { isNonEmptyString } from \"@/predicates/is/isNonEmptyString\";\n\n/** ----------------------------------------------------------\n * * ***Utility: `getInitialsName`.***\n * ----------------------------------------------------------\n * **Extracts initials from the given name string.**\n * - **Behavior:**\n * - For names with two or more words, returns the first letter of the first and second words.\n * - For a single word with 2+ characters, returns the first two letters.\n * - For a single character, returns that character.\n * - For `empty`, `null`, `undefined` or `whitespace-only input`, returns an empty string (`\"\"`).\n * @param {string | null | undefined} name - The name to extract initials from.\n * @returns {string} The extracted initials (e.g., \"JD\" for \"John Doe\").\n * @example\n * getInitialsName(\"Alice\"); // ➔ \"AL\"\n * getInitialsName(\"John Doe\"); // ➔ \"JD\"\n * getInitialsName(\" Bob Marley \"); // ➔ \"BM\"\n * getInitialsName(\"John Ronald Donal\"); // ➔ \"JR\"\n * getInitialsName(\"Lord John Doe Moe\"); // ➔ \"LJ\"\n * getInitialsName(\"X\"); // ➔ \"X\"\n * getInitialsName(\"\"); // ➔ \"\" (empty string)\n * getInitialsName(\" \"); // ➔ \"\" (empty string)\n * getInitialsName(null); // ➔ \"\" (null input)\n * getInitialsName(undefined); // ➔ \"\" (undefined input)\n */\nexport const getInitialsName = (name: string | null | undefined): string => {\n if (!isNonEmptyString(name)) return \"\"; // Handle empty string case\n\n // Trim spaces and remove duplicate spaces\n name = name.replace(/\\s+/g, \" \").trim();\n\n const nameParts = name.split(\" \");\n\n if (nameParts.length > 1) {\n if (!(nameParts[0] && nameParts[1] && nameParts[1][0])) return \"\";\n\n // First letter of first and second words\n return (nameParts[0][0] + nameParts[1][0]).toUpperCase();\n }\n\n return name.length > 1\n ? name.substring(0, 2).toUpperCase()\n : // First two letters for single-word names\n (name[0]?.toUpperCase() ?? \"\");\n};\n","import { isNumber } from \"@/predicates/is/isNumber\";\nimport { isString } from \"@/predicates/is/isString\";\nimport { getPreciseType } from \"@/predicates/type/getPreciseType\";\n\n/** ----------------------------------------------------------\n * * ***Utility: `replaceAt`.***\n * ----------------------------------------------------------\n * **Replaces exactly one character at the specified index in the original string\n * with the provided `replaceTo` string.**\n * - **Behavior:**\n * - If `replaceTo` has more than one character,\n * the result will expand accordingly.\n * @param {number} index - The starting index where the replacement should occur.\n * @param {string} originalString - The original string to modify.\n * @param {string} replaceTo - The string to insert at the specified index.\n * @returns {string} The modified string with the replacement applied.\n * @example\n * replaceAt(3, \"hello\", \"X\");\n * // ➔ \"helXo\"\n * replaceAt(1, \"world\", \"AB\");\n * // ➔ \"wABrld\"\n * replaceAt(0, \"cat\", \"br\");\n * // ➔ \"brat\"\n * replaceAt(2, \"12345\", \"-\");\n * // ➔ \"12-45\"\n * replaceAt(4, \"ABCDE\", \"Z\");\n * // ➔ \"ABCDZ\"\n * // ❌ Examples that throw:\n * replaceAt(10, \"short\", \"X\");\n * // ➔ ❌ RangeError: First parameter (`index`) is out of range from second parameter `originalString`.\n * replaceAt(-1, \"test\", \"X\");\n * // ➔ ❌ RangeError: First parameter (`index`) is out of range from second parameter `originalString`.\n * replaceAt(\"1\", \"test\", \"X\");\n * // ➔ ❌ TypeError: First parameter `index` must be of type `number`, second parameter `originalString` and third parameter `replaceTo` must be of type `string`, but received: \"['index': `string`,...].\"\n * replaceAt(2, null, \"X\");\n * // ➔ ❌ TypeError: First parameter `index` must be of type `number`, second parameter `originalString` and third parameter `replaceTo` must be of type `string`, but received: \"['index': `string`,...].\"\n */\nexport const replaceAt = (\n index: number,\n originalString: string,\n replaceTo: string\n): string => {\n if (!isNumber(index) || !isString(replaceTo) || !isString(originalString)) {\n throw new TypeError(\n `First parameter (\\`index\\`) must be of type \\`number\\`, second parameter (\\`originalString\\`) and third parameter (\\`replaceTo\\`) must be of type \\`string\\`, but received: \"['index': \\`${getPreciseType(\n index\n )}\\`, 'originalString': \\`${getPreciseType(\n originalString\n )}\\`, 'replaceTo': \\`${getPreciseType(replaceTo)}\\`]\".`\n );\n }\n\n // Handle edge cases\n if (index < 0 || index >= originalString.length) {\n throw new RangeError(\n \"First parameter (`index`) is out of range from second parameter (`originalString`).\"\n );\n }\n\n return (\n originalString.slice(0, index) + // Extract before the index\n replaceTo + // Insert replacement\n originalString.slice(index + 1) // Extract after replacement\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,mBACX,QACA,UAAkC;CAChC,mBAAmB;CACnB,MAAM;CACP,KACU;CACX,IAAI,CAACA,yCAAiB,OAAO,EAAE,OAAO;CAEtC,IAAI,CAACC,sCAAc,QAAQ,EACzB,UAAU,EAAE;CAGd,MAAM,oBAAoB,QAAQ,sBAAsB;CAGxD,IAFa,QAAQ,SAAS,MAEpB,SAAS,OAAO,MAAM;CAEhC,QACG,OAAO,KAAK,OAAO,GAAG,aAAa,GAAG,OACtC,oBAAoB,OAAO,MAAM,EAAE,CAAC,aAAa,GAAG,OAAO,MAAM,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACfxE,MAAa,mBACX,OACA,UAAkC;CAChC,gBAAgB;CAChB,MAAM;CACP,KACU;CACX,IAAI,CAACC,yCAAiB,MAAM,EAAE,OAAO;CAErC,IAAI,SAAS;CAEb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CAAS,MAAM,IAAI,CAACC,iCAAS,UAAU,IAAI,CAACA,iCAAS,eAAe,EACvE,MAAM,IAAI,UACR,4LAA4LC,uCAC1L,MACD,CAAC,0BAA0BA,uCAC1B,eACD,CAAC,qBAAqBA,uCAAe,UAAU,CAAC,OAClD;CAIH,IAAI,QAAQ,KAAK,SAAS,eAAe,QACvC,MAAM,IAAI,WACR,sFACD;CAGH,OACE,eAAe,MAAM,GAAG,MAAM,GAC9B,YACA,eAAe,MAAM,QAAQ,EAAE"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* ========================================================================
|
|
3
|
+
* @rzl-zone/utils-js
|
|
4
|
+
* ------------------------------------------------------------------------
|
|
5
|
+
* Version: `3.12.1-beta.1`
|
|
6
|
+
* Author: `Rizalvin Dwiky <rizalvindwiky@gmail.com>`
|
|
7
|
+
* Repository: `https://github.com/rzl-zone/rzl-zone/tree/main/packages/utils-js`
|
|
8
|
+
* ========================================================================
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { a as normalizeString, c as toPascalCaseSpace, d as toKebabCase, f as toDotCase, g as capitalizeFirst, h as capitalizeWords, i as removeSpaces, l as toPascalCase, m as slugify, n as getInitialsName, o as normalizeSpaces, p as toCamelCase, r as stripHtmlTags, s as toSnakeCase, t as replaceAt, u as toLowerCase } from "../index-DsGxO31H.cjs";
|
|
12
|
+
export { capitalizeFirst, capitalizeWords, getInitialsName, normalizeSpaces, normalizeString, removeSpaces, replaceAt, slugify, stripHtmlTags, toCamelCase, toDotCase, toKebabCase, toLowerCase, toPascalCase, toPascalCaseSpace, toSnakeCase };
|