@zuzjs/core 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,46 +1,36 @@
1
- export declare const setCookie: (key: string, value: any, expiry?: number, host?: string) => string | undefined;
2
- export declare const getCookie: (key: string) => string | {
3
- [key: string]: string;
4
- } | null;
5
- export declare const removeCookie: (key: string) => void;
6
- export declare const uuid: (len?: number) => string;
7
- export declare const isEmail: (e: string) => boolean;
8
- export declare const formatBytes: (bytes: number) => string;
9
- export declare const formatSeconds: (n: number) => string;
10
- export declare const formatTime: (time: (string | number)[]) => string;
11
- export declare const createElem: (tag: string, classes?: string[], attrs?: {
12
- [key: string]: string;
13
- }) => HTMLElement;
14
- export type ElementNode = {
15
- tag: string;
16
- id?: string;
17
- text?: string;
18
- classes?: string[];
19
- attrs?: {
20
- [x: string]: string;
21
- };
22
- childs?: ElementNode[];
1
+ import { AxiosProgressEvent } from "axios";
2
+ import { dynamicObject, FormatNumberParams, sortOptions } from "./types";
3
+ export declare const __SALT: string;
4
+ export { default as "_" } from "./withGlobals";
5
+ export declare const numberInRange: (min: number, max: number) => number;
6
+ export declare const toHash: (n: number, len?: number, SALT?: string | null) => string;
7
+ export declare const fromHash: (str: string, SALT?: string | null) => number;
8
+ export declare const MD5: (str: string) => string;
9
+ export declare const uuid: (len: number) => string;
10
+ export declare const ucfirst: (o: any) => string;
11
+ export declare const urldecode: (str: string) => string;
12
+ export declare const urlencode: (str: string) => string;
13
+ export declare const pluralize: (word: string, count: number) => string;
14
+ export declare const isHexColor: (color: string) => boolean;
15
+ export declare const isRgbaColor: (color: string) => boolean;
16
+ export declare const isHslColor: (color: string) => boolean;
17
+ export declare const isColor: (color: string) => boolean;
18
+ export declare const hexToRgba: (hex: string, alpha?: number) => string;
19
+ export declare const removeDuplicates: <T>(array: T[]) => T[];
20
+ export declare const withPost: <T>(uri: string, data: dynamicObject | FormData, timeout?: number, ignoreKind?: boolean, onProgress?: (ev: AxiosProgressEvent) => void) => Promise<T>;
21
+ export declare const withGet: <T>(uri: string, timeout?: number, ignoreKind?: boolean) => Promise<T>;
22
+ export declare const withTime: (fun: (...args: any[]) => any) => {
23
+ result: any;
24
+ executionTime: number;
23
25
  };
24
- export declare const createElems: (list: ElementNode[]) => Node[];
25
- export declare const getPlatform: () => "MAC" | "WIN" | "UNKNOWN";
26
- export declare const findParent: (node: HTMLElement, classes: string[], depth?: number) => HTMLElement | null;
27
- export declare const ucfirst: (str: string) => string;
28
- /**
29
- * HTTP Requests
30
- */
31
- export declare const withRest: (uri: string, data: object, timeout: number | undefined, fd: object, progress?: Function, bearer?: string) => Promise<unknown>;
32
- /**
33
- * Extends Object.prototype adding,
34
- * @function isNull
35
- * @function equals
36
- * @function isString
37
- * @function isNumber
38
- * @function isObject
39
- * @function isArray
40
- * @function isEmpty
41
- * @function isNotEmpty
42
- * @function isEmail
43
- * @function isUrl
44
- *
45
- */
46
- export declare const extendGlobals: () => void;
26
+ export declare const time: (stamp?: number, format?: string) => string;
27
+ export declare const timeSince: (stamp: number) => string;
28
+ export declare const arrayRand: (arr: any[]) => any;
29
+ export declare const formatNumber: ({ number, locale, style, decimal, currency }: FormatNumberParams) => string;
30
+ export declare const formatSize: (bytes: number | string) => string;
31
+ export declare const copyToClipboard: (text: string) => Promise<unknown>;
32
+ export declare const natsort: (options?: sortOptions) => (a: string | number, b: string | number) => number;
33
+ export declare const camelCase: (str: string, ucf?: boolean) => string;
34
+ export declare const camelCaseToDash: (str: string) => string;
35
+ export declare const clamp: (value: number, min: number, max: number) => number;
36
+ export declare const slugify: (text: string, separator?: string) => string;
package/dist/index.js CHANGED
@@ -1,115 +1,96 @@
1
- import Hashids from "hashids";
2
- import { nanoid } from "nanoid";
3
- import Cookies from 'js-cookie';
4
- import axios from 'axios';
5
- const _Hashids = new Hashids('', 4);
6
- export const setCookie = (key, value, expiry, host) => Cookies.set(key, value, { expires: expiry || 7, domain: host || window.location.host });
7
- export const getCookie = (key) => key == `` ? Cookies.get() : Cookies.get(key) || null;
8
- export const removeCookie = (key) => Cookies.remove(key);
9
- export const uuid = (len = 11) => nanoid(len);
10
- export const isEmail = (e) => {
11
- let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
12
- return reg.test(e);
13
- };
14
- export const formatBytes = (bytes) => {
15
- var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
16
- if (bytes == 0)
17
- return '0 Byte';
18
- var i = Math.floor(Math.log(bytes) / Math.log(1024)), nx = bytes / Math.pow(1024, i);
19
- return nx.toFixed(2) + ' ' + sizes[i];
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
20
4
  };
21
- export const formatSeconds = (n) => {
22
- let d = new Date(n * 1000).toISOString().slice(11, 19);
23
- return d.indexOf("00:") > -1 ? d.replace("00:", "") : d;
24
- };
25
- export const formatTime = (time) => {
26
- let _time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
27
- let __ = [];
28
- if (_time.length > 1) { // If time format correct
29
- __ = _time.slice(1); // Remove full string match value
30
- __[5] = +_time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
31
- __[0] = +_time[0] % 12 || 12;
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.slugify = exports.clamp = exports.camelCaseToDash = exports.camelCase = exports.natsort = exports.copyToClipboard = exports.formatSize = exports.formatNumber = exports.arrayRand = exports.timeSince = exports.time = exports.withTime = exports.withGet = exports.withPost = exports.removeDuplicates = exports.hexToRgba = exports.isColor = exports.isHslColor = exports.isRgbaColor = exports.isHexColor = exports.pluralize = exports.urlencode = exports.urldecode = exports.ucfirst = exports.uuid = exports.MD5 = exports.fromHash = exports.toHash = exports.numberInRange = exports["_"] = exports.__SALT = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const hashids_1 = __importDefault(require("hashids"));
9
+ const js_cookie_1 = __importDefault(require("js-cookie"));
10
+ const md5_1 = __importDefault(require("md5"));
11
+ const moment_1 = __importDefault(require("moment"));
12
+ const regexps_1 = require("./regexps");
13
+ const types_1 = require("./types");
14
+ exports.__SALT = `zuzjs-core`;
15
+ var withGlobals_1 = require("./withGlobals");
16
+ Object.defineProperty(exports, "_", { enumerable: true, get: function () { return __importDefault(withGlobals_1).default; } });
17
+ const numberInRange = (min, max) => {
18
+ return Math.floor(Math.random() * (max - min + 1)) + min;
19
+ };
20
+ exports.numberInRange = numberInRange;
21
+ const toHash = (n, len = 6, SALT = null) => new hashids_1.default(SALT || exports.__SALT, len).encode(n);
22
+ exports.toHash = toHash;
23
+ const fromHash = (str, SALT = null) => {
24
+ try {
25
+ const n = new hashids_1.default(SALT || exports.__SALT, +process.env.HASHIDS_LENGTH).decode(str);
26
+ return n.length >= 0 ? Number(n[0]) : 0;
32
27
  }
33
- return __.join('');
34
- };
35
- export const createElem = (tag, classes = [], attrs = {}) => {
36
- for (var el = window.document.createElement(tag), i = 0; i < classes.length; i++)
37
- "" != classes[i] && el.classList.add(classes[i]);
38
- if (Object.keys(attrs).length > 0)
39
- Object.keys(attrs)
40
- .map((k) => el.setAttribute(k, attrs[k]));
41
- return el;
42
- };
43
- export const createElems = (list) => {
44
- let r = [], o;
45
- list.map((item) => {
46
- if (item.tag) {
47
- o = createElem(item.tag, item.classes || [], item.attrs || {});
48
- if (item.childs && item.childs.length > 0) {
49
- let c = createElems(item.childs);
50
- c.map((f) => o.appendChild(f));
51
- }
52
- else if (item.text && "" != item.text) {
53
- // o = document.createTextNode(item.text)
54
- o.textContent = item.text;
55
- }
56
- r.push(o);
57
- }
58
- });
59
- return r;
60
- };
61
- export const getPlatform = () => {
62
- return undefined !== typeof window ?
63
- window.navigator.platform.toUpperCase().indexOf("MAC") > -1 ? `MAC` : `WIN` : `UNKNOWN`;
64
- };
65
- export const findParent = (node, classes, depth = 1) => {
66
- var n, i = node.parentNode, o = 0, a = 0;
67
- if (null === i || !i.classList || i.classList.length == 0)
68
- return null;
69
- for (n = classes.length; a < n; ++a)
70
- i.classList.contains(classes[a]) && (o += 1);
71
- return o === n ? i : 0 < depth ? findParent(i, classes, depth - 1) : null;
72
- };
73
- export const ucfirst = (str) => {
74
- return str = str.trim(),
75
- str.charAt(0).toUpperCase() + str.substring(1);
76
- };
77
- const buildFormData = (data) => {
78
- var formData = new FormData();
79
- var _data = Cookies.get();
80
- Object.keys(_data).map(k => formData.append(k, _data[k]));
81
- Object.keys(data).filter(x => x != 'files').map(k => formData.append(k, data[k]));
82
- if ('files' in data)
83
- [data['files']].map((f) => formData.append('files[]', f));
84
- return formData;
85
- };
86
- /**
87
- * HTTP Requests
88
- */
89
- export const withRest = async (uri, data, timeout = 60, fd, progress, bearer = `__ha`) => {
90
- var Bearer = getCookie(bearer) || `${uuid(8)}^${uuid(8)}`;
91
- var isWindow = typeof window !== 'undefined';
92
- var cancelToken = null;
93
- if (isWindow) {
94
- window.__restToken = axios.CancelToken.source();
95
- cancelToken = window.__restToken?.token;
28
+ catch (e) {
29
+ return 0;
30
+ }
31
+ };
32
+ exports.fromHash = fromHash;
33
+ const MD5 = (str) => (0, md5_1.default)(str);
34
+ exports.MD5 = MD5;
35
+ const uuid = (len) => (0, exports.toHash)((0, exports.numberInRange)(11111111111, 999999999999));
36
+ exports.uuid = uuid;
37
+ const ucfirst = (o) => `${o.charAt(0).toUpperCase()}${o.substring(1, o.length)}`;
38
+ exports.ucfirst = ucfirst;
39
+ const urldecode = (str) => decodeURIComponent(str.replace(/\+/g, '%20'));
40
+ exports.urldecode = urldecode;
41
+ const urlencode = (str) => encodeURIComponent(str);
42
+ exports.urlencode = urlencode;
43
+ const pluralize = (word, count) => `${word}${count !== 1 ? 's' : ''}`;
44
+ exports.pluralize = pluralize;
45
+ const isHexColor = (color) => regexps_1.hexColorRegex.test(color);
46
+ exports.isHexColor = isHexColor;
47
+ const isRgbaColor = (color) => regexps_1.rgbaColorRegex.test(color);
48
+ exports.isRgbaColor = isRgbaColor;
49
+ const isHslColor = (color) => regexps_1.hslColorRegex.test(color);
50
+ exports.isHslColor = isHslColor;
51
+ // Function to validate a color string
52
+ const isColor = (color) => (0, exports.isHexColor)(color) || (0, exports.isRgbaColor)(color) || (0, exports.isHslColor)(color);
53
+ exports.isColor = isColor;
54
+ const hexToRgba = (hex, alpha = 1) => {
55
+ // Remove the hash symbol if present
56
+ hex = hex.replace(/^#/, '');
57
+ // If shorthand hex (#RGB), expand it to full form (#RRGGBB)
58
+ if (hex.length === 3) {
59
+ hex = hex.split('').map(char => char + char).join('');
96
60
  }
97
- if (fd) {
61
+ // Convert to integer values for RGB
62
+ const bigint = parseInt(hex, 16);
63
+ const r = (bigint >> 16) & 255;
64
+ const g = (bigint >> 8) & 255;
65
+ const b = bigint & 255;
66
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`;
67
+ };
68
+ exports.hexToRgba = hexToRgba;
69
+ const removeDuplicates = (array) => {
70
+ return array.reduce((accumulator, currentValue) => {
71
+ if (!accumulator.includes(currentValue)) {
72
+ accumulator.push(currentValue);
73
+ }
74
+ return accumulator;
75
+ }, []);
76
+ };
77
+ exports.removeDuplicates = removeDuplicates;
78
+ const withPost = async (uri, data, timeout = 60, ignoreKind = false, onProgress) => {
79
+ const _cookies = js_cookie_1.default.get();
80
+ if (data instanceof FormData) {
81
+ for (const c in _cookies) {
82
+ data.append(c, _cookies[c]);
83
+ }
98
84
  return new Promise((resolve, reject) => {
99
- axios({
100
- method: "post",
85
+ (0, axios_1.default)({
86
+ method: 'post',
101
87
  url: uri,
102
- data: buildFormData(data),
103
- timeout: 1000 * timeout,
104
- cancelToken: cancelToken,
88
+ data: data,
89
+ timeout: timeout * 1000,
105
90
  headers: {
106
91
  'Content-Type': 'multipart/form-data',
107
- 'Authorization': `Bearer ${Bearer}`
108
92
  },
109
- onUploadProgress: ev => {
110
- //TODO: Add progress
111
- // if(progress) progress(ev.)
112
- }
93
+ onUploadProgress: ev => onProgress && onProgress(ev)
113
94
  })
114
95
  .then(resp => {
115
96
  if (resp.data && "kind" in resp.data) {
@@ -123,57 +104,269 @@ export const withRest = async (uri, data, timeout = 60, fd, progress, bearer = `
123
104
  });
124
105
  }
125
106
  return new Promise((resolve, reject) => {
126
- axios.post(uri, {
127
- ...Cookies.get(),
107
+ axios_1.default.post(uri, {
128
108
  ...data,
129
- __ustmp: new Date().getTime() / 1000
109
+ ..._cookies,
110
+ __stmp: new Date().getTime() / 1000
130
111
  }, {
131
112
  timeout: 1000 * timeout,
132
113
  headers: {
133
114
  'Content-Type': 'application/json',
134
- 'Authorization': `Bearer ${Bearer}`
135
- },
136
- cancelToken: cancelToken
115
+ }
137
116
  })
138
117
  .then(resp => {
139
- if (resp.data && "kind" in resp.data) {
118
+ if (resp.data && (ignoreKind || ("kind" in resp.data))) {
119
+ resolve(resp.data);
120
+ }
121
+ else {
122
+ reject(resp.data);
123
+ }
124
+ })
125
+ .catch(err => {
126
+ if (err?.response?.data)
127
+ reject(err.response.data);
128
+ else
129
+ reject(err.code && err.code == `ERR_NETWORK` ? { error: err.code, message: navigator.onLine ? `Unable to connect to the server. It may be temporarily down.` : `Network error: Unable to connect. Please check your internet connection and try again.` } : err);
130
+ });
131
+ });
132
+ };
133
+ exports.withPost = withPost;
134
+ const withGet = async (uri, timeout = 60, ignoreKind = false) => {
135
+ return new Promise((resolve, reject) => {
136
+ axios_1.default
137
+ .get(uri, { timeout: timeout * 1000 })
138
+ .then((resp) => {
139
+ if (resp.data && (ignoreKind || "kind" in resp.data)) {
140
140
  resolve(resp.data);
141
141
  }
142
142
  else {
143
143
  reject(resp.data);
144
144
  }
145
145
  })
146
- .catch(err => reject(err));
146
+ .catch((err) => {
147
+ if (err?.response?.data)
148
+ reject(err.response.data);
149
+ else
150
+ reject(err.code === `ERR_NETWORK`
151
+ ? {
152
+ error: err.code,
153
+ message: navigator.onLine
154
+ ? `Unable to connect to the server. It may be temporarily down.`
155
+ : `Network error: Unable to connect. Please check your internet connection and try again.`,
156
+ }
157
+ : err);
158
+ });
147
159
  });
148
160
  };
149
- /**
150
- * Extends Object.prototype adding,
151
- * @function isNull
152
- * @function equals
153
- * @function isString
154
- * @function isNumber
155
- * @function isObject
156
- * @function isArray
157
- * @function isEmpty
158
- * @function isNotEmpty
159
- * @function isEmail
160
- * @function isUrl
161
- *
162
- */
163
- export const extendGlobals = () => {
164
- Object.prototype.isNull = function () { return this === null; };
165
- Object.prototype.equals = function (v) { return this === v; };
166
- Object.prototype.isString = function () { return typeof this == `string`; };
167
- Object.prototype.isNumber = function () { return /^[+-]?\d+(\.\d+)?$/.test(this); };
168
- Object.prototype.isObject = function () { return typeof this == `object` && !Array.isArray(this) && this !== null; };
169
- Object.prototype.isArray = function () { return Array.isArray(this); };
170
- Object.prototype.isEmpty = function () {
171
- if (Array.isArray(this))
172
- return this.length === 0;
173
- else if (`object` === typeof this)
174
- return Object.keys(this).length == 0;
175
- else
176
- return this == "" || this.length == 0;
161
+ exports.withGet = withGet;
162
+ const withTime = (fun) => {
163
+ const start = new Date().getTime();
164
+ const result = fun();
165
+ const end = new Date().getTime();
166
+ return {
167
+ result,
168
+ executionTime: end - start
177
169
  };
178
170
  };
179
- extendGlobals();
171
+ exports.withTime = withTime;
172
+ const time = (stamp, format) => {
173
+ return stamp ?
174
+ moment_1.default.unix(+stamp / 1000).format(format || `YYYY-MM-DD HH:mm:ss`)
175
+ : (0, moment_1.default)().format(format || `YYYY-MM-DD HH:mm:ss`);
176
+ };
177
+ exports.time = time;
178
+ const timeSince = (stamp) => (0, moment_1.default)(stamp).fromNow();
179
+ exports.timeSince = timeSince;
180
+ const arrayRand = (arr) => arr[Math.floor(Math.random() * arr.length)];
181
+ exports.arrayRand = arrayRand;
182
+ const formatNumber = ({ number, locale = 'en-US', style = `decimal`, decimal = 2, currency }) => {
183
+ if (style === 'currency' && !currency) {
184
+ throw new TypeError('Currency code is required with currency style.');
185
+ }
186
+ if (currency) {
187
+ const { code, style: currencyStyle, symbol } = currency;
188
+ const out = new Intl.NumberFormat(locale, {
189
+ style: `currency`,
190
+ currency: code,
191
+ currencyDisplay: currencyStyle,
192
+ minimumFractionDigits: +number % 1 > 0 ? decimal : 0,
193
+ maximumFractionDigits: +number % 1 > 0 ? decimal : 0
194
+ }).format(+number);
195
+ return symbol ? out.replace(new RegExp(`\\${code}`, 'g'), symbol) : out;
196
+ }
197
+ return new Intl.NumberFormat(locale, {
198
+ style,
199
+ minimumFractionDigits: +number % 1 > 0 ? 2 : 0,
200
+ maximumFractionDigits: +number % 1 > 0 ? 2 : 0
201
+ }).format(+number);
202
+ };
203
+ exports.formatNumber = formatNumber;
204
+ const formatSize = (bytes) => {
205
+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
206
+ const _bytes = `string` == typeof bytes ? parseFloat(bytes) : bytes;
207
+ if (_bytes == 0)
208
+ return '0 Byte';
209
+ const _i = Math.floor(Math.log(_bytes) / Math.log(1024));
210
+ const i = `string` == typeof _i ? parseInt(_i) : _i;
211
+ const nx = _bytes / Math.pow(1024, i);
212
+ return nx.toFixed(2) + ' ' + sizes[i];
213
+ };
214
+ exports.formatSize = formatSize;
215
+ const copyToClipboard = (text) => {
216
+ if (navigator.clipboard && navigator.clipboard.writeText) {
217
+ return navigator.clipboard.writeText(text);
218
+ }
219
+ else {
220
+ return new Promise((resolve, reject) => {
221
+ const textarea = document.createElement("textarea");
222
+ textarea.value = text;
223
+ textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge.
224
+ document.body.appendChild(textarea);
225
+ textarea.focus();
226
+ textarea.select();
227
+ try {
228
+ document.execCommand("copy");
229
+ resolve(`Copied to clipboard`);
230
+ }
231
+ catch (err) {
232
+ // console.error("Fallback: Oops, unable to copy", err);
233
+ reject(err);
234
+ }
235
+ document.body.removeChild(textarea);
236
+ });
237
+ }
238
+ };
239
+ exports.copyToClipboard = copyToClipboard;
240
+ const natsort = (options = {
241
+ direction: types_1.SORT.Asc,
242
+ caseSensitive: false,
243
+ }) => {
244
+ const ore = /^0/;
245
+ const sre = /\s+/g;
246
+ const tre = /^\s+|\s+$/g;
247
+ // unicode
248
+ const ure = /[^\x00-\x80]/;
249
+ // hex
250
+ const hre = /^0x[0-9a-f]+$/i;
251
+ // numeric
252
+ const nre = /(0x[\da-fA-F]+|(^[\+\-]?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?(?=\D|\s|$))|\d+)/g;
253
+ // datetime
254
+ const dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/; // tslint:disable-line
255
+ const GREATER = options.direction == types_1.SORT.Desc ? -1 : 1;
256
+ const SMALLER = -GREATER;
257
+ const _normalize = !options.caseSensitive
258
+ ? (s) => s.toString().toLowerCase().replace(tre, '')
259
+ : (s) => (`${s}`).replace(tre, '');
260
+ const _tokenize = (s) => {
261
+ return s.replace(nre, '\0$1\0')
262
+ .replace(/\0$/, '')
263
+ .replace(/^\0/, '')
264
+ .split('\0');
265
+ };
266
+ const _parse = (s, l) => {
267
+ return (!s.match(ore) || l === 1) &&
268
+ parseFloat(s)
269
+ || s.replace(sre, ' ').replace(tre, '')
270
+ || 0;
271
+ };
272
+ return function (a, b) {
273
+ const aa = _normalize(a);
274
+ const bb = _normalize(b);
275
+ if (!aa && !bb) {
276
+ return 0;
277
+ }
278
+ if (!aa && bb) {
279
+ return SMALLER;
280
+ }
281
+ if (aa && !bb) {
282
+ return GREATER;
283
+ }
284
+ const aArr = _tokenize(aa);
285
+ const bArr = _tokenize(bb);
286
+ // hex or date detection
287
+ const aHex = aa.match(hre);
288
+ const bHex = bb.match(hre);
289
+ const av = (aHex && bHex) ? parseInt(aHex[0], 16) : (aArr.length !== 1 && Date.parse(aa));
290
+ const bv = (aHex && bHex)
291
+ ? parseInt(bHex[0], 16)
292
+ : av && bb.match(dre) && Date.parse(bb) || null;
293
+ // try and sort Hex codes or Dates
294
+ if (bv) {
295
+ if (av === bv) {
296
+ return 0;
297
+ }
298
+ if (typeof av === 'number' && typeof bv === 'number' && av < bv) {
299
+ return SMALLER;
300
+ }
301
+ if (typeof av === 'number' && av > bv) {
302
+ return GREATER;
303
+ }
304
+ }
305
+ const al = aArr.length;
306
+ const bl = bArr.length;
307
+ // handle numeric strings and default strings
308
+ for (let i = 0, l = Math.max(al, bl); i < l; i += 1) {
309
+ const af = _parse(aArr[i] || '', al);
310
+ const bf = _parse(bArr[i] || '', bl);
311
+ if (isNaN(af) !== isNaN(bf)) {
312
+ return isNaN(af) ? GREATER : SMALLER;
313
+ }
314
+ if (ure.test(af + bf) && af.localeCompare) {
315
+ const comp = af.localeCompare(bf);
316
+ if (comp > 0) {
317
+ return GREATER;
318
+ }
319
+ if (comp < 0) {
320
+ return SMALLER;
321
+ }
322
+ if (i === l - 1) {
323
+ return 0;
324
+ }
325
+ }
326
+ if (af < bf) {
327
+ return SMALLER;
328
+ }
329
+ if (af > bf) {
330
+ return GREATER;
331
+ }
332
+ if (`${af}` < `${bf}`) {
333
+ return SMALLER;
334
+ }
335
+ if (`${af}` > `${bf}`) {
336
+ return GREATER;
337
+ }
338
+ }
339
+ return 0;
340
+ };
341
+ };
342
+ exports.natsort = natsort;
343
+ const camelCase = (str, ucf = false) => {
344
+ return str
345
+ .toLowerCase()
346
+ .split(/[^a-zA-Z0-9]+/) // Split by any non-alphanumeric character
347
+ .map((word, index) => index === 0
348
+ ? ucf ? (0, exports.ucfirst)(word) : word
349
+ : (0, exports.ucfirst)(word))
350
+ .join('');
351
+ };
352
+ exports.camelCase = camelCase;
353
+ const camelCaseToDash = (str) => str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
354
+ exports.camelCaseToDash = camelCaseToDash;
355
+ const clamp = (value, min, max) => {
356
+ return Math.min(Math.max(value, min), max);
357
+ };
358
+ exports.clamp = clamp;
359
+ const slugify = (text, separator = "-") => {
360
+ if (undefined == text) {
361
+ console.log(text, `is undefined`);
362
+ return ``;
363
+ }
364
+ return text
365
+ .normalize("NFKD") // Normalize accents (e.g., é → e)
366
+ .replace(/[\u0300-\u036f]/g, "") // Remove diacritic marks
367
+ .toLowerCase()
368
+ .replace(/[^a-z0-9\p{L}\p{N}]+/gu, separator) // Keep letters/numbers from all languages
369
+ .replace(new RegExp(`\\${separator}{2,}`, "g"), separator) // Remove duplicate separators
370
+ .replace(new RegExp(`^\\${separator}|\\${separator}$`, "g"), ""); // Trim separators from ends
371
+ };
372
+ exports.slugify = slugify;
@@ -0,0 +1,3 @@
1
+ export declare const hexColorRegex: RegExp;
2
+ export declare const rgbaColorRegex: RegExp;
3
+ export declare const hslColorRegex: RegExp;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hslColorRegex = exports.rgbaColorRegex = exports.hexColorRegex = void 0;
4
+ // Hex color regex (#RGB, #RRGGBB)
5
+ exports.hexColorRegex = /^#([A-Fa-f0-9]{3}){1,2}$/;
6
+ // RGBA color regex (rgba(255, 255, 255, 1))
7
+ exports.rgbaColorRegex = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*((0|1|0?\.\d+)\s*))?\)$/;
8
+ // HSL color regex (hsl(360, 100%, 100%))
9
+ exports.hslColorRegex = /^hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)$/;
package/dist/types.d.ts CHANGED
@@ -1,18 +1,22 @@
1
- declare global {
2
- interface Window {
3
- __restToken: any;
4
- }
5
- interface Object {
6
- isNull(): boolean;
7
- equals(v: any): boolean;
8
- isString(): boolean;
9
- isNumber(): boolean;
10
- isObject(): boolean;
11
- isArray(): boolean;
12
- isEmpty(): boolean;
13
- isNotEmpty(v: any): boolean;
14
- isEmail(v: any): boolean;
15
- isUrl(v: any): boolean;
16
- }
1
+ export type dynamicObject = {
2
+ [x: string]: any;
3
+ };
4
+ export interface FormatNumberParams {
5
+ number: number | string;
6
+ locale: string;
7
+ style?: `decimal` | `currency` | `percent`;
8
+ decimal?: number;
9
+ currency?: {
10
+ code: string;
11
+ style: `symbol` | `code` | `name`;
12
+ symbol?: string;
13
+ };
17
14
  }
18
- export {};
15
+ export declare enum SORT {
16
+ Asc = "ASC",
17
+ Desc = "DESC"
18
+ }
19
+ export type sortOptions = {
20
+ direction?: SORT;
21
+ caseSensitive?: boolean;
22
+ };
package/dist/types.js CHANGED
@@ -1 +1,8 @@
1
- export {};
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SORT = void 0;
4
+ var SORT;
5
+ (function (SORT) {
6
+ SORT["Asc"] = "ASC";
7
+ SORT["Desc"] = "DESC";
8
+ })(SORT || (exports.SORT = SORT = {}));
@@ -0,0 +1,25 @@
1
+ declare class withGlobals {
2
+ _: any;
3
+ constructor(value: any);
4
+ isTypeof(v: any): boolean;
5
+ isFunction(): boolean;
6
+ isArray(): boolean;
7
+ isNull(): boolean;
8
+ isString(): boolean;
9
+ isNumber(): boolean;
10
+ isObject(): boolean;
11
+ isEmpty(): boolean;
12
+ isEmail(): boolean;
13
+ isUrl(): boolean;
14
+ toLowerCase(): this;
15
+ equals(v: any): boolean;
16
+ ucfirst(): this;
17
+ formatString(v: string | number, ...vv: (string | number)[]): this;
18
+ camelCase(): this;
19
+ value(): any;
20
+ valueOf(): any;
21
+ toString(): string;
22
+ [Symbol.toPrimitive](hint: string): string | number | boolean;
23
+ }
24
+ declare const _: <T>(value: T) => withGlobals;
25
+ export default _;
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class withGlobals {
4
+ _;
5
+ constructor(value) {
6
+ this._ = value;
7
+ }
8
+ isTypeof(v) {
9
+ return typeof this._ === typeof v;
10
+ }
11
+ isFunction() {
12
+ return typeof this._ === "function";
13
+ }
14
+ isArray() {
15
+ return Array.isArray(this._);
16
+ }
17
+ isNull() {
18
+ return this._ === null;
19
+ }
20
+ isString() {
21
+ return typeof this._ === "string";
22
+ }
23
+ isNumber() {
24
+ return /^[+-]?\d+(\.\d+)?$/.test(this._);
25
+ }
26
+ isObject() {
27
+ return typeof this._ === "object" && !Array.isArray(this._) && this._ !== null;
28
+ }
29
+ isEmpty() {
30
+ if (Array.isArray(this._))
31
+ return this._.length === 0;
32
+ if (typeof this._ === "object" && this._ !== null)
33
+ return Object.keys(this._).length === 0;
34
+ return this._ === "" || String(this._).length === 0;
35
+ }
36
+ isEmail() {
37
+ return typeof this._ === "string" && /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(this._);
38
+ }
39
+ isUrl() {
40
+ return typeof this._ === "string" && /^(https?:\/\/)?(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(\/[^\s]*)?$/.test(this._);
41
+ }
42
+ toLowerCase() {
43
+ this._ = typeof this._ === "string" ? this._.toLowerCase() : String(this._).toLowerCase();
44
+ return this;
45
+ }
46
+ equals(v) { return this._ === v; }
47
+ ucfirst() {
48
+ this._ = typeof this._ === "string" ? this._.charAt(0).toUpperCase() + this._.slice(1) : this._;
49
+ return this;
50
+ }
51
+ formatString(v, ...vv) {
52
+ if (typeof this._ !== "string")
53
+ this._ = "";
54
+ const values = [v, ...vv];
55
+ this._ = this._.replace(/%(\d+)/g, (inp, index) => values[Number(index)]?.toString() || `%${index}`);
56
+ return this;
57
+ }
58
+ camelCase() {
59
+ this._ = typeof this._ === "string"
60
+ ? this._
61
+ .split(/[^a-zA-Z0-9]+/)
62
+ .map((word, index) => index === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1))
63
+ .join("")
64
+ : this._;
65
+ return this;
66
+ }
67
+ value() { return this._; }
68
+ valueOf() { return this._; }
69
+ toString() { return String(this._); }
70
+ [Symbol.toPrimitive](hint) {
71
+ if (hint === "number")
72
+ return Number(this._);
73
+ if (hint === "boolean")
74
+ return Boolean(this._);
75
+ return String(this._);
76
+ }
77
+ }
78
+ const _ = (value) => new withGlobals(value);
79
+ exports.default = _;
package/package.json CHANGED
@@ -1,16 +1,21 @@
1
1
  {
2
2
  "name": "@zuzjs/core",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "keywords": [
5
- "react",
5
+ "core",
6
6
  "zuz",
7
- "zuz.js"
7
+ "zuz.js",
8
+ "zuz orm",
9
+ "zuzjs"
8
10
  ],
9
- "description": "ZuzJS Core",
11
+ "description": "ZuzJS Core Library",
10
12
  "author": "Zuz.js Team <support@zuz.com.pk>",
11
13
  "license": "MIT",
12
- "type": "module",
14
+ "type": "commonjs",
13
15
  "main": "dist/index.js",
16
+ "bin": {
17
+ "zorm": "dist/bin.js"
18
+ },
14
19
  "exports": {
15
20
  ".": "./dist/index.js"
16
21
  },
@@ -18,17 +23,27 @@
18
23
  "dist"
19
24
  ],
20
25
  "scripts": {
21
- "dev": "tsc -d -w -p tsconfig.json",
22
- "build": "tsc -b tsconfig.json"
26
+ "dev": "tsc -d -w -p tsconfig.json"
23
27
  },
24
28
  "engines": {
25
29
  "node": ">=18.17.0"
26
30
  },
31
+ "sideEffects": [
32
+ "reflect-metadata"
33
+ ],
27
34
  "dependencies": {
28
- "axios": "1.6.8",
29
- "hashids": "2.3.0",
30
- "js-cookie": "3.0.5",
31
- "nanoid": "5.0.7",
32
- "prettier": "3.2.5"
35
+ "@types/hashids": "^2.0.1",
36
+ "@types/md5": "^2.3.5",
37
+ "axios": "^1.8.4",
38
+ "hashids": "^2.3.0",
39
+ "js-cookie": "^3.0.5",
40
+ "md5": "^2.3.0",
41
+ "moment": "^2.30.1",
42
+ "nanoid": "^5.1.0"
43
+ },
44
+ "devDependencies": {
45
+ "husky": "^9.1.7",
46
+ "ts-node": "^10.9.2",
47
+ "typescript": "^5.7.3"
33
48
  }
34
49
  }