dff-util 1.0.8 → 1.0.9

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/README.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  ```
4
4
  Http calls
5
+
6
+ **note: if url start with http then it ignoring API_BASE_URL, logic is given below.
7
+ >>>> url = url.startsWith('http') ? url : Http.API_BASE_URL + url;
8
+
5
9
  ```
6
10
 
7
11
  ## util
@@ -52,6 +56,40 @@ JwtVerify(data, secret);
52
56
  JwtValid(token);
53
57
  ```
54
58
 
59
+ #### JWT examples
60
+
61
+ ```
62
+ import { JwtEncode, JwtVerify, JwtDecode, JwtValid } from '../src/index';
63
+
64
+ const runJwtExamples = async () => {
65
+ const secret = 'your-secret-key';
66
+ const payload = { userId: '123', role: 'admin' };
67
+
68
+ // 1. Encode a JWT
69
+ const token = await JwtEncode(payload, secret, 3600);
70
+ console.log('Encoded JWT Token:', token);
71
+
72
+ // 2. Verify the JWT
73
+ try {
74
+ const verifiedPayload = await JwtVerify(token, secret);
75
+ console.log('Verified Payload:', verifiedPayload);
76
+ } catch (error: any) {
77
+ console.error('Verification Error:', error.message);
78
+ }
79
+
80
+ // 3. Decode the JWT without verification
81
+ const decodedPayload = JwtDecode(token);
82
+ console.log('Decoded Payload (without verification):', decodedPayload);
83
+
84
+ // 4. Check if the JWT is valid
85
+ const isValid = JwtValid(token);
86
+ console.log('Is JWT valid:', isValid);
87
+ };
88
+
89
+ runJwtExamples();
90
+
91
+ ```
92
+
55
93
  ## Constant Values
56
94
 
57
95
  ```
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ // bun run tests/jwt.ts
3
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
+ return new (P || (P = Promise))(function (resolve, reject) {
6
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
10
+ });
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ const index_1 = require("../src/index");
14
+ const runJwtExamples = () => __awaiter(void 0, void 0, void 0, function* () {
15
+ const secret = 'your-secret-key';
16
+ const payload = { userId: '123', role: 'admin' };
17
+ // 1. Encode a JWT
18
+ const token = yield (0, index_1.JwtEncode)(payload, secret, 3600);
19
+ console.log('Encoded JWT Token:', token);
20
+ // 2. Verify the JWT
21
+ try {
22
+ const verifiedPayload = yield (0, index_1.JwtVerify)(token, secret);
23
+ console.log('Verified Payload:', verifiedPayload);
24
+ }
25
+ catch (error) {
26
+ console.error('Verification Error:', error.message);
27
+ }
28
+ // 3. Decode the JWT without verification
29
+ const decodedPayload = (0, index_1.JwtDecode)(token);
30
+ console.log('Decoded Payload (without verification):', decodedPayload);
31
+ // 4. Check if the JWT is valid
32
+ const isValid = (0, index_1.JwtValid)(token);
33
+ console.log('Is JWT valid:', isValid);
34
+ });
35
+ runJwtExamples();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dff-util",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {
@@ -15,16 +15,15 @@
15
15
  ],
16
16
  "author": "DesignForFeature",
17
17
  "license": "ISC",
18
- "description": "DesignForFeature Utilies",
18
+ "description": "DesignForFeature Utilities",
19
19
  "devDependencies": {
20
- "@types/jsonwebtoken": "^9.0.6",
21
- "@types/node": "^20.14.10",
20
+ "@types/node": "^22.10.5",
22
21
  "@types/randomstring": "^1.3.0",
23
22
  "ts-node": "^10.9.2",
24
- "typescript": "^5.5.3"
23
+ "typescript": "^5.7.2"
25
24
  },
26
25
  "dependencies": {
27
- "jsonwebtoken": "^9.0.2",
26
+ "jose": "^5.9.6",
28
27
  "randomstring": "1.3.0"
29
28
  }
30
29
  }
