drapcode-utility 2.0.0 → 2.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 (50) hide show
  1. package/build/encryption/KMS.js +54 -102
  2. package/build/encryption/crypt.d.ts +4 -2
  3. package/build/encryption/crypt.js +76 -91
  4. package/build/encryption/file.d.ts +0 -2
  5. package/build/encryption/file.js +14 -130
  6. package/build/encryption/index.js +162 -334
  7. package/build/encryption/utility.js +7 -10
  8. package/build/errors/app-error.js +9 -27
  9. package/build/errors/axios-error.js +3 -3
  10. package/build/errors/bad-request-error.js +10 -28
  11. package/build/errors/custom-error.js +5 -23
  12. package/build/errors/not-found.js +9 -27
  13. package/build/format-fields/index.d.ts +0 -1
  14. package/build/format-fields/index.js +32 -65
  15. package/build/index.d.ts +1 -4
  16. package/build/index.js +1 -4
  17. package/build/middlewares/error-logger.d.ts +1 -1
  18. package/build/middlewares/error-logger.js +29 -29
  19. package/build/middlewares/redis/request-log.js +24 -74
  20. package/build/query/queryBuilder.d.ts +9 -0
  21. package/build/query/queryBuilder.js +567 -0
  22. package/build/utils/check-error.d.ts +15 -8
  23. package/build/utils/check-error.js +71 -160
  24. package/build/utils/common-util.d.ts +40 -39
  25. package/build/utils/common-util.js +60 -59
  26. package/build/utils/date-util.d.ts +28 -7
  27. package/build/utils/date-util.js +180 -127
  28. package/build/utils/file-util.d.ts +51 -6
  29. package/build/utils/file-util.js +36 -40
  30. package/build/utils/prepare-query.js +70 -43
  31. package/build/utils/project-util.d.ts +43 -5
  32. package/build/utils/project-util.js +176 -121
  33. package/build/utils/query-parser.d.ts +1 -1
  34. package/build/utils/query-parser.js +289 -342
  35. package/build/utils/query-utils.d.ts +2 -2
  36. package/build/utils/query-utils.js +103 -116
  37. package/build/utils/rest-client.js +236 -328
  38. package/build/utils/s3-util.js +238 -469
  39. package/build/utils/token.js +34 -81
  40. package/build/utils/util.d.ts +58 -13
  41. package/build/utils/util.js +424 -494
  42. package/build/utils/uuid-generator.d.ts +20 -1
  43. package/build/utils/uuid-generator.js +111 -47
  44. package/package.json +7 -5
  45. package/build/middlewares/interceptor-logger-new.d.ts +0 -2
  46. package/build/middlewares/interceptor-logger-new.js +0 -53
  47. package/build/middlewares/interceptor-logger.d.ts +0 -2
  48. package/build/middlewares/interceptor-logger.js +0 -52
  49. package/build/utils/query-parser-new.d.ts +0 -1
  50. package/build/utils/query-parser-new.js +0 -541
@@ -1,75 +1,29 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
50
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
51
4
  };
52
5
  Object.defineProperty(exports, "__esModule", { value: true });
53
6
  exports.processAndRemoveScriptFromSVG = exports.processAndRemoveExifDataFromImg = exports.fileUploadToS3 = exports.createS3Client = void 0;
