jd_platform_sdk 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/extensions/extensions.d.ts +1 -0
  2. package/dist/extensions/extensions.d.ts.map +1 -0
  3. package/dist/extensions/extensions.js +31 -0
  4. package/dist/globals.d.ts +7 -0
  5. package/dist/globals.d.ts.map +1 -0
  6. package/dist/globals.js +1 -0
  7. package/dist/index.d.ts +13 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +14 -0
  10. package/dist/sdk/configs/dpConfig.d.ts +15 -0
  11. package/dist/sdk/configs/dpConfig.d.ts.map +1 -0
  12. package/dist/sdk/configs/dpConfig.js +49 -0
  13. package/dist/sdk/configs/jdConfig.d.ts +8 -0
  14. package/dist/sdk/configs/jdConfig.d.ts.map +1 -0
  15. package/dist/sdk/configs/jdConfig.js +40 -0
  16. package/dist/sdk/extensions/extensions.d.ts +2 -0
  17. package/dist/sdk/extensions/extensions.d.ts.map +1 -0
  18. package/dist/sdk/extensions/extensions.js +23 -0
  19. package/dist/sdk/jdConnector.d.ts +24 -0
  20. package/dist/sdk/jdConnector.d.ts.map +1 -0
  21. package/dist/sdk/jdConnector.js +141 -0
  22. package/dist/sdk/jdSdk.d.ts +6 -0
  23. package/dist/sdk/jdSdk.d.ts.map +1 -0
  24. package/dist/sdk/jdSdk.js +18 -0
  25. package/dist/sdk/models/jdApplication.d.ts +21 -0
  26. package/dist/sdk/models/jdApplication.d.ts.map +1 -0
  27. package/dist/sdk/models/jdApplication.js +60 -0
  28. package/dist/sdk/models/jdResource.d.ts +43 -0
  29. package/dist/sdk/models/jdResource.d.ts.map +1 -0
  30. package/dist/sdk/models/jdResource.js +149 -0
  31. package/dist/sdk/models/modules/karaoke/jdKtvShop.d.ts +8 -0
  32. package/dist/sdk/models/modules/karaoke/jdKtvShop.d.ts.map +1 -0
  33. package/dist/sdk/models/modules/karaoke/jdKtvShop.js +37 -0
  34. package/dist/sdk/utilities/browserUtils.d.ts +5 -0
  35. package/dist/sdk/utilities/browserUtils.d.ts.map +1 -0
  36. package/dist/sdk/utilities/browserUtils.js +26 -0
  37. package/dist/sdk/utilities/cryptoUtils.d.ts +5 -0
  38. package/dist/sdk/utilities/cryptoUtils.d.ts.map +1 -0
  39. package/dist/sdk/utilities/cryptoUtils.js +25 -0
  40. package/dist/sdk/utilities/crypto_utils.d.ts +5 -0
  41. package/dist/sdk/utilities/crypto_utils.d.ts.map +1 -0
  42. package/dist/sdk/utilities/crypto_utils.js +26 -0
  43. package/dist/sdk/utilities/dateUtils.d.ts +6 -0
  44. package/dist/sdk/utilities/dateUtils.d.ts.map +1 -0
  45. package/dist/sdk/utilities/dateUtils.js +49 -0
  46. package/dist/sdk/utilities/globalEventHandler.d.ts +10 -0
  47. package/dist/sdk/utilities/globalEventHandler.d.ts.map +1 -0
  48. package/dist/sdk/utilities/globalEventHandler.js +34 -0
  49. package/dist/sdk/utilities/stringUtils.d.ts +3 -0
  50. package/dist/sdk/utilities/stringUtils.d.ts.map +1 -0
  51. package/dist/sdk/utilities/stringUtils.js +6 -0
  52. package/dist/sdk/utilities/utils.d.ts +31 -0
  53. package/dist/sdk/utilities/utils.d.ts.map +1 -0
  54. package/dist/sdk/utilities/utils.js +133 -0
  55. package/dist/stringUtils.d.ts +3 -0
  56. package/dist/stringUtils.d.ts.map +1 -0
  57. package/dist/stringUtils.js +6 -0
  58. package/dist/unit_tests.d.ts +2 -0
  59. package/dist/unit_tests.d.ts.map +1 -0
  60. package/dist/unit_tests.js +7 -0
  61. package/package.json +33 -0
  62. package/readme.md +40 -0