package/tests/jwt.ts ADDED
@@ -0,0 +1,30 @@
1
+ // bun run tests/jwt.ts
2
+
3
+ import { JwtEncode, JwtVerify, JwtDecode, JwtValid } from '../src/index';
4
+
5
+ const runJwtExamples = async () => {
6
+ const secret = 'your-secret-key';
7
+ const payload = { userId: '123', role: 'admin' };
8
+
9
+ // 1. Encode a JWT
10
+ const token = await JwtEncode(payload, secret, 3600);
11
+ console.log('Encoded JWT Token:', token);
12
+
13
+ // 2. Verify the JWT
14
+ try {
15
+ const verifiedPayload = await JwtVerify(token, secret);
16
+ console.log('Verified Payload:', verifiedPayload);
17
+ } catch (error: any) {
18
+ console.error('Verification Error:', error.message);
19
+ }
20
+
21
+ // 3. Decode the JWT without verification
22
+ const decodedPayload = JwtDecode(token);
23
+ console.log('Decoded Payload (without verification):', decodedPayload);
24
+
25
+ // 4. Check if the JWT is valid
26
+ const isValid = JwtValid(token);
27
+ console.log('Is JWT valid:', isValid);
28
+ };
29
+
30
+ runJwtExamples();
package/tsconfig.json CHANGED
@@ -105,6 +105,6 @@
105
105
  // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
106
106
  "skipLibCheck": true /* Skip type checking all .d.ts files. */
107
107
  },
108
- "include": [ "src/**/*" ],
108
+ "include": [ "src/**/*", "tests/jwt.ts" ],
109
109
  "exclude": [ "node_modules", "**/*.spec.ts" ]
110
110
  }