54
- var client_s3_1 = require("@aws-sdk/client-s3");
55
- var fs_1 = __importDefault(require("fs"));
56
- var mime_types_1 = __importDefault(require("mime-types"));
57
- var lib_storage_1 = require("@aws-sdk/lib-storage");
58
- var encryption_1 = require("../encryption");
59
- var encryption_2 = require("../encryption");
60
- var uuid_1 = require("uuid");
61
- var gm_1 = __importDefault(require("gm"));
62
- var svgo_1 = require("svgo");
63
- var promises_1 = __importDefault(require("fs/promises"));
64
- var exiftool_vendored_1 = require("exiftool-vendored");
65
- var exiftool = new exiftool_vendored_1.ExifTool({});
66
- var createS3Client = function (awsConfig) {
7
+ const drapcode_constant_1 = require("drapcode-constant");
8
+ const client_s3_1 = require("@aws-sdk/client-s3");
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const mime_types_1 = __importDefault(require("mime-types"));
11
+ const lib_storage_1 = require("@aws-sdk/lib-storage");
12
+ const encryption_1 = require("../encryption");
13
+ const encryption_2 = require("../encryption");
14
+ const uuid_1 = require("uuid");
15
+ const gm_1 = __importDefault(require("gm"));
16
+ const svgo_1 = require("svgo");
17
+ const promises_1 = __importDefault(require("fs/promises"));
18
+ const exiftool_vendored_1 = require("exiftool-vendored");
19
+ const exiftool = new exiftool_vendored_1.ExifTool({});
20
+ const createS3Client = (awsConfig) => {
67
21
  if (!awsConfig) {
68
22
  return null;
69
23
  }
70
- var region = awsConfig.region, accessKey = awsConfig.accessKey, accessSecret = awsConfig.accessSecret;
71
- var s3client = new client_s3_1.S3Client({
72
- region: region,
24
+ const { region, accessKey, accessSecret } = awsConfig;
25
+ const s3client = new client_s3_1.S3Client({
26
+ region,
73
27
  credentials: {
74
28
  accessKeyId: accessKey,
75
29
  secretAccessKey: accessSecret,
@@ -78,327 +32,233 @@ var createS3Client = function (awsConfig) {
78
32
  return s3client;
79
33
  };
80
34
  exports.createS3Client = createS3Client;
81
- var fileUploadToS3 = function (files, s3Client, s3Config, publicS3Client, publicS3Config, isGenerateIcons, encryption, options) {
82
- if (options === void 0) { options = {}; }
83
- return __awaiter(void 0, void 0, void 0, function () {
84
- var awsConfig, encryptionType, dataKey, accessKeyId, secretAccessKey, region, config, plainTextData, fileOptions, s3Key, _a, _b, _c, _i, index, file, fileSlug, fileObj, fileSlug, fileObj;
85
- return __generator(this, function (_d) {
86
- switch (_d.label) {
87
- case 0:
88
- if (!encryption) return [3 /*break*/, 2];
89
- awsConfig = encryption.awsConfig, encryptionType = encryption.encryptionType, dataKey = encryption.dataKey;
90
- if (!(encryptionType === "KMS")) return [3 /*break*/, 2];
91
- accessKeyId = awsConfig.accessKeyId, secretAccessKey = awsConfig.secretAccessKey, region = awsConfig.region;
92
- config = {
93
- region: region,
94
- accessKeyId: accessKeyId,
95
- secretAccessKey: secretAccessKey,
96
- };
97
- return [4 /*yield*/, (0, encryption_2.processKMSDecryption)(config, dataKey, {})];
98
- case 1:
99
- plainTextData = _d.sent();
100
- if (plainTextData.status === "FAILED") {
101
- return [2 /*return*/, plainTextData];
102
- }
103
- encryption.dataKey = plainTextData.data;
104
- _d.label = 2;
105
- case 2:
106
- if (!Array.isArray(files)) return [3 /*break*/, 7];
107
- console.log("I have multiple file");
108
- fileOptions = [];
109
- s3Key = s3Config.key;
110
- _a = files;
111
- _b = [];
112
- for (_c in _a)
113
- _b.push(_c);
114
- _i = 0;
115
- _d.label = 3;
116
- case 3:
117
- if (!(_i < _b.length)) return [3 /*break*/, 6];
118
- _c = _b[_i];
119
- if (!(_c in _a)) return [3 /*break*/, 5];
120
- index = _c;
121
- file = files[index];
122
- fileSlug = slugifyFileName(file.originalname);
123
- if (s3Config.append) {
124
- s3Config.key = "".concat(s3Key, "/").concat((0, uuid_1.v4)(), "/").concat(fileSlug);
125
- }
126
- return [4 /*yield*/, processFileUploadToS3(file, s3Client, s3Config, publicS3Client, publicS3Config, isGenerateIcons, encryption, options, encryption ? true : false)];
127
- case 4:
128
- fileObj = _d.sent();
129
- if (fileObj) {
130
- fileOptions.push(fileObj);
131
- }
132
- _d.label = 5;
133
- case 5:
134
- _i++;
135
- return [3 /*break*/, 3];
136
- case 6: return [2 /*return*/, fileOptions];
137
- case 7:
138
- console.log("I have single file");
139
- fileSlug = slugifyFileName(files.originalname);
140
- if (s3Config.append) {
141
- s3Config.key = "".concat(s3Config.key, "/").concat((0, uuid_1.v4)(), "/").concat(fileSlug);
142
- }
143
- return [4 /*yield*/, processFileUploadToS3(files, s3Client, s3Config, publicS3Client, publicS3Config, isGenerateIcons, encryption, options, encryption ? true : false)];
144
- case 8:
145
- fileObj = _d.sent();
146
- return [2 /*return*/, fileObj];
35
+ const fileUploadToS3 = async (files, s3Client, s3Config, publicS3Client, publicS3Config, isGenerateIcons, encryption, options = {}) => {
36
+ if (encryption) {
37
+ const { awsConfig, encryptionType, dataKey } = encryption;
38
+ if (encryptionType === "KMS") {
39
+ const { accessKeyId, secretAccessKey, region } = awsConfig;
40
+ const config = {
41
+ region,
42
+ accessKeyId,
43
+ secretAccessKey,
44
+ };
45
+ const plainTextData = await (0, encryption_2.processKMSDecryption)(config, dataKey, {});
46
+ if (plainTextData.status === "FAILED") {
47
+ return plainTextData;
147
48
  }
148
- });
149
- });
49
+ encryption.dataKey = plainTextData.data;
50
+ }
51
+ }
52
+ if (Array.isArray(files)) {
53
+ const fileOptions = [];
54
+ const s3Key = s3Config.key;
55
+ for (const file of files) {
56
+ const fileSlug = slugifyFileName(file.originalname);
57
+ if (s3Config.append) {
58
+ s3Config.key = `${s3Key}/${(0, uuid_1.v4)()}/${fileSlug}`;
59
+ }
60
+ const fileObj = await processFileUploadToS3(file, s3Client, s3Config, publicS3Client, publicS3Config, isGenerateIcons, encryption, options, encryption ? true : false);
61
+ if (fileObj) {
62
+ fileOptions.push(fileObj);
63
+ }
64
+ }
65
+ return fileOptions;
66
+ }
67
+ else {
68
+ const fileSlug = slugifyFileName(files.originalname);
69
+ if (s3Config.append) {
70
+ s3Config.key = `${s3Config.key}/${(0, uuid_1.v4)()}/${fileSlug}`;
71
+ }
72
+ return await processFileUploadToS3(files, s3Client, s3Config, publicS3Client, publicS3Config, isGenerateIcons, encryption, options, encryption ? true : false);
73
+ }
150
74
  };
151
75
  exports.fileUploadToS3 = fileUploadToS3;
152
- var processFileUploadToS3 = function (file, s3Client, s3Config, publicS3Client, publicS3Config, isGenerateIcons, encryption, options, encrypt) {
153
- if (options === void 0) { options = {}; }
154
- if (encrypt === void 0) { encrypt = false; }
155
- return __awaiter(void 0, void 0, void 0, function () {
156
- var contentType, acl, key, bucket, params, encryptedFilePath, parallelUploads3, data, _a, smallIcon, mediumIcon, largeIcon, originalname, mimetype, size, error_1;
157
- return __generator(this, function (_b) {
158
- switch (_b.label) {
159
- case 0:
160
- _b.trys.push([0, 6, , 7]);
161
- contentType = mime_types_1.default.lookup(file.originalname) || "";
162
- acl = s3Config.acl, key = s3Config.key, bucket = s3Config.bucket;
163
- params = null;
164
- encryptedFilePath = null;
165
- if (!encrypt) return [3 /*break*/, 2];
166
- return [4 /*yield*/, (0, encryption_1.cryptFile)(file.path, encryption, false)];
167
- case 1:
168
- encryptedFilePath = _b.sent();
169
- params = __assign({ Bucket: bucket, ACL: acl, Key: key, Body: fs_1.default.createReadStream(encryptedFilePath), ContentType: contentType }, options);
170
- return [3 /*break*/, 3];
171
- case 2:
172
- params = __assign({ Bucket: bucket, ACL: acl, Key: key, Body: fs_1.default.createReadStream(file.path), ContentType: contentType }, options);
173
- _b.label = 3;
174
- case 3:
175
- parallelUploads3 = new lib_storage_1.Upload({ client: s3Client, params: params });
176
- return [4 /*yield*/, parallelUploads3.done()];
177
- case 4:
178
- data = _b.sent();
179
- return [4 /*yield*/, handleIconUpload(file, contentType, publicS3Client, publicS3Config, isGenerateIcons, key, options)];
180
- case 5:
181
- _a = _b.sent(), smallIcon = _a.smallIcon, mediumIcon = _a.mediumIcon, largeIcon = _a.largeIcon;
182
- if (data) {
183
- if (encryptedFilePath) {
184
- fs_1.default.unlinkSync(encryptedFilePath);
185
- }
186
- fs_1.default.unlinkSync(file.path);
187
- }
188
- originalname = file.originalname, mimetype = file.mimetype, size = file.size;
189
- return [2 /*return*/, {
190
- originalname: originalname,
191
- mimetype: mimetype,
192
- size: size,
193
- key: data.Key,
194
- contentType: contentType,
195
- smallIcon: smallIcon,
196
- mediumIcon: mediumIcon,
197
- largeIcon: largeIcon,
198
- }];
199
- case 6:
200
- error_1 = _b.sent();
201
- console.error("Error uploading file to S3:", error_1);
202
- return [2 /*return*/, null];
203
- case 7: return [2 /*return*/];
76
+ const processFileUploadToS3 = async (file, s3Client, s3Config, publicS3Client, publicS3Config, isGenerateIcons, encryption, options = {}, encrypt = false) => {
77
+ try {
78
+ const contentType = mime_types_1.default.lookup(file.originalname) || "";
79
+ const { acl, key, bucket } = s3Config;
80
+ let params = null;
81
+ let encryptedFilePath = null;
82
+ if (encrypt) {
83
+ encryptedFilePath = await (0, encryption_1.cryptFile)(file.path, encryption, false);
84
+ params = {
85
+ Bucket: bucket,
86
+ ACL: acl,
87
+ Key: key,
88
+ Body: fs_1.default.createReadStream(encryptedFilePath),
89
+ ContentType: contentType,
90
+ ...options,
91
+ };
92
+ }
93
+ else {
94
+ params = {
95
+ Bucket: bucket,
96
+ ACL: acl,
97
+ Key: key,
98
+ Body: fs_1.default.createReadStream(file.path),
99
+ ContentType: contentType,
100
+ ...options,
101
+ };
102
+ }
103
+ const parallelUploads3 = new lib_storage_1.Upload({ client: s3Client, params });
104
+ const data = await parallelUploads3.done();
105
+ const { smallIcon, mediumIcon, largeIcon } = await handleIconUpload(file, contentType, publicS3Client, publicS3Config, isGenerateIcons, key, options);
106
+ if (data) {
107
+ if (encryptedFilePath) {
108
+ fs_1.default.unlinkSync(encryptedFilePath);
204
109
  }
205
- });
206
- });
110
+ fs_1.default.unlinkSync(file.path);
111
+ }
112
+ const { originalname, mimetype, size } = file;
113
+ return {
114
+ originalname,
115
+ mimetype,
116
+ size,
117
+ key: data.Key,
118
+ contentType,
119
+ smallIcon,
120
+ mediumIcon,
121
+ largeIcon,
122
+ };
123
+ }
124
+ catch (error) {
125
+ console.error("Error uploading file to S3:", error);
126
+ return null;
127
+ }
207
128
  };
208
- var imageTypeFiles = [
209
- "image/png",
210
- "image/jpeg",
211
- "image/jpg",
212
- "image/heic",
213
- "image/webp",
214
- "image/heif",
215
- ];
216
- var processAndRemoveExifDataFromImg = function (files) { return __awaiter(void 0, void 0, void 0, function () {
217
- var promises, error_2;
218
- return __generator(this, function (_a) {
219
- switch (_a.label) {
220
- case 0:
221
- _a.trys.push([0, 3, , 4]);
222
- files = Array.isArray(files) ? files : [files];
223
- files = files.filter(function (file) { return imageTypeFiles.includes(file.mimetype); });
224
- promises = [];
225
- if (!files.length) return [3 /*break*/, 2];
226
- promises = files.map(function (file) { return __awaiter(void 0, void 0, void 0, function () {
227
- return __generator(this, function (_a) {
228
- switch (_a.label) {
229
- case 0: return [4 /*yield*/, exiftool
230
- .write(file.path, {}, { writeArgs: ["-all=", "-overwrite_original"] })
231
- .catch(function (err) {
232
- console.error("Error processing image:", err);
233
- throw err;
234
- })];
235
- case 1:
236
- // Remove EXIF data using exiftool
237
- return [2 /*return*/, _a.sent()];
238
- }
239
- });
240
- }); });
241
- return [4 /*yield*/, Promise.all(promises)];
242
- case 1:
243
- _a.sent();
244
- _a.label = 2;
245
- case 2: return [2 /*return*/, promises];
246
- case 3:
247
- error_2 = _a.sent();
248
- console.error("\n error :>> ", error_2);
249
- return [3 /*break*/, 4];
250
- case 4: return [2 /*return*/];
129
+ const imageTypeFiles = [...drapcode_constant_1.imageMimeTypes, "image/jpg"];
130
+ const processAndRemoveExifDataFromImg = async (files) => {
131
+ try {
132
+ files = Array.isArray(files) ? files : [files];
133
+ files = files.filter((file) => imageTypeFiles.includes(file.mimetype));
134
+ let promises = [];
135
+ if (files.length) {
136
+ promises = files.map(async (file) => {
137
+ // Remove EXIF data using exiftool
138
+ return await exiftool
139
+ .write(file.path, {}, { writeArgs: ["-all=", "-overwrite_original"] })
140
+ .catch((err) => {
141
+ console.error("Error processing image:", err);
142
+ throw err;
143
+ });
144
+ });
145
+ await Promise.all(promises);
251
146
  }
252
- });
253
- }); };
147
+ return promises;
148
+ }
149
+ catch (error) {
150
+ console.error("\n error :>> ", error);
151
+ }
152
+ };
254
153
  exports.processAndRemoveExifDataFromImg = processAndRemoveExifDataFromImg;
255
- var processAndRemoveScriptFromSVG = function (files) { return __awaiter(void 0, void 0, void 0, function () {
256
- var promises, error_3;
257
- return __generator(this, function (_a) {
258
- switch (_a.label) {
259
- case 0:
260
- _a.trys.push([0, 3, , 4]);
261
- files = Array.isArray(files) ? files : [files];
262
- files = files.filter(function (file) { return file.mimetype === "image/svg+xml"; });
263
- if (!files.length) return [3 /*break*/, 2];
264
- promises = files.map(function (file) { return __awaiter(void 0, void 0, void 0, function () {
265
- var fileContent, sanitizedContent;
266
- return __generator(this, function (_a) {
267
- switch (_a.label) {
268
- case 0: return [4 /*yield*/, promises_1.default.readFile(file.path, "utf-8")];
269
- case 1:
270
- fileContent = _a.sent();
271
- sanitizedContent = (0, svgo_1.optimize)(fileContent, {
272
- plugins: [
273
- "removeScriptElement",
274
- "removeDesc",
275
- "removeTitle",
276
- "removeMetadata",
277
- "removeComments",
278
- "removeXMLProcInst",
279
- "removeDoctype",
280
- "cleanupAttrs",
281
- {
282
- name: "removeAttrs",
283
- params: {
284
- attrs: "(on.*)", // Matches attributes starting with "on" (e.g., onclick, onmouseover)
285
- },
286
- },
287
- {
288
- name: "removeForeignObject",
289
- fn: function (item) {
290
- if (item.name === "foreignObject") {
291
- return null; // Remove this element
292
- }
293
- else
294
- return item;
295
- },
296
- },
297
- ],
298
- });
299
- return [4 /*yield*/, promises_1.default.writeFile(file.path, sanitizedContent.data, "utf-8")];
300
- case 2:
301
- _a.sent();
302
- return [2 /*return*/];
303
- }
304
- });
305
- }); });
306
- return [4 /*yield*/, Promise.all(promises)];
307
- case 1:
308
- _a.sent();
309
- _a.label = 2;
310
- case 2: return [3 /*break*/, 4];
311
- case 3:
312
- error_3 = _a.sent();
313
- console.error("\n error :>> ", error_3);
314
- return [3 /*break*/, 4];
315
- case 4: return [2 /*return*/];
154
+ const processAndRemoveScriptFromSVG = async (files) => {
155
+ if (!files || !files.length) {
156
+ return;
157
+ }
158
+ try {
159
+ files = Array.isArray(files) ? files : [files];
160
+ files = files.filter((file) => file.mimetype === "image/svg+xml");
161
+ if (!files || !files.length) {
162
+ return;
316
163
  }
317
- });
318
- }); };
319
- exports.processAndRemoveScriptFromSVG = processAndRemoveScriptFromSVG;
320
- var handleIconUpload = function (file, contentType, publicS3Client, publicS3Config, isGenerateIcons, key, options) {
321
- if (options === void 0) { options = {}; }
322
- return __awaiter(void 0, void 0, void 0, function () {
323
- var filePath, fileSize, iconSizes, iconLabels, iconFiles, bucket_1, acl_1, iconUploads, _a, smallKey, mediumKey, largeKey, iconError_1;
324
- return __generator(this, function (_b) {
325
- switch (_b.label) {
326
- case 0:
327
- filePath = file.path, fileSize = file.size;
328
- iconSizes = [200, 300, 500];
329
- iconLabels = ["small", "medium", "large"];
330
- _b.label = 1;
331
- case 1:
332
- _b.trys.push([1, 6, , 7]);
333
- if (!(isGenerateIcons &&
334
- fileSize < 157286400 && //150mb
335
- [
336
- "image/png",
337
- "image/jpeg",
338
- "image/gif",
339
- "image/webp",
340
- "image/heif",
341
- "image/heic",
342
- "application/pdf",
343
- ].includes(contentType))) return [3 /*break*/, 4];
344
- return [4 /*yield*/, generateDynamicIcons(filePath, iconSizes, contentType)];
345
- case 2:
346
- iconFiles = _b.sent();
347
- bucket_1 = publicS3Config.bucket, acl_1 = publicS3Config.acl;
348
- iconUploads = iconFiles.map(function (iconFilePath, index) { return __awaiter(void 0, void 0, void 0, function () {
349
- var iconLabel, iconKey, iconParams, iconUpload, iconData;
350
- return __generator(this, function (_a) {
351
- switch (_a.label) {
352
- case 0:
353
- iconLabel = iconLabels[index];
354
- iconKey = "".concat(key, "/icons/").concat((0, uuid_1.v4)(), "_").concat(iconLabel, ".png");
355
- iconParams = __assign({ Bucket: bucket_1, ACL: acl_1, Key: iconKey, Body: fs_1.default.createReadStream(iconFilePath), ContentType: "image/png" }, options);
356
- iconUpload = new lib_storage_1.Upload({
357
- client: publicS3Client,
358
- params: iconParams,
359
- });
360
- return [4 /*yield*/, iconUpload.done()];
361
- case 1:
362
- iconData = _a.sent();
363
- fs_1.default.unlinkSync(iconFilePath);
364
- return [2 /*return*/, iconData.Key];
164
+ let promises = files.map(async (file) => {
165
+ const fileContent = await promises_1.default.readFile(file.path, "utf-8");
166
+ const sanitizedContent = (0, svgo_1.optimize)(fileContent, {
167
+ plugins: [
168
+ "removeScriptElement", // Remove <script>,
169
+ "removeDesc",
170
+ "removeTitle",
171
+ "removeMetadata",
172
+ "removeComments",
173
+ "removeXMLProcInst",
174
+ "removeDoctype",
175
+ "cleanupAttrs",
176
+ {
177
+ name: "removeAttrs", // Plugin to remove event handlers (e.g., onclick)
178
+ params: {
179
+ attrs: "(on.*)", // Matches attributes starting with "on" (e.g., onclick, onmouseover)
180
+ },
181
+ },
182
+ {
183
+ name: "removeForeignObject", // Custom plugin to remove <foreignObject>
184
+ fn: (item) => {
185
+ if (item.name === "foreignObject") {
186
+ return null; // Remove this element
365
187
  }
366
- });
367
- }); });
368
- return [4 /*yield*/, Promise.all(iconUploads)];
369
- case 3:
370
- _a = _b.sent(), smallKey = _a[0], mediumKey = _a[1], largeKey = _a[2];
371
- return [2 /*return*/, {
372
- smallIcon: smallKey
373
- ? "https://".concat(bucket_1, ".s3.amazonaws.com/").concat(smallKey)
374
- : null,
375
- mediumIcon: mediumKey
376
- ? "https://".concat(bucket_1, ".s3.amazonaws.com/").concat(mediumKey)
377
- : null,
378
- largeIcon: largeKey
379
- ? "https://".concat(bucket_1, ".s3.amazonaws.com/").concat(largeKey)
380
- : null,
381
- }];
382
- case 4: return [2 /*return*/, generateStaticIcons(contentType)];
383
- case 5: return [3 /*break*/, 7];
384
- case 6:
385
- iconError_1 = _b.sent();
386
- console.error("Error generating or uploading icons:", iconError_1);
387
- return [2 /*return*/, generateStaticIcons(contentType)];
388
- case 7: return [2 /*return*/];
389
- }
188
+ else
189
+ return item;
190
+ },
191
+ },
192
+ ],
193
+ });
194
+ await promises_1.default.writeFile(file.path, sanitizedContent.data, "utf-8");
390
195
  });
391
- });
196
+ await Promise.all(promises);
197
+ }
198
+ catch (error) {
199
+ console.error("\n error :>> ", error);
200
+ }
201
+ };
202
+ exports.processAndRemoveScriptFromSVG = processAndRemoveScriptFromSVG;
203
+ const handleIconUpload = async (file, contentType, publicS3Client, publicS3Config, isGenerateIcons, key, options = {}) => {
204
+ const { path: filePath, size: fileSize } = file;
205
+ const iconSizes = [200, 300, 500];
206
+ const iconLabels = ["small", "medium", "large"];
207
+ try {
208
+ if (isGenerateIcons &&
209
+ fileSize < 157286400 && //150mb
210
+ [...drapcode_constant_1.imageMimeTypes, "application/pdf", "image/gif"].includes(contentType)) {
211
+ const iconFiles = await generateDynamicIcons(filePath, iconSizes, contentType);
212
+ const { bucket, acl } = publicS3Config;
213
+ const iconUploads = iconFiles.map(async (iconFilePath, index) => {
214
+ const iconLabel = iconLabels[index];
215
+ const iconKey = `${key}/icons/${(0, uuid_1.v4)()}_${iconLabel}.png`;
216
+ const iconParams = {
217
+ Bucket: bucket,
218
+ ACL: acl,
219
+ Key: iconKey,
220
+ Body: fs_1.default.createReadStream(iconFilePath),
221
+ ContentType: "image/png",
222
+ ...options,
223
+ };
224
+ const iconUpload = new lib_storage_1.Upload({
225
+ client: publicS3Client,
226
+ params: iconParams,
227
+ });
228
+ const iconData = await iconUpload.done();
229
+ fs_1.default.unlinkSync(iconFilePath);
230
+ return iconData.Key;
231
+ });
232
+ const [smallKey, mediumKey, largeKey] = await Promise.all(iconUploads);
233
+ return {
234
+ smallIcon: generateS3IconUrl(bucket, smallKey),
235
+ mediumIcon: generateS3IconUrl(bucket, mediumKey),
236
+ largeIcon: generateS3IconUrl(bucket, largeKey),
237
+ };
238
+ }
239
+ else {
240
+ return generateStaticIcons(contentType);
241
+ }
242
+ }
243
+ catch (iconError) {
244
+ console.error("Error generating or uploading icons:", iconError);
245
+ return generateStaticIcons(contentType);
246
+ }
247
+ };
248
+ const generateS3IconUrl = (bucket, key) => {
249
+ if (!key)
250
+ return null;
251
+ return `https://${bucket}.s3.amazonaws.com/${key}`;
392
252
  };
393
- var generateDynamicIcons = function (filePath, sizes, contentType) {
394
- return Promise.all(sizes.map(function (size) {
395
- var outputFilePath = "".concat(filePath, "_").concat(size, ".png");
396
- return new Promise(function (resolve, reject) {
397
- var gmInstance = (0, gm_1.default)(filePath);
253
+ const generateDynamicIcons = (filePath, sizes, contentType) => {
254
+ return Promise.all(sizes.map((size) => {
255
+ const outputFilePath = `${filePath}_${size}.png`;
256
+ return new Promise((resolve, reject) => {
257
+ let gmInstance = (0, gm_1.default)(filePath);
398
258
  if (contentType === "application/pdf") {
399
259
  gmInstance = gmInstance.selectFrame(0);
400
260
  }
401
- gmInstance.resize(size, size).write(outputFilePath, function (err) {
261
+ gmInstance.resize(size, size).write(outputFilePath, (err) => {
402
262
  if (err) {
403
263
  reject(err);
404
264
  }
@@ -409,106 +269,15 @@ var generateDynamicIcons = function (filePath, sizes, contentType) {
409
269
  });
410
270
  }));
411
271
  };
412
- var generateStaticIcons = function (type) {
413
- var smallIcon;
414
- var mediumIcon;
415
- var largeIcon;
416
- switch (type) {
417
- case "image/png":
418
- case "image/jpeg":
419
- case "image/gif":
420
- case "image/heif":
421
- case "image/webp":
422
- case "image/heic":
423
- smallIcon =
424
- "https://drapcode-static.s3.amazonaws.com/img/placeholder-img.png";
425
- mediumIcon =
426
- "https://drapcode-static.s3.amazonaws.com/img/placeholder-img.png";
427
- largeIcon =
428
- "https://drapcode-static.s3.amazonaws.com/img/placeholder-img.png";
429
- break;
430
- case "application/zip":
431
- smallIcon = "https://drapcode-static.s3.amazonaws.com/img/zip.png";
432
- mediumIcon = "https://drapcode-static.s3.amazonaws.com/img/zip.png";
433
- largeIcon = "https://drapcode-static.s3.amazonaws.com/img/zip.png";
434
- break;
435
- case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": //xlsx
436
- case "application/vnd.ms-excel": //xls
437
- smallIcon = "https://drapcode-static.s3.amazonaws.com/img/excel.png";
438
- mediumIcon = "https://drapcode-static.s3.amazonaws.com/img/excel.png";
439
- largeIcon = "https://drapcode-static.s3.amazonaws.com/img/excel.png ";
440
- break;
441
- case "application/pdf":
442
- smallIcon = "https://drapcode-static.s3.amazonaws.com/img/pdf-file.png";
443
- mediumIcon = "https://drapcode-static.s3.amazonaws.com/img/pdf-file.png";
444
- largeIcon = "https://drapcode-static.s3.amazonaws.com/img/pdf-file.png";
445
- break;
446
- case "text/csv":
447
- smallIcon = "https://drapcode-static.s3.amazonaws.com/img/csv.png";
448
- mediumIcon = "https://drapcode-static.s3.amazonaws.com/img/csv.png";
449
- largeIcon = "https://drapcode-static.s3.amazonaws.com/img/csv.png";
450
- break;
451
- case "application/msword": //doc
452
- case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": //docx
453
- smallIcon =
454
- "https://drapcode-static.s3.amazonaws.com/img/google-docs.png";
455
- mediumIcon =
456
- "https://drapcode-static.s3.amazonaws.com/img/google-docs.png";
457
- largeIcon =
458
- "https://drapcode-static.s3.amazonaws.com/img/google-docs.png";
459
- break;
460
- case "text/plain":
461
- smallIcon = "https://drapcode-static.s3.amazonaws.com/img/txt.png";
462
- mediumIcon = "https://drapcode-static.s3.amazonaws.com/img/txt.png";
463
- largeIcon = "https://drapcode-static.s3.amazonaws.com/img/txt.png";
464
- break;
465
- case "application/rtf":
466
- smallIcon =
467
- "https://drapcode-static.s3.amazonaws.com/img/rtf-file-symbol.png";
468
- mediumIcon =
469
- "https://drapcode-static.s3.amazonaws.com/img/rtf-file-symbol.png";
470
- largeIcon =
471
- "https://drapcode-static.s3.amazonaws.com/img/rtf-file-symbol.png";
472
- break;
473
- case "text/html":
474
- smallIcon = "https://drapcode-static.s3.amazonaws.com/img/html.png";
475
- mediumIcon = "https://drapcode-static.s3.amazonaws.com/img/html.png";
476
- largeIcon = "https://drapcode-static.s3.amazonaws.com/img/html.png";
477
- break;
478
- case "audio/mpeg":
479
- smallIcon =
480
- "https://drapcode-static.s3.amazonaws.com/img/placeholder-audio.png";
481
- mediumIcon =
482
- "https://drapcode-static.s3.amazonaws.com/img/placeholder-audio.png";
483
- largeIcon =
484
- "https://drapcode-static.s3.amazonaws.com/img/placeholder-audio.png";
485
- break;
486
- case "video/mpeg": //mpg
487
- case "video/x-flv": //flv
488
- case "video/x-msvideo": //avi
489
- smallIcon = "https://drapcode-static.s3.amazonaws.com/img/video.png";
490
- mediumIcon = "https://drapcode-static.s3.amazonaws.com/img/video.png";
491
- largeIcon = "https://drapcode-static.s3.amazonaws.com/img/video.png";
492
- break;
493
- case "application/vnd.ms-powerpoint": //ppt
494
- case "application/vnd.openxmlformats-officedocument.presentationml.presentation": //pptx
495
- smallIcon = "https://drapcode-static.s3.amazonaws.com/img/powerpoint.png";
496
- mediumIcon =
497
- "https://drapcode-static.s3.amazonaws.com/img/powerpoint.png";
498
- largeIcon = "https://drapcode-static.s3.amazonaws.com/img/powerpoint.png";
499
- break;
500
- default:
501
- smallIcon =
502
- "https://drapcode-static.s3.amazonaws.com/img/google-docs.png";
503
- mediumIcon =
504
- "https://drapcode-static.s3.amazonaws.com/img/google-docs.png";
505
- largeIcon =
506
- "https://drapcode-static.s3.amazonaws.com/img/google-docs.png";
507
- break;
508
- }
509
- return { smallIcon: smallIcon, mediumIcon: mediumIcon, largeIcon: largeIcon };
272
+ const generateStaticIcons = (type) => {
273
+ const icon = drapcode_constant_1.iconMaps[type] || drapcode_constant_1.defaultIcon;
274
+ return {
275
+ smallIcon: icon,
276
+ mediumIcon: icon,
277
+ largeIcon: icon,
278
+ };
510
279
  };
511
- var slugifyFileName = function (fileName) {
280
+ const slugifyFileName = (fileName) => {
512
281
  return fileName
513
282
  .replace(/\s+/g, "_") // Replace spaces with underscores
514
283
  .replace(/[^a-zA-Z0-9._]/g, "") // Remove anything that's not a letter, number, dot, or underscore