prostgles-server 4.0.16 → 4.0.18

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 (135) hide show
  1. package/dist/AuthHandler.js +214 -210
  2. package/dist/AuthHandler.js.map +1 -1
  3. package/dist/DBEventsManager.js +34 -31
  4. package/dist/DBEventsManager.js.map +1 -1
  5. package/dist/DBSchemaBuilder.js +3 -2
  6. package/dist/DBSchemaBuilder.js.map +1 -1
  7. package/dist/DboBuilder/QueryBuilder/QueryBuilder.d.ts +19 -14
  8. package/dist/DboBuilder/QueryBuilder/QueryBuilder.d.ts.map +1 -1
  9. package/dist/DboBuilder/QueryBuilder/QueryBuilder.js +159 -151
  10. package/dist/DboBuilder/QueryBuilder/QueryBuilder.js.map +1 -1
  11. package/dist/DboBuilder/TableHandler.d.ts +9 -14
  12. package/dist/DboBuilder/TableHandler.d.ts.map +1 -1
  13. package/dist/DboBuilder/TableHandler.js +21 -41
  14. package/dist/DboBuilder/TableHandler.js.map +1 -1
  15. package/dist/DboBuilder/ViewHandler.d.ts +3 -3
  16. package/dist/DboBuilder/ViewHandler.d.ts.map +1 -1
  17. package/dist/DboBuilder/ViewHandler.js +24 -9
  18. package/dist/DboBuilder/ViewHandler.js.map +1 -1
  19. package/dist/DboBuilder/getSubscribeRelatedTables.d.ts +1 -1
  20. package/dist/DboBuilder/getSubscribeRelatedTables.d.ts.map +1 -1
  21. package/dist/DboBuilder/parseUpdateRules.d.ts.map +1 -1
  22. package/dist/DboBuilder/parseUpdateRules.js.map +1 -1
  23. package/dist/DboBuilder/runSQL.js +5 -5
  24. package/dist/DboBuilder/runSQL.js.map +1 -1
  25. package/dist/DboBuilder.d.ts.map +1 -1
  26. package/dist/DboBuilder.js +85 -78
  27. package/dist/DboBuilder.js.map +1 -1
  28. package/dist/FileManager/FileManager.d.ts +143 -0
  29. package/dist/FileManager/FileManager.d.ts.map +1 -0
  30. package/dist/FileManager/FileManager.js +278 -0
  31. package/dist/FileManager/FileManager.js.map +1 -0
  32. package/dist/FileManager/initFileManager.d.ts +4 -0
  33. package/dist/FileManager/initFileManager.d.ts.map +1 -0
  34. package/dist/FileManager/initFileManager.js +209 -0
  35. package/dist/FileManager/initFileManager.js.map +1 -0
  36. package/dist/FileManager/parseFile.d.ts +15 -0
  37. package/dist/FileManager/parseFile.d.ts.map +1 -0
  38. package/dist/FileManager/parseFile.js +59 -0
  39. package/dist/FileManager/parseFile.js.map +1 -0
  40. package/dist/FileManager/upload.d.ts +6 -0
  41. package/dist/FileManager/upload.d.ts.map +1 -0
  42. package/dist/FileManager/upload.js +76 -0
  43. package/dist/FileManager/upload.js.map +1 -0
  44. package/dist/FileManager/uploadStream.d.ts +5 -0
  45. package/dist/FileManager/uploadStream.d.ts.map +1 -0
  46. package/dist/FileManager/uploadStream.js +70 -0
  47. package/dist/FileManager/uploadStream.js.map +1 -0
  48. package/dist/Filtering.d.ts +1 -1
  49. package/dist/Filtering.d.ts.map +1 -1
  50. package/dist/PostgresNotifListenManager.js +26 -20
  51. package/dist/PostgresNotifListenManager.js.map +1 -1
  52. package/dist/Prostgles.d.ts +2 -2
  53. package/dist/Prostgles.d.ts.map +1 -1
  54. package/dist/Prostgles.js +192 -172
  55. package/dist/Prostgles.js.map +1 -1
  56. package/dist/PubSubManager/PubSubManager.d.ts +3 -3
  57. package/dist/PubSubManager/PubSubManager.js +164 -154
  58. package/dist/PubSubManager/PubSubManager.js.map +1 -1
  59. package/dist/PublishParser.d.ts +13 -13
  60. package/dist/PublishParser.d.ts.map +1 -1
  61. package/dist/PublishParser.js +8 -2
  62. package/dist/PublishParser.js.map +1 -1
  63. package/dist/SchemaWatch.js +2 -1
  64. package/dist/SchemaWatch.js.map +1 -1
  65. package/dist/TableConfig/TableConfig.d.ts.map +1 -1
  66. package/dist/TableConfig/TableConfig.js +100 -92
  67. package/dist/TableConfig/TableConfig.js.map +1 -1
  68. package/lib/AuthHandler.js +1 -1
  69. package/lib/AuthHandler.ts +1 -1
  70. package/lib/DBSchemaBuilder.js +3 -2
  71. package/lib/DBSchemaBuilder.ts +3 -2
  72. package/lib/DboBuilder/TableHandler.d.ts +4 -9
  73. package/lib/DboBuilder/TableHandler.d.ts.map +1 -1
  74. package/lib/DboBuilder/TableHandler.js +1 -22
  75. package/lib/DboBuilder/TableHandler.ts +3 -31
  76. package/lib/DboBuilder/ViewHandler.ts +1 -1
  77. package/lib/DboBuilder/getSubscribeRelatedTables.d.ts +1 -1
  78. package/lib/DboBuilder/getSubscribeRelatedTables.d.ts.map +1 -1
  79. package/lib/DboBuilder/getSubscribeRelatedTables.ts +1 -1
  80. package/lib/DboBuilder/parseUpdateRules.d.ts.map +1 -1
  81. package/lib/DboBuilder/parseUpdateRules.ts +2 -2
  82. package/lib/DboBuilder.d.ts.map +1 -1
  83. package/lib/DboBuilder.js +0 -13
  84. package/lib/DboBuilder.ts +1 -16
  85. package/lib/{FileManager.d.ts → FileManager/FileManager.d.ts} +12 -20
  86. package/lib/FileManager/FileManager.d.ts.map +1 -0
  87. package/lib/FileManager/FileManager.js +303 -0
  88. package/lib/FileManager/FileManager.ts +378 -0
  89. package/lib/FileManager/initFileManager.d.ts +4 -0
  90. package/lib/FileManager/initFileManager.d.ts.map +1 -0
  91. package/lib/FileManager/initFileManager.js +231 -0
  92. package/lib/FileManager/initFileManager.ts +236 -0
  93. package/lib/FileManager/parseFile.d.ts +15 -0
  94. package/lib/FileManager/parseFile.d.ts.map +1 -0
  95. package/lib/FileManager/parseFile.js +58 -0
  96. package/lib/FileManager/parseFile.ts +69 -0
  97. package/lib/FileManager/upload.d.ts +6 -0
  98. package/lib/FileManager/upload.d.ts.map +1 -0
  99. package/lib/FileManager/upload.js +98 -0
  100. package/lib/FileManager/upload.ts +83 -0
  101. package/lib/FileManager/uploadStream.d.ts +5 -0
  102. package/lib/FileManager/uploadStream.d.ts.map +1 -0
  103. package/lib/FileManager/uploadStream.js +92 -0
  104. package/lib/FileManager/uploadStream.ts +80 -0
  105. package/lib/Filtering.d.ts +1 -1
  106. package/lib/Filtering.d.ts.map +1 -1
  107. package/lib/Filtering.ts +1 -1
  108. package/lib/JSONBValidation/validate_jsonb_schema_sql.ts +1 -1
  109. package/lib/Prostgles.d.ts +2 -2
  110. package/lib/Prostgles.d.ts.map +1 -1
  111. package/lib/Prostgles.js +8 -5
  112. package/lib/Prostgles.ts +10 -6
  113. package/lib/PublishParser.d.ts +13 -13
  114. package/lib/PublishParser.d.ts.map +1 -1
  115. package/lib/PublishParser.js +1 -0
  116. package/lib/PublishParser.ts +13 -12
  117. package/lib/TableConfig/TableConfig.d.ts.map +1 -1
  118. package/lib/TableConfig/TableConfig.js +12 -7
  119. package/lib/TableConfig/TableConfig.ts +13 -8
  120. package/package.json +3 -3
  121. package/tests/client/PID.txt +1 -1
  122. package/tests/client/index.d.ts.map +1 -1
  123. package/tests/client/index.ts +1 -3
  124. package/tests/client/package-lock.json +31 -4561
  125. package/tests/client/package.json +2 -2
  126. package/tests/client/tsconfig.json +1 -0
  127. package/tests/isomorphic_queries.d.ts.map +1 -1
  128. package/tests/isomorphic_queries.ts +3 -3
  129. package/tests/server/package-lock.json +13 -13
  130. package/tests/server/package.json +1 -1
  131. package/tests/server/tsconfig.json +1 -0
  132. package/tsconfig.json +3 -2
  133. package/lib/FileManager.d.ts.map +0 -1
  134. package/lib/FileManager.js +0 -676
  135. package/lib/FileManager.ts +0 -811
