@terreno/admin-backend 57.4.0 → 57.6.0

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.
@@ -1,89 +1,28 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- 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;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __read = (this && this.__read) || function (o, n) {
39
- var m = typeof Symbol === "function" && o[Symbol.iterator];
40
- if (!m) return o;
41
- var i = m.call(o), r, ar = [], e;
42
- try {
43
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
44
- }
45
- catch (error) { e = { error: error }; }
46
- finally {
47
- try {
48
- if (r && !r.done && (m = i["return"])) m.call(i);
49
- }
50
- finally { if (e) throw e.error; }
51
- }
52
- return ar;
53
- };
54
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
55
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
56
- if (ar || !(i in from)) {
57
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
58
- ar[i] = from[i];
59
- }
60
- }
61
- return to.concat(ar || Array.prototype.slice.call(from));
62
- };
63
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
64
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
65
4
  };
66
5
  Object.defineProperty(exports, "__esModule", { value: true });
67
6
  exports.DocumentStorageApp = void 0;
68
- var promises_1 = require("node:stream/promises");
69
- var storage_1 = require("@google-cloud/storage");
70
- var api_1 = require("@terreno/api");
71
- var luxon_1 = require("luxon");
72
- var multer_1 = __importDefault(require("multer"));
7
+ const promises_1 = require("node:stream/promises");
8
+ const storage_1 = require("@google-cloud/storage");
9
+ const api_1 = require("@terreno/api");
10
+ const luxon_1 = require("luxon");
11
+ const multer_1 = __importDefault(require("multer"));
73
12
  // Express 5 wildcard route params (e.g. `*filepath`) come through as string[]
74
13
  // when the URL has one or more path segments. Older signatures (and manual
75
14
  // calls) may still provide a string. Normalize both shapes to a single
76
15
  // forward-slash separated path.