@@ -0,0 +1,149 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { Utils } from "../utilities/utils";
11
+ import { DateUtils } from "../utilities/dateUtils";
12
+ import { CryptoUtils } from "../utilities/cryptoUtils";
13
+ import { JDConnector, SimpleResponse } from "../jdConnector";
14
+ export default class JDResource {
15
+ // Properties
16
+ // localisedTitle:string = DPUtility.getStringFromField(this.title, 'en');
17
+ // localisedDescription:string = DPUtility.getStringFromField(this.title, 'en');
18
+ // getLocalisedTitle(){ return DPProfile.language == 'Myanmar' ? this.getTitleEN() : this.getTitleMM(); }
19
+ // getLocalisedDescription(){ return DPProfile.language == 'Myanmar' ? this.getDescriptionEN() : this.getDescriptionMM(); }
20
+ get localisedTitle() { return globalThis.language == 'mm' ? this.titleMM : this.titleEN; }
21
+ get localisedDescription() { return globalThis.language == 'mm' ? this.descriptionMM : this.descriptionEN; }
22
+ get titleEN() { return Utils.getString(this.title, 'en'); }
23
+ get titleMM() { return Utils.getString(this.title, 'mm'); }
24
+ get descriptionEN() { return Utils.getString(this.description, 'en'); }
25
+ get descriptionMM() { return Utils.getString(this.description, 'mm'); }
26
+ get iconURL() { return Utils.getString(this.images, 'icon_url'); }
27
+ get iconURL100() { return Utils.getString(this.images, 'icon_url_100'); }
28
+ get iconURL300() { return Utils.getString(this.images, 'icon_url_300'); }
29
+ get cdnIconURL() { return this.iconURL.includes('http') ? this.iconURL : globalThis.cdnHost + this.iconURL; }
30
+ get cdnIconURL100() { return this.iconURL100.includes('http') ? this.iconURL100 : globalThis.cdnHost + this.iconURL100; }
31
+ get cdnIconURL300() { return this.iconURL.includes('http') ? this.iconURL : globalThis.cdnHost + this.iconURL300; }
32
+ get bannerURL() { return Utils.getString(this.images, 'banner_url'); }
33
+ get bannerURL500() { return Utils.getString(this.images, 'banner_url_500'); }
34
+ get bannerURL800() { return Utils.getString(this.images, 'banner_url_800'); }
35
+ get cdnBannerURL() { return this.bannerURL.includes('http') ? this.bannerURL : globalThis.cdnHost + this.bannerURL; }
36
+ get cdnBannerURL500() { return this.bannerURL800.includes('http') ? this.bannerURL500 : globalThis.cdnHost + this.bannerURL500; }
37
+ get cdnBannerURL800() { return this.bannerURL800.includes('http') ? this.bannerURL800 : globalThis.cdnHost + this.bannerURL800; }
38
+ getFacebookIconURL(fbId) { return 'https://graph.facebook.com/' + fbId + '/picture?type=square'; }
39
+ constructor(data) {
40
+ this.myId = '';
41
+ this.slug = '';
42
+ this.index = 0;
43
+ this.title = {};
44
+ this.description = {};
45
+ this.images = {};
46
+ this.createdAt = new Date();
47
+ this.updatedAt = new Date();
48
+ this.placeholderIconURL = 'https://joydash-downloads.b-cdn.net/misc/banner-male-profile-x300.png';
49
+ this.placeholderIconURL = '';
50
+ }
51
+ setData(data) {
52
+ // console.log('Setting super constructor');
53
+ this.myId = Utils.getString(data, "_id");
54
+ this.slug = Utils.getString(data, "slug");
55
+ this.index = Utils.getInteger(data, "index");
56
+ this.title = Utils.getObject(data, 'title');
57
+ this.description = Utils.getObject(data, 'description');
58
+ this.images = Utils.getObject(data, 'images');
59
+ this.createdAt = Utils.getDate(data, 'created_at');
60
+ this.updatedAt = Utils.getDate(data, 'updated_at');
61
+ // console.log(data);
62
+ // console.log(this.createdAt);
63
+ }
64
+ //Get default hash string with remark
65
+ static getHashBody() {
66
+ return __awaiter(this, arguments, void 0, function* (remark = '') {
67
+ const body = {};
68
+ //Calculate hashes
69
+ const timestamp = DateUtils.getTimeStamp();
70
+ body['timestamp'] = timestamp;
71
+ body['hash_before'] = CryptoUtils.generateBeforeHashString([timestamp, remark]);
72
+ return body;
73
+ });
74
+ }
75
+ // Other Utilities
76
+ static getDefaultHeaders(headers = {}) {
77
+ // console.log(DPProfile.getAccessToken());
78
+ // console.log('Token:' + authToken.get());
79
+ const finalHeaders = {};
80
+ finalHeaders["Content-Type"] = 'application/json';
81
+ finalHeaders["app_id"] = globalThis.appId;
82
+ finalHeaders["app_key"] = globalThis.appKey;
83
+ finalHeaders["x-auth-token"] = globalThis.xAuthToken;
84
+ finalHeaders["random_seed"] = DateUtils.getTimeStamp();
85
+ return finalHeaders;
86
+ }
87
+ //This is used to make a direct call supported on some APIs
88
+ static addDefaultParams(params) {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ params["app_id"] = globalThis.appId;
91
+ params["token"] = globalThis.xAuthToken;
92
+ params["random_seed"] = Date.now();
93
+ });
94
+ }
95
+ static getSortParameters(orderBy, order, pageIndex, countPerPage, fields) {
96
+ return __awaiter(this, void 0, void 0, function* () {
97
+ const params = { 'page_index': pageIndex, 'count_per_page': countPerPage, 'fields': fields };
98
+ if (Utils.isset(orderBy) && Utils.isset(order)) {
99
+ params['order_by'] = orderBy;
100
+ params['order'] = order;
101
+ }
102
+ if (pageIndex >= 0 && countPerPage > 0) {
103
+ params["page_index"] = pageIndex;
104
+ params["count_per_page"] = countPerPage;
105
+ }
106
+ if (Utils.isset(fields)) {
107
+ params["fields"] = fields;
108
+ }
109
+ return params;
110
+ });
111
+ }
112
+ static getFieldParameters(fields) {
113
+ return __awaiter(this, void 0, void 0, function* () {
114
+ const params = {};
115
+ params["fields"] = fields;
116
+ return params;
117
+ });
118
+ }
119
+ // HTTP Calls Utilities
120
+ static getRelative(relativeUrl_1, params_1) {
121
+ return __awaiter(this, arguments, void 0, function* (relativeUrl, params, bShowErrorToast = true, bForceRefresh = false, overrideVersion = '', headers = {}) {
122
+ const finalHeaders = this.getDefaultHeaders(headers);
123
+ const connector = new JDConnector();
124
+ const response = yield connector.httpGetRelativeAsync(relativeUrl, finalHeaders, params, bShowErrorToast, bForceRefresh, true, overrideVersion);
125
+ return new SimpleResponse(response.body, response.statusCode);
126
+ });
127
+ }
128
+ static postRelative(relativeUrl_1, body_1) {
129
+ return __awaiter(this, arguments, void 0, function* (relativeUrl, body, bShowErrorToast = true, overrideVersion = '') {
130
+ const headers = this.getDefaultHeaders();
131
+ const connector = new JDConnector();
132
+ const response = yield connector.httpPostRelativeAsync(relativeUrl, headers, body, bShowErrorToast, true, overrideVersion);
133
+ return new SimpleResponse(response.body, response.statusCode);
134
+ });
135
+ }
136
+ // Direct Calls to the URL without using SDK
137
+ static getDirect(directUrl_1, params_1) {
138
+ return __awaiter(this, arguments, void 0, function* (directUrl, params, bShowErrorToast = true, bForceRefresh = false, overrideVersion = '') {
139
+ const response = yield new JDConnector().httpGetDirectAsync(directUrl, {}, params, bShowErrorToast, true, bForceRefresh, overrideVersion);
140
+ return new SimpleResponse(response.body, response.statusCode);
141
+ });
142
+ }
143
+ static postDirect(directUrl_1, body_1) {
144
+ return __awaiter(this, arguments, void 0, function* (directUrl, body, bShowErrorToast = true, overrideVersion = '') {
145
+ const response = yield new JDConnector().httpPostDirectAsync(directUrl, { 'Content-Type': 'application/json' }, body, bShowErrorToast, false, overrideVersion);
146
+ return new SimpleResponse(response.body, response.statusCode);
147
+ });
148
+ }
149
+ }
@@ -0,0 +1,8 @@
1
+ import JDResource from "../../jdResource";
2
+ export declare class JDKtvShop extends JDResource {
3
+ constructor(data: object);
4
+ setData(data: object): void;
5
+ static getKtvShops(isRecommended?: boolean, orderBy?: string, order?: string, pageIndex?: number, countPerPage?: number, fields?: string): Promise<import("../../../jdConnector").SimpleResponse>;
6
+ static getInfo(id: string): Promise<import("../../../jdConnector").SimpleResponse>;
7
+ }
8
+ //# sourceMappingURL=jdKtvShop.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jdKtvShop.d.ts","sourceRoot":"","sources":["../../../../../src/sdk/models/modules/karaoke/jdKtvShop.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,kBAAkB,CAAC;AAE1C,qBAAa,SAAU,SAAQ,UAAU;gBAC5B,IAAI,EAAC,MAAM;IAKvB,OAAO,CAAC,IAAI,EAAC,MAAM;WAGN,WAAW,CAAC,aAAa,UAAQ,EAAE,OAAO,SAAe,EAAE,KAAK,SAAS,EAAE,SAAS,SAAI,EAAE,YAAY,SAAK,EAAE,MAAM,SAAK;WAWxH,OAAO,CAAC,EAAE,EAAC,MAAM;CAI9B"}
@@ -0,0 +1,37 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import JDResource from "../../jdResource";
11
+ import { Utils } from "../../../utilities/utils";
12
+ export class JDKtvShop extends JDResource {
13
+ constructor(data) {
14
+ super(data);
15
+ this.setData(data);
16
+ }
17
+ setData(data) {
18
+ super.setData(data);
19
+ }
20
+ static getKtvShops() {
21
+ return __awaiter(this, arguments, void 0, function* (isRecommended = false, orderBy = 'updated_at', order = 'desc', pageIndex = 0, countPerPage = 20, fields = '') {
22
+ const params = JDResource.getSortParameters(orderBy, order, pageIndex, countPerPage, fields);
23
+ if (Utils.isset(isRecommended)) {
24
+ params['recommended'] = isRecommended ? 'true' : 'false';
25
+ }
26
+ // console.log(params);
27
+ const response = yield JDResource.getRelative('/applications', params);
28
+ return response;
29
+ });
30
+ }
31
+ static getInfo(id) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ const response = yield JDResource.getRelative(`/applications/${id}`, {});
34
+ return response;
35
+ });
36
+ }
37
+ }
@@ -0,0 +1,5 @@
1
+ export declare function setSessionItem(key: string, val: string): void;
2
+ export declare function getSessionItem(key: string): string | null;
3
+ export declare function setStorageItem(key: string, val: string): void;
4
+ export declare function getStorageItem(key: string): string | null;
5
+ //# sourceMappingURL=browserUtils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserUtils.d.ts","sourceRoot":"","sources":["../../../src/sdk/utilities/browserUtils.ts"],"names":[],"mappings":"AACA,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAI7D;AAGD,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAKzD;AAGD,wBAAiB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAI9D;AAGD,wBAAiB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAK1D"}
@@ -0,0 +1,26 @@
1
+ // Set a session storage item
2
+ export function setSessionItem(key, val) {
3
+ if (typeof window !== "undefined") {
4
+ window.sessionStorage.setItem(key, val);
5
+ }
6
+ }
7
+ // Get a session storage item
8
+ export function getSessionItem(key) {
9
+ if (typeof window !== "undefined") {
10
+ return window.sessionStorage.getItem(key);
11
+ }
12
+ return null;
13
+ }
14
+ // Set a local storage item
15
+ export function setStorageItem(key, val) {
16
+ if (typeof window !== "undefined") {
17
+ window.localStorage.setItem(key, val);
18
+ }
19
+ }
20
+ // Get a local storage item
21
+ export function getStorageItem(key) {
22
+ if (typeof window !== "undefined") {
23
+ return window.localStorage.getItem(key);
24
+ }
25
+ return null;
26
+ }
@@ -0,0 +1,5 @@
1
+ export declare class CryptoUtils {
2
+ static generateBeforeHashString(paramsArray: string[]): string | undefined;
3
+ static generateHash(strMessage: string, secret: string): string;
4
+ }
5
+ //# sourceMappingURL=cryptoUtils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cryptoUtils.d.ts","sourceRoot":"","sources":["../../../src/sdk/utilities/cryptoUtils.ts"],"names":[],"mappings":"AAGA,qBAAa,WAAW;IAEpB,MAAM,CAAC,wBAAwB,CAAC,WAAW,EAAC,MAAM,EAAE;IAqBpD,MAAM,CAAC,YAAY,CAAC,UAAU,EAAC,MAAM,EAAE,MAAM,EAAC,MAAM;CAGvD"}
@@ -0,0 +1,25 @@
1
+ import hmacSha256 from 'crypto-js/hmac-sha256';
2
+ import { Utils } from "./utils";
3
+ export class CryptoUtils {
4
+ // Generate hash string to sign to communicate with the server to allow from this client only
5
+ static generateBeforeHashString(paramsArray) {
6
+ const curUserId = globalThis.userId;
7
+ const curApplicationId = globalThis.applicationId;
8
+ const curAppSecret = globalThis.appSecret;
9
+ if (!Utils.isset(curUserId) || !Utils.isset(curApplicationId) || !Utils.isset(curAppSecret)) {
10
+ console.log("You need to initialise the required parameters before hashing!");
11
+ return;
12
+ }
13
+ let strBeforeHash = curApplicationId + curUserId;
14
+ for (const param of paramsArray) {
15
+ strBeforeHash += param;
16
+ }
17
+ // console.log(`Cur Application Id: ${curApplicationId.get()}`);
18
+ // console.log(`Cur User Id: ${userId}`);
19
+ // console.log(`Before Hash: ${strBeforeHash}`);
20
+ return hmacSha256(strBeforeHash, curAppSecret).toString();
21
+ }
22
+ static generateHash(strMessage, secret) {
23
+ return hmacSha256(strMessage, secret).toString();
24
+ }
25
+ }
@@ -0,0 +1,5 @@
1
+ export declare class CryptoUtility {
2
+ static generateBeforeHashString(paramsArray: any): any;
3
+ static generateHash(strMessage: string, secret: string): any;
4
+ }
5
+ //# sourceMappingURL=crypto_utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto_utils.d.ts","sourceRoot":"","sources":["../../../src/sdk/utilities/crypto_utils.ts"],"names":[],"mappings":"AAIA,qBAAa,aAAa;IAEtB,MAAM,CAAC,wBAAwB,CAAC,WAAW,EAAC,GAAG;IAqB/C,MAAM,CAAC,YAAY,CAAC,UAAU,EAAC,MAAM,EAAE,MAAM,EAAC,MAAM;CAGvD"}
@@ -0,0 +1,26 @@
1
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2
+ // @ts-ignore
3
+ import hmacSha256 from 'crypto-js/hmac-sha256';
4
+ export class CryptoUtility {
5
+ // Generate hash string to sign to communicate with the server to allow from this client only
6
+ static generateBeforeHashString(paramsArray) {
7
+ const curUserId = globalThis.curUserId;
8
+ const curApplicationId = globalThis.curApplicationId;
9
+ const curAppSecret = globalThis.curAppSecret;
10
+ const userId = curUserId.get();
11
+ let strBeforeHash = curApplicationId.get() + userId;
12
+ const appSecret = curAppSecret.get();
13
+ // console.log(`Player ID: ${playerId}`);
14
+ for (const param of paramsArray) {
15
+ strBeforeHash += param;
16
+ }
17
+ // console.log(`Cur Application Id: ${curApplicationId.get()}`);
18
+ // console.log(`Cur User Id: ${userId}`);
19
+ // console.log(`Before Hash: ${strBeforeHash}`);
20
+ // console.log(`App Secret: ${appSecret}`);
21
+ return hmacSha256(strBeforeHash, appSecret).toString();
22
+ }
23
+ static generateHash(strMessage, secret) {
24
+ return hmacSha256(strMessage, secret).toString();
25
+ }
26
+ }
@@ -0,0 +1,6 @@
1
+ export declare class DateUtils {
2
+ static formatPrettyDate(date: Date): string;
3
+ static getRandomStamp(): string;
4
+ static getTimeStamp(): string;
5
+ }
6
+ //# sourceMappingURL=dateUtils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dateUtils.d.ts","sourceRoot":"","sources":["../../../src/sdk/utilities/dateUtils.ts"],"names":[],"mappings":"AAAA,qBAAa,SAAS;IAQlB,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE,IAAI;IA+BlC,MAAM,CAAC,cAAc,IAAI,MAAM;IAK/B,MAAM,CAAC,YAAY,IAAI,MAAM;CAGhC"}
@@ -0,0 +1,49 @@
1
+ export class DateUtils {
2
+ //////////////////////////////////////////////////////////////////////////////////
3
+ // Example usage:
4
+ // const targetDate = new Date('2023-08-01T12:00:00Z');
5
+ // const formattedDate = formatPrettyDate(targetDate);
6
+ // console.log(formattedDate); // Output will vary based on the current date and time
7
+ //////////////////////////////////////////////////////////////////////////////////
8
+ static formatPrettyDate(date) {
9
+ const now = new Date();
10
+ // console.log(`${now} : ${date}`);
11
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
12
+ // @ts-ignore
13
+ const diff = Math.floor((now - date) / 1000); // Calculate time difference in seconds
14
+ if (diff < 5) {
15
+ return 'just now';
16
+ }
17
+ else if (diff < 60) {
18
+ return `${diff} seconds ago`;
19
+ }
20
+ else if (diff < 3600) {
21
+ const minutes = Math.floor(diff / 60);
22
+ return `${minutes} ${minutes === 1 ? 'minute' : 'minutes'} ago`;
23
+ }
24
+ else if (diff < 86400) {
25
+ const hours = Math.floor(diff / 3600);
26
+ return `${hours} ${hours === 1 ? 'hour' : 'hours'} ago`;
27
+ }
28
+ else if (diff < 2592000) {
29
+ const days = Math.floor(diff / 86400);
30
+ return `${days} ${days === 1 ? 'day' : 'days'} ago`;
31
+ }
32
+ else if (diff < 31536000) {
33
+ const months = Math.floor(diff / 2592000);
34
+ return `${months} ${months === 1 ? 'month' : 'months'} ago`;
35
+ }
36
+ else {
37
+ const years = Math.floor(diff / 31536000);
38
+ return `${years} ${years === 1 ? 'year' : 'years'} ago`;
39
+ }
40
+ }
41
+ //Get Time stamp with random to avoid API call cachings
42
+ static getRandomStamp() {
43
+ return (Date.now() + Math.floor(Math.random() * 1e4)).toString();
44
+ }
45
+ //Get Time stamp with random to avoid API call cachings
46
+ static getTimeStamp() {
47
+ return Date.now().toString();
48
+ }
49
+ }
@@ -0,0 +1,10 @@
1
+ type GlobalEventHandler = (...args: any[]) => void;
2
+ declare class GlobalEventEmitter {
3
+ private events;
4
+ on(event: string, handler: GlobalEventHandler): void;
5
+ off(event: string, handler: GlobalEventHandler): void;
6
+ emit(event: string, ...args: any[]): void;
7
+ }
8
+ export declare const globalEventEmitter: GlobalEventEmitter;
9
+ export {};
10
+ //# sourceMappingURL=globalEventHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"globalEventHandler.d.ts","sourceRoot":"","sources":["../../../src/sdk/utilities/globalEventHandler.ts"],"names":[],"mappings":"AAAA,KAAK,kBAAkB,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;AAWnD,cAAM,kBAAkB;IACpB,OAAO,CAAC,MAAM,CAA+C;IAG7D,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB;IAQ7C,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB;IAM9C,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE;CAIrC;AAGD,eAAO,MAAM,kBAAkB,oBAA2B,CAAC"}
@@ -0,0 +1,34 @@
1
+ ////////////////////////////////////////////////////////////////
2
+ // Listening for an event
3
+ // import { globalEventEmitter } from "./GlobalEventEmitter";
4
+ //
5
+ // globalEventEmitter.on("userLoggedIn", (data) => {
6
+ // console.log("User logged in:", data.username);
7
+ // });
8
+ ////////////////////////////////////////////////////////////////
9
+ class GlobalEventEmitter {
10
+ constructor() {
11
+ this.events = {};
12
+ }
13
+ // Register an event listener
14
+ on(event, handler) {
15
+ if (!this.events[event]) {
16
+ this.events[event] = [];
17
+ }
18
+ this.events[event].push(handler);
19
+ }
20
+ // Unregister an event listener
21
+ off(event, handler) {
22
+ if (!this.events[event])
23
+ return;
24
+ this.events[event] = this.events[event].filter((h) => h !== handler);
25
+ }
26
+ // Emit an event globally
27
+ emit(event, ...args) {
28
+ if (!this.events[event])
29
+ return;
30
+ this.events[event].forEach((handler) => handler(...args));
31
+ }
32
+ }
33
+ // Export a singleton instance
34
+ export const globalEventEmitter = new GlobalEventEmitter();
@@ -0,0 +1,3 @@
1
+ export declare function capitalize(text: string): string;
2
+ export declare function lowercase(text: string): string;
3
+ //# sourceMappingURL=stringUtils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stringUtils.d.ts","sourceRoot":"","sources":["../../../src/sdk/utilities/stringUtils.ts"],"names":[],"mappings":"AAAA,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9C"}
@@ -0,0 +1,6 @@
1
+ export function capitalize(text) {
2
+ return text.charAt(0).toUpperCase() + text.slice(1);
3
+ }
4
+ export function lowercase(text) {
5
+ return text.toLowerCase();
6
+ }
@@ -0,0 +1,31 @@
1
+ export declare class Utils {
2
+ static hasField(data: any, field: string): boolean;
3
+ static getString(data: any, field: string, defaultVal?: string): string;
4
+ static getNumber(data: Record<string, any>, field: string): number;
5
+ static getInteger(data: any, field: string, defaultVal?: number): number;
6
+ static getBigInteger(data: any, field: string, defaultVal?: number): bigint;
7
+ static getFloat(data: any, field: string, defaultVal?: number): number;
8
+ static getBoolean(data: any, field: string): boolean;
9
+ static getObject(data: Record<string, any>, field: string): Record<string, any>;
10
+ static getArray(data: Record<string, any>, field: string): any[];
11
+ static getDate(data: any, field: string): Date;
12
+ static isMongoDateExpiredFromField(data: any, field: string): boolean;
13
+ static isMongoDateExpired(mongoDate: string | Date): boolean;
14
+ static addIntegerToField(data: any, field: string, amount: number): number;
15
+ static addFloatToField(data: any, field: string, amount: number): number;
16
+ static stringToObject(strData: string): any;
17
+ static stringToArray(strData: string): any[];
18
+ static copyToClipboard(val: string, message?: string): void;
19
+ static isset(obj: Record<string, any> | null | undefined | string | boolean): boolean;
20
+ static issetNum(val: any): boolean;
21
+ static isEmpty(obj: Record<string, any>): boolean;
22
+ static isNotEmpty(obj: Record<string, any>): boolean;
23
+ static shuffleArray<T>(array: T[]): T[];
24
+ static stringToNumber(strVal: string): number;
25
+ static numberFormat(num: number): string;
26
+ static numberFormatDecimals(num: number, decimals?: number): string;
27
+ static generateCode(length?: number): string;
28
+ static generateRandomString(length?: number): string;
29
+ static sleep(ms: number): Promise<void>;
30
+ }
31
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/sdk/utilities/utils.ts"],"names":[],"mappings":"AAEA,qBAAa,KAAK;IACd,MAAM,CAA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AE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAG1C"}
@@ -0,0 +1,133 @@
1
+ import { globalEventEmitter } from "./globalEventHandler";
2
+ export class Utils {
3
+ static hasField(data, field) {
4
+ return this.isNotEmpty(data) && this.isset(data[field]);
5
+ }
6
+ static getString(data, field, defaultVal = '') {
7
+ return this.hasField(data, field) ? data[field] : defaultVal;
8
+ }
9
+ static getNumber(data, field) {
10
+ return this.hasField(data, field) ? data[field] : 0;
11
+ }
12
+ static getInteger(data, field, defaultVal = 0) {
13
+ return this.hasField(data, field) ? parseInt(data[field]) : defaultVal;
14
+ }
15
+ static getBigInteger(data, field, defaultVal = 0) {
16
+ return this.hasField(data, field) ? BigInt(data[field]) : BigInt(defaultVal);
17
+ }
18
+ static getFloat(data, field, defaultVal = 0.0) {
19
+ return this.hasField(data, field) ? parseFloat(data[field]) : defaultVal;
20
+ }
21
+ static getBoolean(data, field) {
22
+ return this.isset(data) && this.isset(data[field]) ? data[field] : false;
23
+ }
24
+ static getObject(data, field) {
25
+ return this.hasField(data, field) ? data[field] : {};
26
+ }
27
+ static getArray(data, field) {
28
+ return this.hasField(data, field) ? data[field] : [];
29
+ }
30
+ static getDate(data, field) {
31
+ const strMongoDate = this.getString(data, field).replace('000', 'Z');
32
+ return new Date(strMongoDate);
33
+ }
34
+ static isMongoDateExpiredFromField(data, field) {
35
+ const oldDate = this.getDate(data, field);
36
+ const oldTime = oldDate.getTime();
37
+ const curTime = Date.now();
38
+ return oldTime < curTime;
39
+ }
40
+ static isMongoDateExpired(mongoDate) {
41
+ const oldDate = new Date(mongoDate);
42
+ return oldDate.getTime() < Date.now();
43
+ }
44
+ static addIntegerToField(data, field, amount) {
45
+ return this.getInteger(data, field) + amount;
46
+ }
47
+ static addFloatToField(data, field, amount) {
48
+ return this.getFloat(data, field) + amount;
49
+ }
50
+ static stringToObject(strData) {
51
+ try {
52
+ return JSON.parse(strData);
53
+ }
54
+ catch (ex) {
55
+ console.log('Error while parsing JSON string:', strData, ex);
56
+ return {};
57
+ }
58
+ }
59
+ static stringToArray(strData) {
60
+ try {
61
+ return JSON.parse(strData);
62
+ }
63
+ catch (ex) {
64
+ return [];
65
+ }
66
+ }
67
+ static copyToClipboard(val, message = 'Text copied') {
68
+ navigator.clipboard.writeText(val)
69
+ .then(() => {
70
+ globalEventEmitter.emit("clipboard", { type: "success", message: "Text copied" });
71
+ })
72
+ .catch((error) => {
73
+ globalEventEmitter.emit("clipboard", { type: "danger", message: `${error.message}` });
74
+ });
75
+ }
76
+ // Check if a value is set
77
+ static isset(obj) {
78
+ if (typeof obj == "string") {
79
+ return obj != "";
80
+ }
81
+ return obj !== null && obj !== undefined && Object.keys(obj).length > 0;
82
+ }
83
+ // Check if a numeric value is set and valid
84
+ static issetNum(val) {
85
+ return val != null && val !== "" && !isNaN(val);
86
+ }
87
+ // Check if an object is empty
88
+ static isEmpty(obj) {
89
+ return Object.keys(obj).length === 0;
90
+ }
91
+ static isNotEmpty(obj) {
92
+ return Object.keys(obj).length > 0;
93
+ }
94
+ // Shuffle the array
95
+ static shuffleArray(array) {
96
+ return array.sort(() => Math.random() - 0.5);
97
+ }
98
+ // Parse a number from a string, extracting only digits
99
+ static stringToNumber(strVal) {
100
+ const num = strVal.match(/\d/g);
101
+ return num ? parseInt(num.join(""), 10) : NaN;
102
+ }
103
+ // Show the number in comma-separated format
104
+ static numberFormat(num) {
105
+ return num.toLocaleString("en-US");
106
+ }
107
+ // Limit the decimal number for the value
108
+ static numberFormatDecimals(num, decimals = 2) {
109
+ return num.toFixed(decimals);
110
+ }
111
+ // Generate a random numeric code of a specified length
112
+ static generateCode(length = 4) {
113
+ let result = "";
114
+ const characters = "123456789";
115
+ for (let i = 0; i < length; i++) {
116
+ result += characters.charAt(Math.floor(Math.random() * characters.length));
117
+ }
118
+ return result;
119
+ }
120
+ // Generate a random alphanumeric string of a specified length
121
+ static generateRandomString(length = 12) {
122
+ let result = "";
123
+ const characters = "ABCDEFGHJKMNOPQRSTUVWXYZ123456789abcdefghijkmnopqrstuvwxyz";
124
+ for (let i = 0; i < length; i++) {
125
+ result += characters.charAt(Math.floor(Math.random() * characters.length));
126
+ }
127
+ return result;
128
+ }
129
+ // Sleep for a specified amount of time
130
+ static sleep(ms) {
131
+ return new Promise((resolve) => setTimeout(resolve, ms));
132
+ }
133
+ }
@@ -0,0 +1,3 @@
1
+ export declare function capitalize(text: string): string;
2
+ export declare function lowercase(text: string): string;
3
+ //# sourceMappingURL=stringUtils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stringUtils.d.ts","sourceRoot":"","sources":["../src/stringUtils.ts"],"names":[],"mappings":"AAAA,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9C"}
@@ -0,0 +1,6 @@
1
+ export function capitalize(text) {
2
+ return text.charAt(0).toUpperCase() + text.slice(1);
3
+ }
4
+ export function lowercase(text) {
5
+ return text.toLowerCase();
6
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=unit_tests.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unit_tests.d.ts","sourceRoot":"","sources":["../src/unit_tests.ts"],"names":[],"mappings":""}