package/dist/index.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export * from './main/util';
2
- export * from './main/jwt-util';
3
- export * from './main/http';
4
- export * from './main/regexr';
5
- export * from './main/const-value';
6
- export * from './main/const-type';
package/dist/index.js DELETED
@@ -1,22 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./main/util"), exports);
18
- __exportStar(require("./main/jwt-util"), exports);
19
- __exportStar(require("./main/http"), exports);
20
- __exportStar(require("./main/regexr"), exports);
21
- __exportStar(require("./main/const-value"), exports);
22
- __exportStar(require("./main/const-type"), exports);
@@ -1,24 +0,0 @@
1
- export type SessionInfo = {
2
- id: string;
3
- email?: string;
4
- mobile?: string;
5
- name?: string;
6
- roles: string[];
7
- requestId?: string;
8
- token?: string;
9
- iat?: number;
10
- exp?: number;
11
- key: string;
12
- };
13
- export type SessionUser = {
14
- id: string;
15
- email?: string;
16
- mobile?: string;
17
- name?: string;
18
- roles: string[];
19
- };
20
- export type ResponseType = {
21
- status?: string | number;
22
- data?: any;
23
- error?: any;
24
- };
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,36 +0,0 @@
1
- export declare const ConstValue: {
2
- AND: string;
3
- OR: string;
4
- NOT: string;
5
- AT: string;
6
- HASH: string;
7
- DOLLAR: string;
8
- PERCENT: string;
9
- CARET: string;
10
- AMPERSAND: string;
11
- ASTERISK: string;
12
- TILDE: string;
13
- COLON: string;
14
- SEMICOLON: string;
15
- DOUBLE_QUOTE: string;
16
- SINGLE_QUOTE: string;
17
- COMMA: string;
18
- PERIOD: string;
19
- SLASH: string;
20
- QUESTION_MARK: string;
21
- PLUS: string;
22
- UNDERSCORE: string;
23
- HYPHEN: string;
24
- EQUALS: string;
25
- BACKSLASH: string;
26
- PIPE: string;
27
- SPACE: string;
28
- EMPTY: string;
29
- TRUE: string;
30
- FALSE: string;
31
- NULL: string;
32
- UNDEFINED: string;
33
- STR_AND: string;
34
- STR_OR: string;
35
- STR_NOT: string;
36
- };
@@ -1,43 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ConstValue = void 0;
4
- exports.ConstValue = {
5
- // Logical operators
6
- AND: '&&',
7
- OR: '||',
8
- NOT: '!',
9
- // Common special characters
10
- AT: '@',
11
- HASH: '#',
12
- DOLLAR: '$',
13
- PERCENT: '%',
14
- CARET: '^',
15
- AMPERSAND: '&',
16
- ASTERISK: '*',
17
- TILDE: '~',
18
- COLON: ':',
19
- SEMICOLON: ';',
20
- DOUBLE_QUOTE: '"',
21
- SINGLE_QUOTE: "'",
22
- COMMA: ',',
23
- PERIOD: '.',
24
- SLASH: '/',
25
- QUESTION_MARK: '?',
26
- PLUS: '+',
27
- UNDERSCORE: '_',
28
- HYPHEN: '-',
29
- EQUALS: '=',
30
- BACKSLASH: '\\',
31
- PIPE: '|',
32
- // Space
33
- SPACE: ' ',
34
- EMPTY: '',
35
- // Other
36
- TRUE: 'true',
37
- FALSE: 'false',
38
- NULL: 'null',
39
- UNDEFINED: 'undefined',
40
- STR_AND: 'AND',
41
- STR_OR: 'OR',
42
- STR_NOT: 'NOT',
43
- };
@@ -1,29 +0,0 @@
1
- export declare enum RespType {
2
- JSON = "json",
3
- TEXT = "text",
4
- BLOB = "blob",
5
- FORM_DATA = "formData",
6
- ARRAY_BUFFER = "arrayBuffer"
7
- }
8
- export declare const HttpHeaders: {
9
- 'Content-Type': string;
10
- authorization: null;
11
- 'x-request-id': null;
12
- };
13
- export declare const BaseHeaders: {
14
- authorization: null;
15
- 'x-request-id': null;
16
- };
17
- export declare class Http {
18
- static API_BASE_URL: string | undefined;
19
- static TOKEN_URL: string;
20
- private static RespData;
21
- static Get(url: string, params: any, headers: any, type?: RespType): Promise<any>;
22
- static Post(url: string, data: any, headers: any, type?: RespType): Promise<any>;
23
- static Put(url: string, data: any, headers: any, type?: RespType): Promise<any>;
24
- static Delete(url: string, params: any, headers: any, type?: RespType): Promise<any>;
25
- static Token(sessionInfo: any, appKey: string, apiKey?: string, type?: RespType): Promise<any>;
26
- static FormUpload(fullUrl: string, file: File, isHeadersAddMultiForm?: boolean, data?: Record<string, any>, headers?: any, method?: 'POST' | 'PUT', type?: RespType): Promise<any>;
27
- static CloudUpload(fullUrl: string, file: File, headers?: any, method?: 'POST' | 'PUT'): Promise<Response>;
28
- static FileDownload(fullUrl: string, params: any, headers?: any, method?: string): Promise<Buffer>;
29
- }
package/dist/main/http.js DELETED
@@ -1,196 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.Http = exports.BaseHeaders = exports.HttpHeaders = exports.RespType = void 0;
13
- var RespType;
14
- (function (RespType) {
15
- RespType["JSON"] = "json";
16
- RespType["TEXT"] = "text";
17
- RespType["BLOB"] = "blob";
18
- RespType["FORM_DATA"] = "formData";
19
- RespType["ARRAY_BUFFER"] = "arrayBuffer";
20
- })(RespType || (exports.RespType = RespType = {}));
21
- exports.HttpHeaders = {
22
- 'Content-Type': 'application/json',
23
- authorization: null,
24
- 'x-request-id': null,
25
- };
26
- exports.BaseHeaders = {
27
- authorization: null,
28
- 'x-request-id': null,
29
- };
30
- class Http {
31
- static RespData(response_1) {
32
- return __awaiter(this, arguments, void 0, function* (response, type = RespType.JSON) {
33
- if (!response.ok) {
34
- throw { status: response.status || 0, statusText: response.statusText || response };
35
- }
36
- switch (type) {
37
- case RespType.JSON:
38
- return yield (response === null || response === void 0 ? void 0 : response.json());
39
- case RespType.TEXT:
40
- return yield (response === null || response === void 0 ? void 0 : response.text());
41
- case RespType.BLOB:
42
- return yield (response === null || response === void 0 ? void 0 : response.blob());
43
- case RespType.FORM_DATA:
44
- return yield (response === null || response === void 0 ? void 0 : response.formData());
45
- case RespType.ARRAY_BUFFER:
46
- return yield (response === null || response === void 0 ? void 0 : response.arrayBuffer());
47
- case RespType.BLOB:
48
- return yield (response === null || response === void 0 ? void 0 : response.blob());
49
- default:
50
- return null;
51
- }
52
- });
53
- }
54
- static Get(url_1, params_1, headers_1) {
55
- return __awaiter(this, arguments, void 0, function* (url, params, headers, type = RespType.JSON) {
56
- url = Http.API_BASE_URL + url;
57
- const fullUrl = params ? `${url}?${new URLSearchParams(params).toString()}` : url;
58
- try {
59
- const requestOptions = { method: 'GET', headers: headers || exports.HttpHeaders };
60
- const response = yield fetch(fullUrl, requestOptions);
61
- return yield Http.RespData(response, type);
62
- }
63
- catch (error) {
64
- console.error('HttpGet error: ', error);
65
- throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
66
- }
67
- });
68
- }
69
- static Post(url_1, data_1, headers_1) {
70
- return __awaiter(this, arguments, void 0, function* (url, data, headers, type = RespType.JSON) {
71
- url = Http.API_BASE_URL + url;
72
- try {
73
- const requestOptions = { method: 'POST', body: JSON.stringify(data || {}), headers: headers || exports.HttpHeaders };
74
- const response = yield fetch(url, requestOptions);
75
- return yield Http.RespData(response, type);
76
- }
77
- catch (error) {
78
- console.error('HttpPost error: ', error);
79
- throw { url: url, requestId: exports.HttpHeaders['x-request-id'], body: data, error: error };
80
- }
81
- });
82
- }
83
- static Put(url_1, data_1, headers_1) {
84
- return __awaiter(this, arguments, void 0, function* (url, data, headers, type = RespType.JSON) {
85
- url = Http.API_BASE_URL + url;
86
- try {
87
- const requestOptions = { method: 'PUT', body: JSON.stringify(data || {}), headers: headers || exports.HttpHeaders };
88
- const response = yield fetch(url, requestOptions);
89
- return yield Http.RespData(response, type);
90
- }
91
- catch (error) {
92
- console.error('HttpPut error: ', error);
93
- throw { url: url, requestId: exports.HttpHeaders['x-request-id'], body: data, error: error };
94
- }
95
- });
96
- }
97
- static Delete(url_1, params_1, headers_1) {
98
- return __awaiter(this, arguments, void 0, function* (url, params, headers, type = RespType.JSON) {
99
- url = Http.API_BASE_URL + url;
100
- const fullUrl = params ? `${url}?${new URLSearchParams(params).toString()}` : url;
101
- try {
102
- const requestOptions = { method: 'DELETE', headers: headers || exports.HttpHeaders };
103
- const response = yield fetch(fullUrl, requestOptions);
104
- return yield Http.RespData(response, type);
105
- }
106
- catch (error) {
107
- console.error('HttpDelete error: ', error);
108
- throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
109
- }
110
- });
111
- }
112
- static Token(sessionInfo_1, appKey_1, apiKey_1) {
113
- return __awaiter(this, arguments, void 0, function* (sessionInfo, appKey, apiKey, type = RespType.TEXT) {
114
- const url = `${Http.API_BASE_URL}${Http.TOKEN_URL}`;
115
- const params = { key: appKey, payload: JSON.stringify(sessionInfo) };
116
- const fullUrl = `${url}?${new URLSearchParams(params).toString()}`;
117
- const headers = Object.assign(Object.assign({}, Headers), { 'X-API-KEY': apiKey || '' });
118
- try {
119
- const requestOptions = { method: 'GET', headers: headers };
120
- const response = yield fetch(fullUrl, requestOptions);
121
- return yield Http.RespData(response, type);
122
- }
123
- catch (error) {
124
- console.error('HttpToken error: ', error);
125
- throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
126
- }
127
- });
128
- }
129
- static FormUpload(fullUrl_1, file_1) {
130
- return __awaiter(this, arguments, void 0, function* (fullUrl, file, isHeadersAddMultiForm = false, data = {}, headers = exports.BaseHeaders, method = 'PUT', type = RespType.JSON) {
131
- const formData = new FormData();
132
- formData.append('file', file);
133
- for (const key in data) {
134
- if (data[key] !== undefined && data[key] !== null) {
135
- formData.append(key, data[key]);
136
- }
137
- }
138
- if (isHeadersAddMultiForm) {
139
- headers = Object.assign(Object.assign({}, headers), { 'Content-Type': headers['Content-Type'] || 'multipart/form-data' });
140
- }
141
- try {
142
- const requestOptions = {
143
- method: method,
144
- body: formData,
145
- headers: Object.assign({}, headers),
146
- };
147
- console.log(requestOptions);
148
- const response = yield fetch(fullUrl, requestOptions);
149
- return yield Http.RespData(response, type);
150
- }
151
- catch (error) {
152
- console.error('HttpUpload error: ', error);
153
- throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
154
- }
155
- });
156
- }
157
- static CloudUpload(fullUrl_1, file_1) {
158
- return __awaiter(this, arguments, void 0, function* (fullUrl, file, headers = null, method = 'PUT') {
159
- headers = headers || {
160
- 'Content-Type': file.type,
161
- };
162
- try {
163
- const requestOptions = {
164
- method: method,
165
- body: file,
166
- headers: Object.assign({}, headers),
167
- };
168
- const response = yield fetch(fullUrl, requestOptions);
169
- return response;
170
- }
171
- catch (error) {
172
- console.error('HttpUpload error: ', error);
173
- throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
174
- }
175
- });
176
- }
177
- static FileDownload(fullUrl_1, params_1) {
178
- return __awaiter(this, arguments, void 0, function* (fullUrl, params, headers = exports.HttpHeaders, method = 'GET') {
179
- fullUrl = params ? `${fullUrl}?${new URLSearchParams(params).toString()}` : fullUrl;
180
- try {
181
- const requestOptions = { method: method, headers: headers || exports.HttpHeaders };
182
- const response = yield fetch(fullUrl, requestOptions);
183
- const blob = yield response.blob();
184
- const buffer = Buffer.from(yield blob.arrayBuffer());
185
- return buffer;
186
- }
187
- catch (error) {
188
- console.error('HttpDownload error: ', error);
189
- throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
190
- }
191
- });
192
- }
193
- }
194
- exports.Http = Http;
195
- Http.API_BASE_URL = process.env.API_BASE_URL;
196
- Http.TOKEN_URL = `/apisix/plugin/jwt/sign`;
@@ -1,28 +0,0 @@
1
- import * as jwt from 'jsonwebtoken';
2
- /**
3
- * Encode JWT Token with secret key, expiresIn in seconds (86400 = 1 day) default
4
- * @param data
5
- * @param token
6
- * @param expiresIn
7
- * @returns
8
- */
9
- export declare const JwtEncode: (data: any, secret: string, expiresIn?: number) => string;
10
- /**
11
- * Verify JWT token with secret
12
- * @param data
13
- * @param token
14
- * @returns
15
- */
16
- export declare const JwtVerify: (data: string, secret: string) => string | jwt.JwtPayload;
17
- /**
18
- * Deocde JWT Token
19
- * @param token
20
- * @returns
21
- */
22
- export declare const JwtDecode: (token: string) => string | jwt.JwtPayload | null;
23
- /**
24
- * checking token expires or not
25
- * @param token
26
- * @returns
27
- */
28
- export declare const JwtValid: (token: string) => boolean;
@@ -1,108 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.JwtValid = exports.JwtDecode = exports.JwtVerify = exports.JwtEncode = void 0;
27
- const jwt = __importStar(require("jsonwebtoken"));
28
- /**
29
- * Encode JWT Token with secret key, expiresIn in seconds (86400 = 1 day) default
30
- * @param data
31
- * @param token
32
- * @param expiresIn
33
- * @returns
34
- */
35
- const JwtEncode = (data, secret, expiresIn = 86400) => {
36
- return jwt.sign(data, secret, {
37
- expiresIn: expiresIn,
38
- });
39
- };
40
- exports.JwtEncode = JwtEncode;
41
- /**
42
- * Verify JWT token with secret
43
- * @param data
44
- * @param token
45
- * @returns
46
- */
47
- const JwtVerify = (data, secret) => {
48
- if (data) {
49
- try {
50
- data = data.replace('jwt ', '').replace('JWT ', '');
51
- data = data.replace('Bearer ', '').replace('bearer ', '').replace('BEARER', '');
52
- return jwt.verify(data, secret);
53
- }
54
- catch (err) {
55
- throw { name: 'error', message: 'Token is not valid' };
56
- }
57
- }
58
- else {
59
- throw { name: 'error', message: 'Auth token is not supplied' };
60
- }
61
- };
62
- exports.JwtVerify = JwtVerify;
63
- /**
64
- * Deocde JWT Token
65
- * @param token
66
- * @returns
67
- */
68
- const JwtDecode = (token) => {
69
- if (token) {
70
- try {
71
- token = token.replace('jwt ', '').replace('JWT ', '');
72
- token = token.replace('Bearer ', '').replace('bearer ', '').replace('BEARER', '');
73
- return jwt.decode(token);
74
- }
75
- catch (err) {
76
- console.log(err);
77
- throw { name: 'error', message: 'Token is not valid' };
78
- }
79
- }
80
- else {
81
- throw { name: 'error', message: 'Auth token is not supplied' };
82
- }
83
- };
84
- exports.JwtDecode = JwtDecode;
85
- /**
86
- * checking token expires or not
87
- * @param token
88
- * @returns
89
- */
90
- const JwtValid = (token) => {
91
- try {
92
- if (!token) {
93
- return false;
94
- }
95
- const payloadBase64 = token.split('.')[1];
96
- const payload = JSON.parse(atob(payloadBase64));
97
- const currentTime = Math.floor(Date.now() / 1000);
98
- if (payload.exp && payload.exp < currentTime) {
99
- return false;
100
- }
101
- return true;
102
- }
103
- catch (error) {
104
- console.error('Invalid JWT:', error);
105
- return false;
106
- }
107
- };
108
- exports.JwtValid = JwtValid;
@@ -1,22 +0,0 @@
1
- export declare const RegExp: {
2
- NON_ALPHA_NUMERIC: RegExp;
3
- DIGITS_ONLY: RegExp;
4
- ALPHABETS_ONLY: RegExp;
5
- ALPHA_NUMERIC: RegExp;
6
- EMAIL: RegExp;
7
- URL: RegExp;
8
- PHONE_US: RegExp;
9
- STRONG_PASSWORD: RegExp;
10
- WHITESPACE: RegExp;
11
- HTML_TAG: RegExp;
12
- IPV4: RegExp;
13
- DATE_YYYY_MM_DD: RegExp;
14
- TIME_HH_MM: RegExp;
15
- ISO_DATETIME: RegExp;
16
- HEX_COLOR: RegExp;
17
- UUID_V4: RegExp;
18
- NON_ASCII: RegExp;
19
- LINE_BREAK: RegExp;
20
- AMOUNT_DECIMAL: RegExp;
21
- PERCENTAGE: RegExp;
22
- };
@@ -1,45 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RegExp = void 0;
4
- exports.RegExp = {
5
- // Matches any non-alphanumeric characters
6
- NON_ALPHA_NUMERIC: /[^\w\s]/g,
7
- // Matches only numeric digits (0-9)
8
- DIGITS_ONLY: /^\d+$/,
9
- // Matches only alphabets (case-insensitive)
10
- ALPHABETS_ONLY: /^[a-zA-Z]+$/,
11
- // Matches alphanumeric characters (letters and digits)
12
- ALPHA_NUMERIC: /^[a-zA-Z0-9]+$/,
13
- // Matches an email address
14
- EMAIL: /^[\w.%+-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,}$/,
15
- // Matches a URL
16
- URL: /^(https?:\/\/)?([\w.-]+)\.([a-z]{2,6}\.?)(\/[\w.-]*)*\/?$/i,
17
- // Matches a US phone number (formats like (123) 456-7890, 123-456-7890, etc.)
18
- PHONE_US: /^(\(\d{3}\)\s?|\d{3}[-.\s]?)?\d{3}[-.\s]?\d{4}$/,
19
- // Matches a password with at least one lowercase, one uppercase, one digit, and one special character
20
- STRONG_PASSWORD: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/,
21
- // Matches whitespace characters
22
- WHITESPACE: /\s+/g,
23
- // Matches any HTML tags
24
- HTML_TAG: /<\/?[\w\s="/.':;#-\/\?]+>/gi,
25
- // Matches IPv4 addresses
26
- IPV4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/,
27
- // Matches dates in YYYY-MM-DD format
28
- DATE_YYYY_MM_DD: /^\d{4}-\d{2}-\d{2}$/,
29
- // Matches time in HH:MM 24-hour format
30
- TIME_HH_MM: /^([01]\d|2[0-3]):([0-5]\d)$/,
31
- // Matches ISO 8601 datetime format (e.g., 2023-08-15T13:45:30Z, 2023-08-15T13:45:30+05:30)
32
- ISO_DATETIME: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,
33
- // Matches a hexadecimal color code
34
- HEX_COLOR: /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/,
35
- // Matches a UUID (version 4)
36
- UUID_V4: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
37
- // Matches non-ASCII characters
38
- NON_ASCII: /[^\x00-\x7F]/g,
39
- // Matches line breaks (newlines)
40
- LINE_BREAK: /\r?\n/g,
41
- // Matches amounts in decimal format (e.g., 123.45, 0.99, 1000)
42
- AMOUNT_DECIMAL: /^\d+(\.\d{1,2})?$/,
43
- // Matches percentages from 0-100 or in decimal format (e.g., 25%, 99.99%, 100, 0.5)
44
- PERCENTAGE: /^(100(\.0{1,2})?|0|0?\.\d{1,2}|[1-9]?\d(\.\d{1,2})?)%?$/,
45
- };
@@ -1,7 +0,0 @@
1
- export declare const AppRandomString: (length: number, charset: string) => string;
2
- export declare const AppUniqueCode: () => string;
3
- export declare const AppCodeByType: (name: string, type?: null) => string;
4
- export declare const AppCode: (name: string) => string | null;
5
- export declare const AppDaysBack: (date: Date, backValue: number, isDays?: boolean) => Date;
6
- export declare const AppAddDays: (date: Date, addDays: number, isDays?: boolean) => Date;
7
- export declare const AppUUID4: () => string;
package/dist/main/util.js DELETED
@@ -1,76 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AppUUID4 = exports.AppAddDays = exports.AppDaysBack = exports.AppCode = exports.AppCodeByType = exports.AppUniqueCode = exports.AppRandomString = void 0;
4
- const randomstring_1 = require("randomstring");
5
- const regexr_1 = require("./regexr");
6
- const AppRandomString = (length, charset) => {
7
- return (0, randomstring_1.generate)({ length: length, charset: charset });
8
- };
9
- exports.AppRandomString = AppRandomString;
10
- let uniqueId = 0;
11
- const AppUniqueCode = () => {
12
- let time = new Date().getTime();
13
- if (uniqueId == time) {
14
- while (new Date().getTime() < 1 + time) { }
15
- time = new Date().getTime();
16
- }
17
- uniqueId = time;
18
- return time.toString(36).toUpperCase();
19
- };
20
- exports.AppUniqueCode = AppUniqueCode;
21
- const AppCodeByType = (name, type = null) => {
22
- let str = '';
23
- if (type) {
24
- str = type + '_' + name;
25
- }
26
- else {
27
- str = name + '_' + (0, exports.AppUniqueCode)();
28
- }
29
- str = str.replace(regexr_1.RegExp.NON_ALPHA_NUMERIC, '_');
30
- str = str.replace(/\s/g, '_');
31
- str = str.substr(0, 128);
32
- return str.toUpperCase();
33
- };
34
- exports.AppCodeByType = AppCodeByType;
35
- const AppCode = (name) => {
36
- if (name == null)
37
- return null;
38
- let str = '';
39
- str = name.trim();
40
- str = str.replace(regexr_1.RegExp.NON_ALPHA_NUMERIC, '_');
41
- str = str.replace(/\s/g, '_');
42
- return str.toUpperCase();
43
- };
44
- exports.AppCode = AppCode;
45
- const AppDaysBack = (date, backValue, isDays = true) => {
46
- date = new Date(date);
47
- if (isDays) {
48
- date.setDate(date.getDate() - backValue);
49
- }
50
- else {
51
- date.setMilliseconds(date.getMilliseconds() - backValue);
52
- }
53
- date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
54
- return date;
55
- };
56
- exports.AppDaysBack = AppDaysBack;
57
- const AppAddDays = (date, addDays, isDays = true) => {
58
- date = new Date(date);
59
- if (isDays) {
60
- date.setDate(date.getDate() + addDays);
61
- }
62
- else {
63
- date.setMilliseconds(date.getMilliseconds() + addDays);
64
- }
65
- date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
66
- return date;
67
- };
68
- exports.AppAddDays = AppAddDays;
69
- const AppUUID4 = () => {
70
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
71
- const r = (Math.random() * 16) | 0;
72
- const v = c == 'x' ? r : (r & 0x3) | 0x8;
73
- return v.toString(16);
74
- });
75
- };
76
- exports.AppUUID4 = AppUUID4;