77
- var normalizePathParam = function (value) {
16
+ const normalizePathParam = (value) => {
78
17
  if (Array.isArray(value)) {
79
- return value.filter(function (segment) { return typeof segment === "string"; }).join("/");
18
+ return value.filter((segment) => typeof segment === "string").join("/");
80
19
  }
81
20
  if (typeof value === "string") {
82
21
  return value;
83
22
  }
84
23
  return "";
85
24
  };
86
- var DEFAULT_ALLOWED_MIME_TYPES = new Set([
25
+ const DEFAULT_ALLOWED_MIME_TYPES = new Set([
87
26
  "image/jpeg",
88
27
  "image/png",
89
28
  "image/gif",
@@ -98,69 +37,56 @@ var DEFAULT_ALLOWED_MIME_TYPES = new Set([
98
37
  "application/vnd.ms-excel",
99
38
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
100
39
  ]);
101
- var DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
102
- var isAdmin = function (req) {
103
- var user = req.user;
104
- return (user === null || user === void 0 ? void 0 : user.admin) === true;
40
+ const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
41
+ const isAdmin = (req) => {
42
+ const user = req.user;
43
+ return user?.admin === true;
105
44
  };
106
- var DocumentStorageApp = /** @class */ (function () {
107
- function DocumentStorageApp(options) {
45
+ class DocumentStorageApp {
46
+ options;
47
+ storage;
48
+ constructor(options) {
108
49
  this.options = options;
109
50
  this.storage = new storage_1.Storage();
110
51
  }
111
- DocumentStorageApp.prototype.adminContribution = function () {
52
+ adminContribution() {
112
53
  return {
113
54
  customScreens: [{ displayName: "Documents", icon: "folder", name: "documents" }],
114
55
  };
115
- };
116
- Object.defineProperty(DocumentStorageApp.prototype, "bucket", {
117
- get: function () {
118
- var bucketName = this.options.bucketName || process.env.GCS_BUCKET;
119
- if (!bucketName) {
120
- throw new api_1.APIError({
121
- detail: "Configure storage settings before accessing files.",
122
- disableExternalErrorTracking: true,
123
- status: 503,
124
- title: "Storage not configured",
125
- });
126
- }
127
- return this.storage.bucket(bucketName);
128
- },
129
- enumerable: false,
130
- configurable: true
131
- });
132
- Object.defineProperty(DocumentStorageApp.prototype, "prefix", {
133
- get: function () {
134
- var _a;
135
- return (_a = this.options.folderPrefix) !== null && _a !== void 0 ? _a : "";
136
- },
137
- enumerable: false,
138
- configurable: true
139
- });
140
- Object.defineProperty(DocumentStorageApp.prototype, "allowedMimeTypes", {
141
- get: function () {
142
- if (this.options.allowedMimeTypes) {
143
- return new Set(this.options.allowedMimeTypes);
144
- }
145
- return DEFAULT_ALLOWED_MIME_TYPES;
146
- },
147
- enumerable: false,
148
- configurable: true
149
- });
150
- DocumentStorageApp.prototype.register = function (app) {
151
- var _this = this;
152
- var _a, _b;
153
- var basePath = (_a = this.options.basePath) !== null && _a !== void 0 ? _a : "/documents";
154
- var maxFileSize = (_b = this.options.maxFileSize) !== null && _b !== void 0 ? _b : DEFAULT_MAX_FILE_SIZE;
155
- var allowedMimeTypes = this.allowedMimeTypes;
156
- var upload = (0, multer_1.default)({
157
- fileFilter: function (_req, file, cb) {
56
+ }
57
+ get bucket() {
58
+ const bucketName = this.options.bucketName || process.env.GCS_BUCKET;
59
+ if (!bucketName) {
60
+ throw new api_1.APIError({
61
+ detail: "Configure storage settings before accessing files.",
62
+ disableExternalErrorTracking: true,
63
+ status: 503,
64
+ title: "Storage not configured",
65
+ });
66
+ }
67
+ return this.storage.bucket(bucketName);
68
+ }
69
+ get prefix() {
70
+ return this.options.folderPrefix ?? "";
71
+ }
72
+ get allowedMimeTypes() {
73
+ if (this.options.allowedMimeTypes) {
74
+ return new Set(this.options.allowedMimeTypes);
75
+ }
76
+ return DEFAULT_ALLOWED_MIME_TYPES;
77
+ }
78
+ register(app) {
79
+ const basePath = this.options.basePath ?? "/documents";
80
+ const maxFileSize = this.options.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
81
+ const allowedMimeTypes = this.allowedMimeTypes;
82
+ const upload = (0, multer_1.default)({
83
+ fileFilter: (_req, file, cb) => {
158
84
  if (allowedMimeTypes.has(file.mimetype)) {
159
85
  cb(null, true);
160
86
  }
161
87
  else {
162
88
  cb(new api_1.APIError({
163
- detail: "File type ".concat(file.mimetype, " is not allowed"),
89
+ detail: `File type ${file.mimetype} is not allowed`,
164
90
  disableExternalErrorTracking: true,
165
91
  status: 400,
166
92
  title: "File type not allowed",
@@ -170,9 +96,9 @@ var DocumentStorageApp = /** @class */ (function () {
170
96
  limits: { fileSize: maxFileSize },
171
97
  storage: multer_1.default.memoryStorage(),
172
98
  });
173
- var adminGuard = [
99
+ const adminGuard = [
174
100
  (0, api_1.authenticateMiddleware)(),
175
- function (req, _res, next) {
101
+ (req, _res, next) => {
176
102
  if (!isAdmin(req)) {
177
103
  throw new api_1.APIError({ status: 403, title: "Admin access required" });
178
104
  }
@@ -180,213 +106,146 @@ var DocumentStorageApp = /** @class */ (function () {
180
106
  },
181
107
  ];
182
108
  // GET basePath/ — List files and folders
183
- app.get.apply(app, __spreadArray(__spreadArray(["".concat(basePath, "/")], __read(adminGuard), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
184
- var queryPrefix, fullPrefix, _a, files, apiResponse, documentFiles, prefixes, folders, response;
185
- var _this = this;
186
- var _b, _c;
187
- return __generator(this, function (_d) {
188
- switch (_d.label) {
189
- case 0:
190
- queryPrefix = (_b = req.query.prefix) !== null && _b !== void 0 ? _b : "";
191
- fullPrefix = "".concat(this.prefix).concat(queryPrefix);
192
- return [4 /*yield*/, this.bucket.getFiles({
193
- delimiter: "/",
194
- prefix: fullPrefix,
195
- })];
196
- case 1:
197
- _a = __read.apply(void 0, [_d.sent(), 3]), files = _a[0], apiResponse = _a[2];
198
- documentFiles = files
199
- .filter(function (file) { return file.name !== fullPrefix; })
200
- .map(function (file) {
201
- var _a, _b;
202
- return ({
203
- contentType: file.metadata.contentType,
204
- fullPath: file.name.slice(_this.prefix.length),
205
- isFolder: false,
206
- name: (_a = file.name.split("/").filter(Boolean).pop()) !== null && _a !== void 0 ? _a : file.name,
207
- size: Number((_b = file.metadata.size) !== null && _b !== void 0 ? _b : 0),
208
- updated: file.metadata.updated,
209
- });
210
- });
211
- prefixes = (_c = apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.prefixes) !== null && _c !== void 0 ? _c : [];
212
- folders = prefixes.map(function (p) {
213
- var relative = p.slice(_this.prefix.length);
214
- return relative;
215
- });
216
- response = {
217
- files: documentFiles,
218
- folders: folders,
219
- prefix: queryPrefix,
220
- };
221
- return [2 /*return*/, res.json(response)];
222
- }
223
- });
224
- }); })], false));
109
+ app.get(`${basePath}/`, ...adminGuard, (0, api_1.asyncHandler)(async (req, res) => {
110
+ const queryPrefix = req.query.prefix ?? "";
111
+ const fullPrefix = `${this.prefix}${queryPrefix}`;
112
+ const [files, , apiResponse] = await this.bucket.getFiles({
113
+ delimiter: "/",
114
+ prefix: fullPrefix,
115
+ });
116
+ const documentFiles = files
117
+ .filter((file) => file.name !== fullPrefix)
118
+ .map((file) => ({
119
+ contentType: file.metadata.contentType,
120
+ fullPath: file.name.slice(this.prefix.length),
121
+ isFolder: false,
122
+ name: file.name.split("/").filter(Boolean).pop() ?? file.name,
123
+ size: Number(file.metadata.size ?? 0),
124
+ updated: file.metadata.updated,
125
+ }));
126
+ const prefixes = apiResponse?.prefixes ?? [];
127
+ const folders = prefixes.map((p) => {
128
+ const relative = p.slice(this.prefix.length);
129
+ return relative;
130
+ });
131
+ const response = {
132
+ files: documentFiles,
133
+ folders,
134
+ prefix: queryPrefix,
135
+ };
136
+ return res.json(response);
137
+ }));
225
138
  // POST basePath/ — Upload a file
226
- app.post.apply(app, __spreadArray(__spreadArray(["".concat(basePath, "/")], __read(adminGuard), false), [upload.single("file"),
227
- (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
228
- var file, targetPrefix, sanitizedFilename, gcsPath, gcsFile, documentFile;
229
- var _a;
230
- return __generator(this, function (_b) {
231
- switch (_b.label) {
232
- case 0:
233
- file = req.file;
234
- if (!file) {
235
- throw new api_1.APIError({ status: 400, title: "No file provided" });
236
- }
237
- targetPrefix = (_a = req.body.prefix) !== null && _a !== void 0 ? _a : "";
238
- sanitizedFilename = file.originalname.replace(/[^a-zA-Z0-9._-]/g, "_");
239
- gcsPath = "".concat(this.prefix).concat(targetPrefix).concat(sanitizedFilename);
240
- gcsFile = this.bucket.file(gcsPath);
241
- return [4 /*yield*/, gcsFile.save(file.buffer, {
242
- contentType: file.mimetype,
243
- })];
244
- case 1:
245
- _b.sent();
246
- documentFile = {
247
- contentType: file.mimetype,
248
- fullPath: "".concat(targetPrefix).concat(sanitizedFilename),
249
- isFolder: false,
250
- name: sanitizedFilename,
251
- size: file.buffer.length,
252
- updated: luxon_1.DateTime.now().toISO(),
253
- };
254
- return [2 /*return*/, res.json(documentFile)];
255
- }
256
- });
257
- }); })], false));
139
+ app.post(`${basePath}/`, ...adminGuard, upload.single("file"), (0, api_1.asyncHandler)(async (req, res) => {
140
+ const file = req.file;
141
+ if (!file) {
142
+ throw new api_1.APIError({ status: 400, title: "No file provided" });
143
+ }
144
+ const targetPrefix = req.body.prefix ?? "";
145
+ const sanitizedFilename = file.originalname.replace(/[^a-zA-Z0-9._-]/g, "_");
146
+ const gcsPath = `${this.prefix}${targetPrefix}${sanitizedFilename}`;
147
+ const gcsFile = this.bucket.file(gcsPath);
148
+ await gcsFile.save(file.buffer, {
149
+ contentType: file.mimetype,
150
+ });
151
+ const documentFile = {
152
+ contentType: file.mimetype,
153
+ fullPath: `${targetPrefix}${sanitizedFilename}`,
154
+ isFolder: false,
155
+ name: sanitizedFilename,
156
+ size: file.buffer.length,
157
+ updated: luxon_1.DateTime.now().toISO(),
158
+ };
159
+ return res.json(documentFile);
160
+ }));
258
161
  // GET basePath/download/* — Stream file download
259
- app.get.apply(app, __spreadArray(__spreadArray(["".concat(basePath, "/download/*filepath")], __read(adminGuard), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
260
- var filePath, gcsPath, gcsFile, metadata, _a, meta, err_1, storageErr, contentType, filename, err_2, pipelineErr;
261
- var _b, _c, _d;
262
- return __generator(this, function (_e) {
263
- switch (_e.label) {
264
- case 0:
265
- filePath = normalizePathParam(req.params.filepath);
266
- if (!filePath) {
267
- throw new api_1.APIError({ status: 400, title: "File path is required" });
268
- }
269
- gcsPath = "".concat(this.prefix).concat(filePath);
270
- gcsFile = this.bucket.file(gcsPath);
271
- _e.label = 1;
272
- case 1:
273
- _e.trys.push([1, 3, , 4]);
274
- return [4 /*yield*/, gcsFile.getMetadata()];
275
- case 2:
276
- _a = __read.apply(void 0, [_e.sent(), 1]), meta = _a[0];
277
- metadata = meta;
278
- return [3 /*break*/, 4];
279
- case 3:
280
- err_1 = _e.sent();
281
- storageErr = err_1;
282
- if ((storageErr === null || storageErr === void 0 ? void 0 : storageErr.code) === 404) {
283
- throw new api_1.APIError({
284
- disableExternalErrorTracking: true,
285
- status: 404,
286
- title: "File not found",
287
- });
288
- }
289
- api_1.logger.error("Document download metadata failed", {
290
- status: (_b = storageErr === null || storageErr === void 0 ? void 0 : storageErr.code) !== null && _b !== void 0 ? _b : storageErr === null || storageErr === void 0 ? void 0 : storageErr.status,
291
- });
292
- throw new api_1.APIError({
293
- status: 500,
294
- title: "Failed to access file",
295
- });
296
- case 4:
297
- contentType = (_c = metadata.contentType) !== null && _c !== void 0 ? _c : "application/octet-stream";
298
- filename = (_d = filePath.split("/").filter(Boolean).pop()) !== null && _d !== void 0 ? _d : "download";
299
- res.setHeader("Content-Type", contentType);
300
- res.setHeader("Content-Disposition", "attachment; filename=\"".concat(filename, "\""));
301
- if (metadata.size) {
302
- res.setHeader("Content-Length", String(metadata.size));
303
- }
304
- _e.label = 5;
305
- case 5:
306
- _e.trys.push([5, 7, , 8]);
307
- return [4 /*yield*/, (0, promises_1.pipeline)(gcsFile.createReadStream(), res)];
308
- case 6:
309
- _e.sent();
310
- return [3 /*break*/, 8];
311
- case 7:
312
- err_2 = _e.sent();
313
- pipelineErr = err_2;
314
- api_1.logger.error("Document download stream failed", {
315
- status: pipelineErr === null || pipelineErr === void 0 ? void 0 : pipelineErr.code,
316
- });
317
- if (!res.headersSent) {
318
- throw new api_1.APIError({
319
- status: 500,
320
- title: "Failed to stream file",
321
- });
322
- }
323
- return [3 /*break*/, 8];
324
- case 8: return [2 /*return*/];
325
- }
162
+ app.get(`${basePath}/download/*filepath`, ...adminGuard, (0, api_1.asyncHandler)(async (req, res) => {
163
+ const filePath = normalizePathParam(req.params.filepath);
164
+ if (!filePath) {
165
+ throw new api_1.APIError({ status: 400, title: "File path is required" });
166
+ }
167
+ const gcsPath = `${this.prefix}${filePath}`;
168
+ const gcsFile = this.bucket.file(gcsPath);
169
+ let metadata;
170
+ try {
171
+ const [meta] = await gcsFile.getMetadata();
172
+ metadata = meta;
173
+ }
174
+ catch (err) {
175
+ const storageErr = err;
176
+ if (storageErr?.code === 404) {
177
+ throw new api_1.APIError({
178
+ disableExternalErrorTracking: true,
179
+ status: 404,
180
+ title: "File not found",
181
+ });
182
+ }
183
+ api_1.logger.error("Document download metadata failed", {
184
+ status: storageErr?.code ?? storageErr?.status,
326
185
  });
327
- }); })], false));
328
- // POST basePath/folder — Create a folder
329
- app.post.apply(app, __spreadArray(__spreadArray(["".concat(basePath, "/folder")], __read(adminGuard), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
330
- var _a, folderName, prefix, sanitizedName, targetPrefix, gcsPath, gcsFile;
331
- return __generator(this, function (_b) {
332
- switch (_b.label) {
333
- case 0:
334
- _a = req.body, folderName = _a.folderName, prefix = _a.prefix;
335
- if (!folderName) {
336
- throw new api_1.APIError({ status: 400, title: "Folder name is required" });
337
- }
338
- sanitizedName = folderName.replace(/[^a-zA-Z0-9._-]/g, "_");
339
- targetPrefix = prefix !== null && prefix !== void 0 ? prefix : "";
340
- gcsPath = "".concat(this.prefix).concat(targetPrefix).concat(sanitizedName, "/");
341
- gcsFile = this.bucket.file(gcsPath);
342
- return [4 /*yield*/, gcsFile.save(Buffer.alloc(0), { contentType: "application/x-directory" })];
343
- case 1:
344
- _b.sent();
345
- return [2 /*return*/, res.json({ folder: "".concat(targetPrefix).concat(sanitizedName, "/") })];
346
- }
186
+ throw new api_1.APIError({
187
+ status: 500,
188
+ title: "Failed to access file",
347
189
  });
348
- }); })], false));
349
- // DELETE basePath/folder/* — Delete a folder and all its contents
350
- app.delete.apply(app, __spreadArray(__spreadArray(["".concat(basePath, "/folder/*folderpath")], __read(adminGuard), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
351
- var folderPath, gcsPrefix, _a, files;
352
- return __generator(this, function (_b) {
353
- switch (_b.label) {
354
- case 0:
355
- folderPath = normalizePathParam(req.params.folderpath);
356
- if (!folderPath) {
357
- throw new api_1.APIError({ status: 400, title: "Folder path is required" });
358
- }
359
- gcsPrefix = "".concat(this.prefix).concat(folderPath);
360
- return [4 /*yield*/, this.bucket.getFiles({ prefix: gcsPrefix })];
361
- case 1:
362
- _a = __read.apply(void 0, [_b.sent(), 1]), files = _a[0];
363
- return [4 /*yield*/, Promise.all(files.map(function (f) { return f.delete({ ignoreNotFound: true }); }))];
364
- case 2:
365
- _b.sent();
366
- return [2 /*return*/, res.json({ success: true })];
367
- }
190
+ }
191
+ const contentType = metadata.contentType ?? "application/octet-stream";
192
+ const filename = filePath.split("/").filter(Boolean).pop() ?? "download";
193
+ res.setHeader("Content-Type", contentType);
194
+ res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
195
+ if (metadata.size) {
196
+ res.setHeader("Content-Length", String(metadata.size));
197
+ }
198
+ try {
199
+ await (0, promises_1.pipeline)(gcsFile.createReadStream(), res);
200
+ }
201
+ catch (err) {
202
+ const pipelineErr = err;
203
+ api_1.logger.error("Document download stream failed", {
204
+ status: pipelineErr?.code,
368
205
  });
369
- }); })], false));
206
+ if (!res.headersSent) {
207
+ throw new api_1.APIError({
208
+ status: 500,
209
+ title: "Failed to stream file",
210
+ });
211
+ }
212
+ }
213
+ }));
214
+ // POST basePath/folder — Create a folder
215
+ app.post(`${basePath}/folder`, ...adminGuard, (0, api_1.asyncHandler)(async (req, res) => {
216
+ const { folderName, prefix } = req.body;
217
+ if (!folderName) {
218
+ throw new api_1.APIError({ status: 400, title: "Folder name is required" });
219
+ }
220
+ const sanitizedName = folderName.replace(/[^a-zA-Z0-9._-]/g, "_");
221
+ const targetPrefix = prefix ?? "";
222
+ const gcsPath = `${this.prefix}${targetPrefix}${sanitizedName}/`;
223
+ const gcsFile = this.bucket.file(gcsPath);
224
+ await gcsFile.save(Buffer.alloc(0), { contentType: "application/x-directory" });
225
+ return res.json({ folder: `${targetPrefix}${sanitizedName}/` });
226
+ }));
227
+ // DELETE basePath/folder/* — Delete a folder and all its contents
228
+ app.delete(`${basePath}/folder/*folderpath`, ...adminGuard, (0, api_1.asyncHandler)(async (req, res) => {
229
+ const folderPath = normalizePathParam(req.params.folderpath);
230
+ if (!folderPath) {
231
+ throw new api_1.APIError({ status: 400, title: "Folder path is required" });
232
+ }
233
+ const gcsPrefix = `${this.prefix}${folderPath}`;
234
+ const [files] = await this.bucket.getFiles({ prefix: gcsPrefix });
235
+ await Promise.all(files.map((f) => f.delete({ ignoreNotFound: true })));
236
+ return res.json({ success: true });
237
+ }));
370
238
  // DELETE basePath/* — Delete a file
371
- app.delete.apply(app, __spreadArray(__spreadArray(["".concat(basePath, "/*filepath")], __read(adminGuard), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
372
- var filePath, gcsPath, gcsFile;
373
- return __generator(this, function (_a) {
374
- switch (_a.label) {
375
- case 0:
376
- filePath = normalizePathParam(req.params.filepath);
377
- if (!filePath) {
378
- throw new api_1.APIError({ status: 400, title: "File path is required" });
379
- }
380
- gcsPath = "".concat(this.prefix).concat(filePath);
381
- gcsFile = this.bucket.file(gcsPath);
382
- return [4 /*yield*/, gcsFile.delete({ ignoreNotFound: true })];
383
- case 1:
384
- _a.sent();
385
- return [2 /*return*/, res.json({ success: true })];
386
- }
387
- });
388
- }); })], false));
389
- };
390
- return DocumentStorageApp;
391
- }());
239
+ app.delete(`${basePath}/*filepath`, ...adminGuard, (0, api_1.asyncHandler)(async (req, res) => {
240
+ const filePath = normalizePathParam(req.params.filepath);
241
+ if (!filePath) {
242
+ throw new api_1.APIError({ status: 400, title: "File path is required" });
243
+ }
244
+ const gcsPath = `${this.prefix}${filePath}`;
245
+ const gcsFile = this.bucket.file(gcsPath);
246
+ await gcsFile.delete({ ignoreNotFound: true });
247
+ return res.json({ success: true });
248
+ }));
249
+ }
250
+ }
392
251
  exports.DocumentStorageApp = DocumentStorageApp;
@@ -1,37 +1,26 @@
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
14
3
  exports.enrichAdminListFilters = void 0;
15
4
  /**
16
5
  * Derives `allowEmpty` for optional choice filters from the Mongoose schema when not
17
6
  * set explicitly on admin config.
18
7
  */
19
- var enrichAdminListFilters = function (filters, model) {
8
+ const enrichAdminListFilters = (filters, model) => {
20
9
  if (!filters) {
21
10
  return filters;
22
11
  }
23
- return filters.map(function (filter) {
12
+ return filters.map((filter) => {
24
13
  if (filter.kind !== "choice") {
25
14
  return filter;
26
15
  }
27
16
  if (filter.allowEmpty !== undefined) {
28
17
  return filter;
29
18
  }
30
- var path = model.schema.path(filter.field);
19
+ const path = model.schema.path(filter.field);
31
20
  if (!path || path.isRequired) {
32
21
  return filter;
33
22
  }
34
- return __assign(__assign({}, filter), { allowEmpty: true });
23
+ return { ...filter, allowEmpty: true };
35
24
  });
36
25
  };
37
26
  exports.enrichAdminListFilters = enrichAdminListFilters;