prostgles-server 2.0.188 → 2.0.191

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 (40) hide show
  1. package/dist/DboBuilder/insertDataParse.d.ts.map +1 -1
  2. package/dist/DboBuilder/insertDataParse.js +14 -4
  3. package/dist/DboBuilder/insertDataParse.js.map +1 -1
  4. package/dist/DboBuilder.d.ts +5 -3
  5. package/dist/DboBuilder.d.ts.map +1 -1
  6. package/dist/DboBuilder.js +67 -161
  7. package/dist/DboBuilder.js.map +1 -1
  8. package/dist/FileManager.d.ts +20 -72
  9. package/dist/FileManager.d.ts.map +1 -1
  10. package/dist/FileManager.js +232 -164
  11. package/dist/FileManager.js.map +1 -1
  12. package/dist/Prostgles.d.ts +13 -2
  13. package/dist/Prostgles.d.ts.map +1 -1
  14. package/dist/Prostgles.js.map +1 -1
  15. package/dist/TableConfig.d.ts +1 -2
  16. package/dist/TableConfig.d.ts.map +1 -1
  17. package/dist/TableConfig.js.map +1 -1
  18. package/lib/DboBuilder/insertDataParse.d.ts.map +1 -1
  19. package/lib/DboBuilder/insertDataParse.js +14 -4
  20. package/lib/DboBuilder/insertDataParse.ts +14 -4
  21. package/lib/DboBuilder.d.ts +5 -3
  22. package/lib/DboBuilder.d.ts.map +1 -1
  23. package/lib/DboBuilder.js +67 -161
  24. package/lib/DboBuilder.ts +84 -191
  25. package/lib/FileManager.d.ts +19 -71
  26. package/lib/FileManager.d.ts.map +1 -1
  27. package/lib/FileManager.js +232 -164
  28. package/lib/FileManager.ts +272 -191
  29. package/lib/Prostgles.d.ts +13 -2
  30. package/lib/Prostgles.d.ts.map +1 -1
  31. package/lib/Prostgles.ts +2 -2
  32. package/lib/TableConfig.d.ts +1 -2
  33. package/lib/TableConfig.d.ts.map +1 -1
  34. package/lib/TableConfig.ts +2 -4
  35. package/lib/fileType/core.js +1527 -0
  36. package/lib/fileType/supported.js +278 -0
  37. package/package.json +5 -5
  38. package/tests/client/PID.txt +1 -1
  39. package/tests/server/DBoGenerated.d.ts +1 -1
  40. package/tests/server/package-lock.json +9 -9
@@ -23,12 +23,12 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.asSQLIdentifier = void 0;
26
+ exports.getFileType = exports.getFileTypeFromFilename = exports.asSQLIdentifier = void 0;
27
27
  const aws_sdk_1 = require("aws-sdk");
28
28
  const fs = __importStar(require("fs"));
29
- const FileType = __importStar(require("file-type"));
30
29
  const sharp = __importStar(require("sharp"));
31
30
  const prostgles_types_1 = require("prostgles-types");
31
+ const DboBuilder_1 = require("./DboBuilder");
32
32
  const HOUR = 3600 * 1000;