@@ -0,0 +1,236 @@
1
+ import { asName, getKeys } from "prostgles-types";
2
+ import { canCreateTables } from "../DboBuilder/runSQL";
3
+ import { TableHandler } from "../DboBuilder/TableHandler";
4
+ import { Prostgles } from "../Prostgles";
5
+ import { FileManager, HOUR, LocalConfig } from "./FileManager";
6
+ import * as fs from 'fs';
7
+ import { PubSubManager } from "../PubSubManager/PubSubManager";
8
+
9
+ export async function initFileManager(this: FileManager, prg: Prostgles){
10
+ this.prostgles = prg;
11
+
12
+ // const { dbo, db, opts } = prg;
13
+
14
+ const { fileTable } = prg.opts;
15
+ if(!fileTable) throw "fileTable missing";
16
+ const { tableName = "media", referencedTables = {} } = fileTable;
17
+ this.tableName = tableName;
18
+
19
+ const maxBfSizeMB = (prg.opts.io?.engine?.opts?.maxHttpBufferSize || 1e6)/1e6;
20
+ console.log(`Prostgles: Initiated file manager. Max allowed file size: ${maxBfSizeMB}MB (maxHttpBufferSize = 1e6). To increase this set maxHttpBufferSize in socket.io server init options`);
21
+
22
+ // throw `this.db.tx(d => do everything in a transaction pls!!!!`;
23
+
24
+ const canCreate = await canCreateTables(this.db);
25
+ const runQuery = (q: string): Promise<any[]> => {
26
+ if(!canCreate) throw "File table creation failed. Your postgres user does not have CREATE table privileges";
27
+ return this.db.any(`
28
+ ${q}
29
+ `);
30
+ /* ${PubSubManager.EXCLUDE_QUERY_FROM_SCHEMA_WATCH_ID} */
31
+ }
32
+ /**
33
+ * 1. Create media table
34
+ */
35
+ if(!this.dbo[tableName]){
36
+
37
+ console.log(`Creating fileTable ${asName(tableName)} ...`);
38
+ await runQuery(`CREATE EXTENSION IF NOT EXISTS pgcrypto `);
39
+ await runQuery(`CREATE TABLE IF NOT EXISTS ${asName(tableName)} (
40
+ name TEXT NOT NULL,
41
+ extension TEXT NOT NULL,
42
+ content_type TEXT NOT NULL,
43
+ content_length BIGINT NOT NULL DEFAULT 0,
44
+ added TIMESTAMP NOT NULL DEFAULT NOW(),
45
+ url TEXT NOT NULL,
46
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
47
+ original_name TEXT NOT NULL,
48
+ description TEXT,
49
+ s3_url TEXT,
50
+ signed_url TEXT,
51
+ signed_url_expires BIGINT,
52
+ etag TEXT,
53
+ deleted BIGINT,
54
+ deleted_from_storage BIGINT,
55
+ UNIQUE(id),
56
+ UNIQUE(name)
57
+ )`);
58
+ console.log(`Created fileTable ${asName(tableName)}`);
59
+ await prg.refreshDBO();
60
+ }
61
+
62
+ /**
63
+ * 2. Create media lookup tables
64
+ */
65
+ for(const refTable in referencedTables){
66
+
67
+ if(!this.dbo[refTable]) {
68
+ throw `Referenced table (${refTable}) from fileTable.referencedTables prostgles init config does not exist`;
69
+ }
70
+ const cols = await (this.dbo[refTable] as TableHandler).getColumns();
71
+
72
+ const tableConfig = referencedTables[refTable]!;
73
+ if(typeof tableConfig !== "string"){
74
+
75
+ for (const colName of getKeys(tableConfig.referenceColumns)){
76
+
77
+ const existingCol = cols.find(c => c.name === colName);
78
+ if(existingCol){
79
+ if(existingCol.references?.some(({ ftable }) => ftable === tableName)){
80
+ // All ok
81
+ } else {
82
+ if(existingCol.udt_name === "uuid"){
83
+ try {
84
+ const query = `ALTER TABLE ${asName(refTable)} ADD FOREIGN KEY (${asName(colName)}) REFERENCES ${asName(tableName)} (id);`;
85
+ console.log(`Referenced file column ${refTable} (${colName}) exists but is not referencing file table. Trying to add REFERENCE constraing...\n${query}`);
86
+ await runQuery(query);
87
+ console.log("SUCCESS: " + query);
88
+ } catch(e){
89
+ console.error(`Could not add constraing. Err: ${e instanceof Error? e.message : JSON.stringify(e)}`)
90
+ }
91
+ } else {
92
+ console.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)`);
93
+ }
94
+ }
95
+ } else {
96
+ try {
97
+ const query = `ALTER TABLE ${asName(refTable)} ADD COLUMN ${asName(colName)} UUID REFERENCES ${asName(tableName)} (id);`
98
+ console.log(`Creating referenced file column ${refTable} (${colName})...\n${query}`);
99
+ await runQuery(query);
100
+ console.log("SUCCESS: " + query);
101
+ } catch(e){
102
+ console.error(`FAILED. Err: ${e instanceof Error? e.message : JSON.stringify(e)}`)
103
+ }
104
+ }
105
+
106
+ }
107
+ } else {
108
+
109
+ const lookupTableName = await this.parseSQLIdentifier(`prostgles_lookup_${tableName}_${refTable}`);
110
+ const pKeyFields = cols.filter(f => f.is_pkey);
111
+
112
+ if(pKeyFields.length !== 1) {
113
+ console.error(`Could not make link table for ${refTable}. ${pKeyFields} must have exactly one primary key column. Current pkeys: ${pKeyFields.map(f => f.name)}`);
114
+ }
115
+
116
+ const pkField = pKeyFields[0]!;
117
+ const refType = referencedTables[refTable];
118
+
119
+ if(!this.dbo[lookupTableName]){
120
+ // if(!(await dbo[lookupTableName].count())) await db.any(`DROP TABLE IF EXISTS ${lookupTableName};`);
121
+ const action = ` (${tableName} <-> ${refTable}) join table ${lookupTableName}`; // PRIMARY KEY
122
+ const query = `
123
+ CREATE TABLE ${lookupTableName} (
124
+ foreign_id ${pkField.udt_name} ${refType === "one"? " PRIMARY KEY " : ""} REFERENCES ${asName(refTable)}(${asName(pkField.name)}),
125
+ media_id UUID NOT NULL REFERENCES ${asName(tableName)}(id)
126
+ )
127
+ `;
128
+ console.log(`Creating ${action} ...`, lookupTableName);
129
+ await runQuery(query);
130
+ console.log(`Created ${action}`);
131
+
132
+ } else {
133
+ const cols = await this.dbo[lookupTableName]!.getColumns!();
134
+ const badCols = cols.filter(c => !c.references);
135
+ await Promise.all(badCols.map(async badCol => {
136
+ console.error(
137
+ `Prostgles: media ${lookupTableName} joining table has lost a reference constraint for column ${badCol.name}.` +
138
+ ` This may have been caused by a DROP TABLE ... CASCADE.`
139
+ );
140
+ let q = ` ALTER TABLE ${asName(lookupTableName)} ADD FOREIGN KEY (${badCol.name}) `;
141
+ console.log("Trying to add the missing constraint back");
142
+ if(badCol.name === "foreign_id"){
143
+ q += `REFERENCES ${asName(refTable)}(${asName(pkField.name)}) `;
144
+ } else if(badCol.name === "media_id"){
145
+ q += `REFERENCES ${asName(tableName)}(id) `;
146
+ }
147
+
148
+ if(q){
149
+
150
+ try {
151
+ await runQuery(q)
152
+ console.log("Added missing constraint back");
153
+
154
+ } catch(e){
155
+ console.error("Failed to add missing constraint", e)
156
+ }
157
+ }
158
+
159
+ }));
160
+ }
161
+ }
162
+
163
+
164
+ await prg.refreshDBO();
165
+ }
166
+
167
+ /**
168
+ * 4. Serve media through express
169
+ */
170
+ const {
171
+ fileServeRoute = `/${tableName}`,
172
+ expressApp: app
173
+ } = fileTable;
174
+
175
+ if(fileServeRoute.endsWith("/")){
176
+ throw `fileServeRoute must not end with a '/'`
177
+ }
178
+ this.fileRoute = fileServeRoute;
179
+
180
+ if(app){
181
+ app.get(this.fileRouteExpress, async (req, res) => {
182
+ if(!this.dbo[tableName]){
183
+ res.status(500).json({ err: `Internal error: media table (${tableName}) not valid` });
184
+ return false;
185
+ }
186
+
187
+ const mediaTable = this.dbo[tableName] as unknown as TableHandler;
188
+
189
+ try {
190
+
191
+ const { name } = req.params;
192
+ if(typeof name !== "string" || !name) throw "Invalid media name";
193
+
194
+ const media = await mediaTable.findOne({ name }, { select: { id: 1, name: 1, signed_url: 1, signed_url_expires: 1, content_type: 1 } }, { httpReq: req } as any);
195
+
196
+ if(!media) {
197
+ /**
198
+ * Redirect to login !??
199
+ */
200
+ // const mediaExists = await mediaTable.count({ name });
201
+ // if(mediaExists && this.prostgles.authHandler){
202
+
203
+ // } else {
204
+ // throw "Invalid media";
205
+ // }
206
+ throw "Invalid media";
207
+ }
208
+
209
+ if(this.s3Client){
210
+ let url = media.signed_url;
211
+ const expires = +(media.signed_url_expires || 0);
212
+
213
+ const EXPIRES = Date.now() + HOUR;
214
+ if(!url || expires < EXPIRES){
215
+ url = await this.getFileS3URL(media.name, 60 * 60);
216
+ await mediaTable.update({ name }, { signed_url: url, signed_url_expires: EXPIRES });
217
+ }
218
+
219
+ res.redirect(url);
220
+
221
+ } else {
222
+ const pth = `${(this.config as LocalConfig).localFolderPath}/${media.name}`;
223
+ if(!fs.existsSync(pth)){
224
+ throw new Error("File not found");
225
+ }
226
+ res.contentType(media.content_type);
227
+ res.sendFile(pth);
228
+ }
229
+
230
+ } catch(e){
231
+ console.log(e)
232
+ res.status(404).json({ err: "Invalid/missing media" });
233
+ }
234
+ });
235
+ }
236
+ }
@@ -0,0 +1,15 @@
1
+ /// <reference types="node" />
2
+ import { ALLOWED_CONTENT_TYPE, ALLOWED_EXTENSION } from "prostgles-types";
3
+ import { FileManager } from "./FileManager";
4
+ type Args = {
5
+ file: Buffer | string;
6
+ fileName: string;
7
+ colName?: string;
8
+ tableName?: string;
9
+ };
10
+ export declare function parseFile(this: FileManager, args: Args): Promise<{
11
+ mime: string | ALLOWED_CONTENT_TYPE;
12
+ ext: string | ALLOWED_EXTENSION;
13
+ }>;
14
+ export {};
15
+ //# sourceMappingURL=parseFile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parseFile.d.ts","sourceRoot":"","sources":["parseFile.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAA0C,MAAM,iBAAiB,CAAC;AAElH,OAAO,EAAE,WAAW,EAAwC,MAAM,eAAe,CAAC;AAElF,KAAK,IAAI,GAAG;IACV,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AACF,wBAAsB,SAAS,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC;IACtE,IAAI,EAAE,MAAM,GAAG,oBAAoB,CAAC;IACpC,GAAG,EAAE,MAAM,GAAG,iBAAiB,CAAC;CAIjC,CAAC,CAoDD"}
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseFile = void 0;
4
+ const prostgles_types_1 = require("prostgles-types");
5
+ const ViewHandler_1 = require("../DboBuilder/ViewHandler");
6
+ const FileManager_1 = require("./FileManager");
7
+ async function parseFile(args) {
8
+ const { file, fileName, tableName, colName } = args;
9
+ const config = this.prostgles?.opts.fileTable;
10
+ if (!config)
11
+ throw new Error("File table config missing");
12
+ const buffer = typeof file === "string" ? Buffer.from(file, 'utf8') : file;
13
+ const result = await (0, FileManager_1.getFileTypeFromFilename)(fileName);
14
+ if (tableName && colName) {
15
+ const tableConfig = config.referencedTables?.[tableName];
16
+ if (tableConfig && (0, prostgles_types_1.isObject)(tableConfig) && tableConfig.referenceColumns[colName]) {
17
+ const colConfig = tableConfig.referenceColumns[colName];
18
+ if (colConfig.maxFileSizeMB) {
19
+ const actualBufferSize = Buffer.byteLength(buffer);
20
+ if ((actualBufferSize / 1e6) > colConfig.maxFileSizeMB) {
21
+ throw new Error(`Provided file is larger than the ${colConfig.maxFileSizeMB}MB limit`);
22
+ }
23
+ }
24
+ if ("acceptedContent" in colConfig && colConfig.acceptedContent && colConfig.acceptedContent !== "*") {
25
+ const mime = await (0, FileManager_1.getFileType)(buffer, fileName);
26
+ const CONTENTS = [
27
+ "image",
28
+ "audio",
29
+ "video",
30
+ "text",
31
+ "application",
32
+ ];
33
+ const allowedContent = ViewHandler_1.ViewHandler._parseFieldFilter(colConfig.acceptedContent, false, CONTENTS);
34
+ if (!allowedContent.some(c => mime.mime.startsWith(c))) {
35
+ throw new Error(`Dissallowed content type provided: ${mime.mime.split("/")[0]}. Allowed content types: ${allowedContent} `);
36
+ }
37
+ }
38
+ else if ("acceptedContentType" in colConfig && colConfig.acceptedContentType && colConfig.acceptedContentType !== "*") {
39
+ const mime = await (0, FileManager_1.getFileType)(buffer, fileName);
40
+ const allowedContentTypes = ViewHandler_1.ViewHandler._parseFieldFilter(colConfig.acceptedContentType, false, (0, prostgles_types_1.getKeys)(prostgles_types_1.CONTENT_TYPE_TO_EXT));
41
+ if (!allowedContentTypes.some(c => c === mime.mime)) {
42
+ throw new Error(`Dissallowed MIME provided: ${mime.mime}. Allowed MIME values: ${allowedContentTypes} `);
43
+ }
44
+ }
45
+ else if ("acceptedFileTypes" in colConfig && colConfig.acceptedFileTypes && colConfig.acceptedFileTypes !== "*") {
46
+ const mime = await (0, FileManager_1.getFileType)(buffer, fileName);
47
+ const allowedExtensions = ViewHandler_1.ViewHandler._parseFieldFilter(colConfig.acceptedFileTypes, false, Object.values(prostgles_types_1.CONTENT_TYPE_TO_EXT).flat());
48
+ if (!allowedExtensions.some(c => c === mime.ext)) {
49
+ throw new Error(`Dissallowed extension provided: ${mime.ext}. Allowed extension values: ${allowedExtensions} `);
50
+ }
51
+ }
52
+ }
53
+ }
54
+ if (!result?.mime)
55
+ throw `File MIME type not found for the provided extension: ${result?.ext}`;
56
+ return result;
57
+ }
58
+ exports.parseFile = parseFile;
@@ -0,0 +1,69 @@
1
+ import { ALLOWED_CONTENT_TYPE, ALLOWED_EXTENSION, CONTENT_TYPE_TO_EXT, getKeys, isObject } from "prostgles-types";
2
+ import { ViewHandler } from "../DboBuilder/ViewHandler";
3
+ import { FileManager, getFileType, getFileTypeFromFilename } from "./FileManager";
4
+
5
+ type Args = {
6
+ file: Buffer | string;
7
+ fileName: string;
8
+ colName?: string;
9
+ tableName?: string;
10
+ };
11
+ export async function parseFile(this: FileManager, args: Args): Promise<{
12
+ mime: string | ALLOWED_CONTENT_TYPE;
13
+ ext: string | ALLOWED_EXTENSION;
14
+
15
+ /** File name is not returned because we fail if the extensions do not match */
16
+ // fileName: string;
17
+ }> {
18
+ const { file, fileName, tableName, colName } = args;
19
+ const config = this.prostgles?.opts.fileTable;
20
+ if(!config) throw new Error("File table config missing");
21
+
22
+ const buffer = typeof file === "string"? Buffer.from(file, 'utf8') : file;
23
+
24
+ const result = await getFileTypeFromFilename(fileName);
25
+ if(tableName && colName){
26
+ const tableConfig = config.referencedTables?.[tableName];
27
+
28
+ if(tableConfig && isObject(tableConfig) && tableConfig.referenceColumns[colName]){
29
+ const colConfig = tableConfig.referenceColumns[colName]!;
30
+ if(colConfig.maxFileSizeMB){
31
+ const actualBufferSize = Buffer.byteLength(buffer);
32
+ if((actualBufferSize/1e6) > colConfig.maxFileSizeMB){
33
+ throw new Error(`Provided file is larger than the ${colConfig.maxFileSizeMB}MB limit`);
34
+ }
35
+ }
36
+
37
+ if("acceptedContent" in colConfig && colConfig.acceptedContent && colConfig.acceptedContent !== "*"){
38
+ const mime = await getFileType(buffer, fileName);
39
+ const CONTENTS = [
40
+ "image",
41
+ "audio",
42
+ "video",
43
+ "text",
44
+ "application",
45
+ ];
46
+ const allowedContent = ViewHandler._parseFieldFilter(colConfig.acceptedContent, false, CONTENTS);
47
+ if(!allowedContent.some(c => mime.mime.startsWith(c))){
48
+ throw new Error(`Dissallowed content type provided: ${mime.mime.split("/")[0]}. Allowed content types: ${allowedContent} `)
49
+ }
50
+ } else if("acceptedContentType" in colConfig && colConfig.acceptedContentType && colConfig.acceptedContentType !== "*"){
51
+ const mime = await getFileType(buffer, fileName);
52
+ const allowedContentTypes = ViewHandler._parseFieldFilter(colConfig.acceptedContentType, false, getKeys(CONTENT_TYPE_TO_EXT));
53
+
54
+ if(!allowedContentTypes.some(c => c === mime.mime)){
55
+ throw new Error(`Dissallowed MIME provided: ${mime.mime}. Allowed MIME values: ${allowedContentTypes} `)
56
+ }
57
+ } else if("acceptedFileTypes" in colConfig && colConfig.acceptedFileTypes && colConfig.acceptedFileTypes !== "*"){
58
+ const mime = await getFileType(buffer, fileName);
59
+ const allowedExtensions = ViewHandler._parseFieldFilter(colConfig.acceptedFileTypes, false, Object.values(CONTENT_TYPE_TO_EXT).flat());
60
+
61
+ if(!allowedExtensions.some(c => c === mime.ext)){
62
+ throw new Error(`Dissallowed extension provided: ${mime.ext}. Allowed extension values: ${allowedExtensions} `)
63
+ }
64
+ }
65
+ }
66
+ }
67
+ if(!result?.mime) throw `File MIME type not found for the provided extension: ${result?.ext}`;
68
+ return result;
69
+ }
@@ -0,0 +1,6 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { FileManager, OnProgress, UploadedItem } from "./FileManager";
4
+ import * as stream from 'stream';
5
+ export declare function upload(this: FileManager, file: Buffer | string | stream.PassThrough, name: string, mime: string, onProgress?: OnProgress): Promise<UploadedItem>;
6
+ //# sourceMappingURL=upload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["upload.ts"],"names":[],"mappings":";;AAAA,OAAO,EAAE,WAAW,EAAe,UAAU,EAAY,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7F,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAIjC,wBAAsB,MAAM,CAC1B,IAAI,EAAE,WAAW,EACjB,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC,WAAW,EAC1C,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,UAAU,GACtB,OAAO,CAAC,YAAY,CAAC,CAuErB"}
@@ -0,0 +1,98 @@
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.upload = void 0;
27
+ const stream = __importStar(require("stream"));
28
+ const fs = __importStar(require("fs"));
29
+ async function upload(file, name, mime, onProgress) {
30
+ return new Promise(async (resolve, reject) => {
31
+ if (!file) {
32
+ throw "No file. Expecting: Buffer | String | stream";
33
+ }
34
+ if (!name) {
35
+ throw "No name. Expecting: String";
36
+ }
37
+ // let type = await this.getMIME(file, name, allowedExtensions);
38
+ const url = this.getLocalFileUrl(name);
39
+ if (!this.s3Client) {
40
+ if (file instanceof stream.PassThrough) {
41
+ throw new Error("S3 config missing. Can only upload streams to S3");
42
+ }
43
+ const config = this.config;
44
+ try {
45
+ await fs.promises.mkdir(config.localFolderPath, { recursive: true });
46
+ const filePath = `${config.localFolderPath}/${name}`;
47
+ fs.writeFileSync(filePath, file);
48
+ resolve({
49
+ url,
50
+ etag: `none`,
51
+ content_length: fs.statSync(filePath).size
52
+ });
53
+ }
54
+ catch (err) {
55
+ console.error("Error saving file locally", err);
56
+ reject("Internal error");
57
+ }
58
+ }
59
+ else {
60
+ /* S3 Upload */
61
+ // ACL: "public-read",
62
+ /* ACL needs this permission:
63
+ "s3:PutObject",
64
+ "s3:PutObjectAcl",
65
+ "s3:GetObject",
66
+ "s3:GetObjectAcl",
67
+ */
68
+ const params = {
69
+ Bucket: this.config.bucket,
70
+ Key: name,
71
+ ContentType: mime,
72
+ Body: file
73
+ };
74
+ let content_length = 0;
75
+ const manager = this.s3Client.upload(params, (err, res) => {
76
+ // const manager = this.s3Client.send(new PutObjectCommand(params), (err: Error, res) => {
77
+ if (err) {
78
+ reject(err.toString());
79
+ console.error(err);
80
+ }
81
+ else {
82
+ // console.log("Uploaded file:", res)
83
+ resolve({
84
+ url,
85
+ etag: res.ETag,
86
+ s3_url: res.Location,
87
+ content_length // await fileMgr.s3Client?.headObject({ Bucket: ..., Key: ... }).promise() ).ContentLength;
88
+ });
89
+ }
90
+ });
91
+ manager.on('httpUploadProgress', prog => {
92
+ content_length = prog.total;
93
+ onProgress?.(prog);
94
+ });
95
+ }
96
+ });
97
+ }
98
+ exports.upload = upload;
@@ -0,0 +1,83 @@
1
+ import { FileManager, LocalConfig, OnProgress, S3Config, UploadedItem } from "./FileManager";
2
+ import * as stream from 'stream';
3
+ import * as fs from 'fs';
4
+ import { ManagedUpload } from "aws-sdk/clients/s3";
5
+
6
+ export async function upload(
7
+ this: FileManager,
8
+ file: Buffer | string | stream.PassThrough,
9
+ name: string,
10
+ mime: string,
11
+ onProgress?: OnProgress
12
+ ): Promise<UploadedItem> {
13
+
14
+ return new Promise(async (resolve, reject) => {
15
+ if(!file){
16
+ throw "No file. Expecting: Buffer | String | stream";
17
+ }
18
+ if(!name){
19
+ throw "No name. Expecting: String";
20
+ }
21
+
22
+ // let type = await this.getMIME(file, name, allowedExtensions);
23
+ const url = this.getLocalFileUrl(name)
24
+ if(!this.s3Client){
25
+ if(file instanceof stream.PassThrough){
26
+ throw new Error("S3 config missing. Can only upload streams to S3");
27
+ }
28
+ const config = this.config as LocalConfig;
29
+ try {
30
+ await fs.promises.mkdir(config.localFolderPath, { recursive: true });
31
+ const filePath = `${config.localFolderPath}/${name}`;
32
+ fs.writeFileSync(filePath, file);
33
+ resolve({
34
+ url,
35
+ etag: `none`,
36
+ content_length: fs.statSync(filePath).size
37
+ })
38
+ } catch(err){
39
+ console.error("Error saving file locally", err);
40
+ reject("Internal error")
41
+ }
42
+ } else {
43
+
44
+ /* S3 Upload */
45
+ // ACL: "public-read",
46
+ /* ACL needs this permission:
47
+ "s3:PutObject",
48
+ "s3:PutObjectAcl",
49
+ "s3:GetObject",
50
+ "s3:GetObjectAcl",
51
+ */
52
+ const params = {
53
+ Bucket: (this.config as S3Config).bucket,
54
+ Key: name,
55
+ ContentType: mime,
56
+ Body: file
57
+ };
58
+
59
+ let content_length = 0;
60
+ const manager = this.s3Client.upload(params, (err: Error, res: ManagedUpload.SendData) => {
61
+ // const manager = this.s3Client.send(new PutObjectCommand(params), (err: Error, res) => {
62
+
63
+ if(err){
64
+ reject(err.toString());
65
+ console.error(err)
66
+ } else {
67
+ // console.log("Uploaded file:", res)
68
+ resolve({
69
+ url,
70
+ etag: res.ETag,
71
+ s3_url: res.Location,
72
+ content_length // await fileMgr.s3Client?.headObject({ Bucket: ..., Key: ... }).promise() ).ContentLength;
73
+ });
74
+ }
75
+ });
76
+ manager.on('httpUploadProgress', prog => {
77
+ content_length = prog.total;
78
+ onProgress?.(prog);
79
+ });
80
+ }
81
+
82
+ });
83
+ }
@@ -0,0 +1,5 @@
1
+ /// <reference types="node" />
2
+ import { FileManager, OnProgress, UploadedItem } from "./FileManager";
3
+ import * as stream from 'stream';
4
+ export declare function uploadStream(this: FileManager, name: string, mime: string, onProgress?: OnProgress, onError?: (error: any) => void, onEnd?: (item: UploadedItem) => void, expectedSizeBytes?: number): stream.PassThrough;
5
+ //# sourceMappingURL=uploadStream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uploadStream.d.ts","sourceRoot":"","sources":["uploadStream.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAEtE,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAGjC,wBAAgB,YAAY,CAC1B,IAAI,EAAE,WAAW,EACjB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,UAAU,EACvB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAG,IAAI,EAC5B,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,YAAY,KAAG,IAAI,EAClC,iBAAiB,CAAC,EAAE,MAAM,sBAmE3B"}
@@ -0,0 +1,92 @@
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.uploadStream = void 0;
27
+ const fs = __importStar(require("fs"));
28
+ const stream = __importStar(require("stream"));
29
+ const path = __importStar(require("path"));
30
+ function uploadStream(name, mime, onProgress, onError, onEnd, expectedSizeBytes) {
31
+ const passThrough = new stream.PassThrough();
32
+ if (!this.s3Client && "localFolderPath" in this.config) {
33
+ // throw new Error("S3 config missing. Can only upload streams to S3");
34
+ try {
35
+ this.checkFreeSpace(this.config.localFolderPath, expectedSizeBytes).catch(err => {
36
+ onError?.(err);
37
+ passThrough.end();
38
+ });
39
+ const url = this.getLocalFileUrl(name);
40
+ fs.mkdirSync(this.config.localFolderPath, { recursive: true });
41
+ const filePath = path.resolve(`${this.config.localFolderPath}/${name}`);
42
+ const writeStream = fs.createWriteStream(filePath);
43
+ let errored = false;
44
+ let loaded = 0;
45
+ writeStream.on('error', err => {
46
+ errored = true;
47
+ onError?.(err);
48
+ });
49
+ let lastProgress = Date.now();
50
+ const throttle = 1000;
51
+ if (onProgress) {
52
+ passThrough.on('data', function (chunk) {
53
+ loaded += chunk.length;
54
+ const now = Date.now();
55
+ if (now - lastProgress > throttle) {
56
+ lastProgress = now;
57
+ onProgress?.({ loaded, total: 0 });
58
+ }
59
+ });
60
+ }
61
+ if (onEnd) {
62
+ writeStream.on('finish', () => {
63
+ if (errored)
64
+ return;
65
+ let content_length = 0;
66
+ try {
67
+ content_length = fs.statSync(filePath).size;
68
+ onEnd?.({
69
+ url,
70
+ filePath,
71
+ etag: `none`,
72
+ content_length
73
+ });
74
+ }
75
+ catch (err) {
76
+ onError?.(err);
77
+ }
78
+ });
79
+ }
80
+ passThrough.pipe(writeStream);
81
+ }
82
+ catch (err) {
83
+ onError?.(err);
84
+ }
85
+ }
86
+ else {
87
+ this.upload(passThrough, name, mime, onProgress).then(onEnd)
88
+ .catch(onError);
89
+ }
90
+ return passThrough;
91
+ }
92
+ exports.uploadStream = uploadStream;