33
33
  const asSQLIdentifier = async (name, db) => {
34
34
  return (await db.one("select format('%I', $1) as name", [name]))?.name;
@@ -81,6 +81,18 @@ class FileManager {
81
81
  return res;
82
82
  };
83
83
  this.parseSQLIdentifier = async (name) => (0, exports.asSQLIdentifier)(name, this.prostgles.db); // this.prostgles.dbo.sql<"value">("select format('%I', $1)", [name], { returnType: "value" } )
84
+ this.getColInfo = (args) => {
85
+ const { colName, tableName } = args;
86
+ const tableConfig = this.prostgles?.opts.fileTable?.referencedTables?.[tableName];
87
+ const isReferencingFileTable = this.dbo[tableName]?.columns?.some(c => c.name === colName && c.references && c.references?.ftable === this.tableName);
88
+ if (isReferencingFileTable) {
89
+ if (tableConfig && typeof tableConfig !== "string") {
90
+ return tableConfig.referenceColumns[colName];
91
+ }
92
+ return { acceptedContent: "*" };
93
+ }
94
+ return undefined;
95
+ };
84
96
  this.init = async (prg) => {
85
97
  this.prostgles = prg;
86
98
  // const { dbo, db, opts } = prg;
@@ -121,56 +133,96 @@ class FileManager {
121
133
  /**
122
134
  * 2. Create media lookup tables
123
135
  */
124
- await Promise.all(Object.keys(referencedTables).map(async (refTable) => {
136
+ await Promise.all((0, prostgles_types_1.getKeys)(referencedTables).map(async (refTable) => {
125
137
  if (!this.dbo[refTable])
126
- throw `Referenced table (${refTable}) from fileTable.referencedTables record is missing`;
127
- // const lookupTableName = asName(`lookup_${tableName}_${refTable}`);
128
- const lookupTableName = await this.parseSQLIdentifier(`prostgles_lookup_${tableName}_${refTable}`);
129
- const pKeyFields = (await this.dbo[refTable].getColumns()).filter(f => f.is_pkey);
130
- if (pKeyFields.length !== 1)
131
- throw `Could not make link table for ${refTable}. ${pKeyFields} must have exactly one primary key column. Current pkeys: ${pKeyFields.map(f => f.name)}`;
132
- const pkField = pKeyFields[0];
133
- const refType = referencedTables[refTable];
134
- if (!this.dbo[lookupTableName]) {
135
- // if(!(await dbo[lookupTableName].count())) await db.any(`DROP TABLE IF EXISTS ${lookupTableName};`);
136
- const action = ` (${tableName} <-> ${refTable}) join table ${lookupTableName}`; // PRIMARY KEY
137
- const query = `
138
- CREATE TABLE ${lookupTableName} (
139
- foreign_id ${pkField.udt_name} ${refType === "one" ? " PRIMARY KEY " : ""} REFERENCES ${(0, prostgles_types_1.asName)(refTable)}(${(0, prostgles_types_1.asName)(pkField.name)}),
140
- media_id UUID NOT NULL REFERENCES ${(0, prostgles_types_1.asName)(tableName)}(id)
141
- )
142
- `;
143
- console.log(`Creating ${action} ...`, lookupTableName);
144
- await this.db.any(query);
145
- console.log(`Created ${action}`);
146
- }
147
- else {
148
- const cols = await this.dbo[lookupTableName].getColumns();
149
- const badCols = cols.filter(c => !c.references);
150
- await Promise.all(badCols.map(async (badCol) => {
151
- console.error(`Prostgles: media ${lookupTableName} joining table has lost a reference constraint for column ${badCol.name}.` +
152
- ` This may have been caused by a DROP TABLE ... CASCADE.`);
153
- let q = `
154
- ALTER TABLE ${(0, prostgles_types_1.asName)(lookupTableName)}
155
- ADD CONSTRAINT ${(lookupTableName + "_" + badCol.name + "_r")} FOREIGN KEY (${badCol.name})
156
- `;
157
- console.log("Trying to add the missing constraint back");
158
- if (badCol.name === "foreign_id") {
159
- q += `REFERENCES ${(0, prostgles_types_1.asName)(refTable)}(${(0, prostgles_types_1.asName)(pkField.name)}) `;
160
- }
161
- else if (badCol.name === "media_id") {
162
- q += `REFERENCES ${(0, prostgles_types_1.asName)(tableName)}(id) `;
138
+ throw `Referenced table (${refTable}) from fileTable.referencedTables prostgles init config is missing`;
139
+ const cols = await this.dbo[refTable].getColumns();
140
+ const tableConfig = referencedTables[refTable];
141
+ if (typeof tableConfig !== "string") {
142
+ for await (const colName of (0, prostgles_types_1.getKeys)(tableConfig.referenceColumns)) {
143
+ const existingCol = cols.find(c => c.name === colName);
144
+ if (existingCol) {
145
+ if (existingCol.references?.ftable === tableName) {
146
+ // All ok
147
+ }
148
+ else {
149
+ if (existingCol.udt_name === "uuid") {
150
+ try {
151
+ const query = `ALTER TABLE ${(0, prostgles_types_1.asName)(tableName)} ADD CONSTRAINT FOREIGN KEY (${(0, prostgles_types_1.asName)(colName)}) REFERENCES ${(0, prostgles_types_1.asName)(tableName)} (id);`;
152
+ console.log(`Referenced file column ${refTable} (${colName}) exists but is not referencing file table. Trying to add REFERENCE constraing...\n${query}`);
153
+ await this.db.any(query);
154
+ console.log("SUCCESS: " + query);
155
+ }
156
+ catch (e) {
157
+ throw new Error(`Could not add constraing. Err: ${e instanceof Error ? e.message : JSON.stringify(e)}`);
158
+ }
159
+ }
160
+ else {
161
+ throw new Error(`Referenced file column ${refTable} (${colName}) exists but is not of required type (UUID). Choose a different column name or ALTER the existing column to match the type and the data found in file table ${tableName}(id)`);
162
+ }
163
+ }
163
164
  }
164
- if (q) {
165
+ else {
165
166
  try {
166
- await this.db.any(q);
167
- console.log("Added missing constraint back");
167
+ const query = `ALTER TABLE ${(0, prostgles_types_1.asName)(tableName)} ADD COLUMN ${(0, prostgles_types_1.asName)(colName)} UUID REFERENCES ${(0, prostgles_types_1.asName)(tableName)} (id);`;
168
+ console.log(`Creating referenced file column ${refTable} (${colName})...\n${query}`);
169
+ await this.db.any(query);
170
+ console.log("SUCCESS: " + query);
168
171
  }
169
172
  catch (e) {
170
- console.error("Failed to add missing constraint", e);
173
+ throw new Error(`FAILED. Err: ${e instanceof Error ? e.message : JSON.stringify(e)}`);
171
174
  }
172
175
  }
173
- }));
176
+ }
177
+ }
178
+ else {
179
+ const lookupTableName = await this.parseSQLIdentifier(`prostgles_lookup_${tableName}_${refTable}`);
180
+ const pKeyFields = cols.filter(f => f.is_pkey);
181
+ if (pKeyFields.length !== 1)
182
+ throw `Could not make link table for ${refTable}. ${pKeyFields} must have exactly one primary key column. Current pkeys: ${pKeyFields.map(f => f.name)}`;
183
+ const pkField = pKeyFields[0];
184
+ const refType = referencedTables[refTable];
185
+ if (!this.dbo[lookupTableName]) {
186
+ // if(!(await dbo[lookupTableName].count())) await db.any(`DROP TABLE IF EXISTS ${lookupTableName};`);
187
+ const action = ` (${tableName} <-> ${refTable}) join table ${lookupTableName}`; // PRIMARY KEY
188
+ const query = `
189
+ CREATE TABLE ${lookupTableName} (
190
+ foreign_id ${pkField.udt_name} ${refType === "one" ? " PRIMARY KEY " : ""} REFERENCES ${(0, prostgles_types_1.asName)(refTable)}(${(0, prostgles_types_1.asName)(pkField.name)}),
191
+ media_id UUID NOT NULL REFERENCES ${(0, prostgles_types_1.asName)(tableName)}(id)
192
+ )
193
+ `;
194
+ console.log(`Creating ${action} ...`, lookupTableName);
195
+ await this.db.any(query);
196
+ console.log(`Created ${action}`);
197
+ }
198
+ else {
199
+ const cols = await this.dbo[lookupTableName].getColumns();
200
+ const badCols = cols.filter(c => !c.references);
201
+ await Promise.all(badCols.map(async (badCol) => {
202
+ console.error(`Prostgles: media ${lookupTableName} joining table has lost a reference constraint for column ${badCol.name}.` +
203
+ ` This may have been caused by a DROP TABLE ... CASCADE.`);
204
+ let q = `
205
+ ALTER TABLE ${(0, prostgles_types_1.asName)(lookupTableName)}
206
+ ADD CONSTRAINT ${(lookupTableName + "_" + badCol.name + "_r")} FOREIGN KEY (${badCol.name})
207
+ `;
208
+ console.log("Trying to add the missing constraint back");
209
+ if (badCol.name === "foreign_id") {
210
+ q += `REFERENCES ${(0, prostgles_types_1.asName)(refTable)}(${(0, prostgles_types_1.asName)(pkField.name)}) `;
211
+ }
212
+ else if (badCol.name === "media_id") {
213
+ q += `REFERENCES ${(0, prostgles_types_1.asName)(tableName)}(id) `;
214
+ }
215
+ if (q) {
216
+ try {
217
+ await this.db.any(q);
218
+ console.log("Added missing constraint back");
219
+ }
220
+ catch (e) {
221
+ console.error("Failed to add missing constraint", e);
222
+ }
223
+ }
224
+ }));
225
+ }
174
226
  }
175
227
  await prg.refreshDBO();
176
228
  return true;
@@ -251,63 +303,108 @@ class FileManager {
251
303
  return this.prostgles.db;
252
304
  }
253
305
  ;
254
- async getMIME(file, fileName, allowedExtensions, dissallowedExtensions, onlyFromName = true) {
255
- const nameParts = fileName.split(".");
256
- const nameExt = nameParts[nameParts.length - 1].toLowerCase(), mime = (0, prostgles_types_1.getKeys)(CONTENT_TYPE_TO_EXT).find(k => CONTENT_TYPE_TO_EXT[k].includes(nameExt));
257
- let type = {
258
- fileName,
259
- mime,
260
- ext: nameExt,
261
- };
262
- if (onlyFromName && !mime)
263
- throw `Invalid file extension: content_type could not be found for extension(${nameExt})`;
264
- if (!mime) {
265
- /* Set correct/missing extension */
266
- if (["xml", "txt", "csv", "tsv", "doc"].includes(nameExt)) {
267
- type = { ...type, mime: ("text/" + nameExt), ext: nameExt };
268
- }
269
- else if (["svg"].includes(nameExt)) {
270
- type = { ...type, mime: "image/svg+xml", ext: nameExt };
271
- }
272
- else if (Buffer.isBuffer(file)) {
273
- const res = await FileType.fromBuffer(file);
274
- type = {
275
- ...res,
276
- fileName,
277
- };
278
- }
279
- else if (typeof file === "string") {
280
- const res = await FileType.fromFile(file);
281
- type = {
282
- ...res,
283
- fileName,
284
- };
285
- }
286
- else {
287
- throw "Unexpected file. Expecting: Buffer | String";
306
+ async parseFile(args) {
307
+ const { file, fileName, tableName, colName } = args;
308
+ const config = this.prostgles?.opts.fileTable;
309
+ if (!config)
310
+ throw new Error("File table config missing");
311
+ const buffer = typeof file === "string" ? Buffer.from(file, 'utf8') : file;
312
+ const mime = await (0, exports.getFileType)(buffer, fileName);
313
+ if (tableName && colName) {
314
+ const tableConfig = config.referencedTables?.[tableName];
315
+ if (tableConfig && (0, prostgles_types_1.isObject)(tableConfig) && tableConfig.referenceColumns[colName]) {
316
+ const colConfig = tableConfig.referenceColumns[colName];
317
+ if (colConfig.maxFileSizeMB) {
318
+ const actualBufferSize = Buffer.byteLength(buffer);
319
+ if ((actualBufferSize / 1e6) > colConfig.maxFileSizeMB) {
320
+ throw new Error(`Provided file is larger than the ${colConfig.maxFileSizeMB}MB limit`);
321
+ }
322
+ }
323
+ if ("acceptedContent" in colConfig && colConfig.acceptedContent) {
324
+ const CONTENTS = [
325
+ "image",
326
+ "audio",
327
+ "video",
328
+ "text",
329
+ "application",
330
+ ];
331
+ const allowedContent = DboBuilder_1.ViewHandler._parseFieldFilter(colConfig.acceptedContent, false, CONTENTS);
332
+ if (!allowedContent.some(c => mime.mime.startsWith(c))) {
333
+ throw new Error(`Dissallowed content type provided: ${mime.mime.split("/")[0]}. Allowed content types: ${allowedContent} `);
334
+ }
335
+ }
336
+ else if ("acceptedContentType" in colConfig && colConfig.acceptedContentType) {
337
+ const allowedContentTypes = DboBuilder_1.ViewHandler._parseFieldFilter(colConfig.acceptedContentType, false, (0, prostgles_types_1.getKeys)(prostgles_types_1.CONTENT_TYPE_TO_EXT));
338
+ if (!allowedContentTypes.some(c => c === mime.mime)) {
339
+ throw new Error(`Dissallowed MIME provided: ${mime.mime}. Allowed MIME values: ${allowedContentTypes} `);
340
+ }
341
+ }
342
+ else if ("acceptedFileTypes" in colConfig && colConfig.acceptedFileTypes) {
343
+ const allowedExtensions = DboBuilder_1.ViewHandler._parseFieldFilter(colConfig.acceptedFileTypes, false, Object.values(prostgles_types_1.CONTENT_TYPE_TO_EXT).flat());
344
+ if (!allowedExtensions.some(c => c === mime.ext)) {
345
+ throw new Error(`Dissallowed extension provided: ${mime.ext}. Allowed extension values: ${allowedExtensions} `);
346
+ }
347
+ }
288
348
  }
289
349
  }
290
- if (allowedExtensions &&
291
- !allowedExtensions.map(v => v.toLowerCase())?.includes(type.ext)) {
292
- throw fileName + " -> File type ( " + type.ext + " ) not allowed. Expecting one of: " + allowedExtensions.map(v => v.toLowerCase()).join(", ");
293
- }
294
- else if (dissallowedExtensions &&
295
- dissallowedExtensions.map(v => v.toLowerCase())?.includes(type.ext)) {
296
- throw fileName + " -> File type ( " + type.ext + " ) not allowed";
297
- }
298
- if (!onlyFromName) {
299
- let { ext } = type;
300
- if (nameExt !== ext)
301
- fileName = nameParts.slice(0, -1).join('') + "." + ext;
302
- }
303
- const res = {
304
- ...type,
305
- fileName
306
- };
307
- if (!res.mime)
308
- throw "Could not find mime";
309
- return res;
350
+ return mime;
310
351
  }
352
+ // private async getMIME(
353
+ // file: Buffer | string,
354
+ // fileName: string,
355
+ // allowedExtensions?: Array<ALLOWED_EXTENSION>,
356
+ // dissallowedExtensions?: Array<ALLOWED_EXTENSION>,
357
+ // onlyFromName = true
358
+ // ): Promise<{
359
+ // mime: string;
360
+ // ext: string | ALLOWED_EXTENSION;
361
+ // fileName: string;
362
+ // }> {
363
+ // const nameParts = fileName.split(".");
364
+ // const nameExt = nameParts[nameParts.length - 1].toLowerCase(),
365
+ // mime = getKeys(CONTENT_TYPE_TO_EXT).find(k => (CONTENT_TYPE_TO_EXT[k] as readonly string[]).includes(nameExt));
366
+ // let type = {
367
+ // fileName,
368
+ // mime,
369
+ // ext: nameExt,
370
+ // }
371
+ // if(onlyFromName && !mime) throw `Invalid file extension: content_type could not be found for extension(${nameExt})`;
372
+ // if(!mime){
373
+ // /* Set correct/missing extension */
374
+ // if(["xml", "txt", "csv", "tsv"].includes(nameExt)){
375
+ // type = { ...type, mime: ("text/" + nameExt) as any, ext: nameExt };
376
+ // } else if(["svg"].includes(nameExt)){
377
+ // type = { ...type, mime: "image/svg+xml", ext: nameExt };
378
+ // } else {
379
+ // const res = await getFileTypeFromBuffer(file);
380
+ // type = {
381
+ // ...(res as any),
382
+ // fileName,
383
+ // }
384
+ // }
385
+ // }
386
+ // if(
387
+ // allowedExtensions &&
388
+ // !allowedExtensions.map(v => v.toLowerCase())?.includes(type.ext)
389
+ // ){
390
+ // throw fileName + " -> File type ( " + type.ext + " ) not allowed. Expecting one of: " + allowedExtensions.map(v => v.toLowerCase()).join(", ");
391
+ // } else if(
392
+ // dissallowedExtensions &&
393
+ // dissallowedExtensions.map(v => v.toLowerCase())?.includes(type.ext)
394
+ // ){
395
+ // throw fileName + " -> File type ( " + type.ext + " ) not allowed";
396
+ // }
397
+ // if(!onlyFromName){
398
+ // let { ext } = type;
399
+ // if(nameExt !== ext) fileName = nameParts.slice(0, -1).join('') + "." + ext;
400
+ // }
401
+ // const res = {
402
+ // ...type,
403
+ // fileName
404
+ // }
405
+ // if(!res.mime) throw "Could not find mime"
406
+ // return res as any;
407
+ // }
311
408
  // async getUploadURL(fileName: string): Promise<string> {
312
409
  // const thisHour = new Date();
313
410
  // thisHour.setMilliseconds(0);
@@ -391,72 +488,43 @@ class FileManager {
391
488
  }
392
489
  }
393
490
  exports.default = FileManager;
394
- const CONTENT_TYPE_TO_EXT = {
395
- "text/html": ["html", "htm", "shtml"],
396
- "text/css": ["css"],
397
- "text/xml": ["xml"],
398
- "text/mathml": ["mml"],
399
- "text/plain": ["txt"],
400
- "text/vnd.sun.j2me.app-descriptor": ["jad"],
401
- "text/vnd.wap.wml": ["wml"],
402
- "text/x-component": ["htc"],
403
- "image/gif": ["gif"],
404
- "image/jpeg": ["jpeg", "jpg"],
405
- "image/png": ["png"],
406
- "image/tiff": ["tif", "tiff"],
407
- "image/vnd.wap.wbmp": ["wbmp"],
408
- "image/x-icon": ["ico"],
409
- "image/x-jng": ["jng"],
410
- "image/x-ms-bmp": ["bmp"],
411
- "image/svg+xml": ["svg"],
412
- "image/webp": ["webp"],
413
- "application/x-javascript": ["js"],
414
- "application/atom+xml": ["atom"],
415
- "application/rss+xml": ["rss"],
416
- "application/java-archive": ["jar", "war", "ear"],
417
- "application/mac-binhex40": ["hqx"],
418
- "application/msword": ["doc", "docx"],
419
- "application/pdf": ["pdf"],
420
- "application/postscript": ["ps", "eps", "ai"],
421
- "application/rtf": ["rtf"],
422
- "application/vnd.ms-excel": ["xls", "xlsx"],
423
- "application/vnd.ms-powerpoint": ["ppt", "pptx"],
424
- "application/vnd.wap.wmlc": ["wmlc"],
425
- "application/vnd.google-earth.kml+xml": ["kml"],
426
- "application/vnd.google-earth.kmz": ["kmz"],
427
- "application/x-7z-compressed": ["7z"],
428
- "application/x-cocoa": ["cco"],
429
- "application/x-java-archive-diff": ["jardiff"],
430
- "application/x-java-jnlp-file": ["jnlp"],
431
- "application/x-makeself": ["run"],
432
- "application/x-perl": ["pl", "pm"],
433
- "application/x-pilot": ["prc", "pdb"],
434
- "application/x-rar-compressed": ["rar"],
435
- "application/x-redhat-package-manager": ["rpm"],
436
- "application/x-sea": ["sea"],
437
- "application/x-shockwave-flash": ["swf"],
438
- "application/x-stuffit": ["sit"],
439
- "application/x-tcl": ["tcl", "tk"],
440
- "application/x-x509-ca-cert": ["der", "pem", "crt"],
441
- "application/x-xpinstall": ["xpi"],
442
- "application/xhtml+xml": ["xhtml"],
443
- "application/zip": ["zip"],
444
- "application/octet-stream": ["bin", "exe", "dll", "deb", "dmg", "eot", "iso", "img", "msi", "msp", "msm"],
445
- "audio/midi": ["mid", "midi", "kar"],
446
- "audio/mpeg": ["mp3"],
447
- "audio/ogg": ["ogg"],
448
- "audio/x-realaudio": ["ra"],
449
- "video/3gpp": ["3gpp", "3gp"],
450
- "video/mpeg": ["mpeg", "mpg"],
451
- "video/quicktime": ["mov"],
452
- "video/x-flv": ["flv"],
453
- "video/x-mng": ["mng"],
454
- "video/x-ms-asf": ["asx", "asf"],
455
- "video/x-ms-wmv": ["wmv"],
456
- "video/x-msvideo": ["avi"],
457
- "video/mp4": ["m4v", "mp4"],
458
- "video/webm": ["webm"],
491
+ const getFileTypeFromFilename = (fileName) => {
492
+ const nameParts = fileName.split(".");
493
+ if (!nameParts.length)
494
+ return undefined;
495
+ const nameExt = nameParts[nameParts.length - 1].toLowerCase(), mime = (0, prostgles_types_1.getKeys)(prostgles_types_1.CONTENT_TYPE_TO_EXT).find(k => prostgles_types_1.CONTENT_TYPE_TO_EXT[k].includes(nameExt));
496
+ if (!mime)
497
+ return undefined;
498
+ return {
499
+ mime,
500
+ ext: nameExt,
501
+ };
502
+ };
503
+ exports.getFileTypeFromFilename = getFileTypeFromFilename;
504
+ // const fileType = require("file-type");
505
+ // const res = await fileType.fromBuffer(typeof file === "string"? Buffer.from(file, 'utf8') : file);
506
+ const getFileType = async (file, fileName) => {
507
+ const { fileTypeFromBuffer } = await eval('import("file-type")');
508
+ const fileNameMime = (0, exports.getFileTypeFromFilename)(fileName);
509
+ if (!fileNameMime?.ext)
510
+ throw new Error("File name must contain extenions");
511
+ const res = await fileTypeFromBuffer(typeof file === "string" ? Buffer.from(file, 'utf8') : file);
512
+ if (!res) {
513
+ /* Set correct/missing extension */
514
+ const nameExt = fileNameMime?.ext;
515
+ if (["xml", "txt", "csv", "tsv", "svg"].includes(nameExt)) {
516
+ return fileNameMime;
517
+ }
518
+ throw new Error("Could not get the file type from file buffer");
519
+ }
520
+ else {
521
+ if (!res.ext || fileNameMime?.ext.toLowerCase() !== res.ext.toLowerCase()) {
522
+ throw new Error(`There is a mismatch between file name extension and actual buffer extension: ${fileNameMime?.ext} vs ${res.ext}`);
523
+ }
524
+ }
525
+ return res;
459
526
  };
527
+ exports.getFileType = getFileType;
460
528
  /**
461
529
  *
462
530