arkos 1.1.68-test → 1.1.70-test

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 (78) hide show
  1. package/dist/cjs/app.js +1 -1
  2. package/dist/cjs/app.js.map +1 -1
  3. package/dist/cjs/exports/controllers/index.js +5 -3
  4. package/dist/cjs/exports/controllers/index.js.map +1 -1
  5. package/dist/cjs/exports/services/index.js +4 -4
  6. package/dist/cjs/exports/services/index.js.map +1 -1
  7. package/dist/cjs/modules/base/base.service.js.map +1 -1
  8. package/dist/cjs/modules/{file-uploader/file-uploader.controller.js → file-upload/file-upload.controller.js} +29 -29
  9. package/dist/cjs/modules/file-upload/file-upload.controller.js.map +1 -0
  10. package/dist/cjs/modules/{file-uploader/file-uploader.router.js → file-upload/file-upload.router.js} +7 -7
  11. package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -0
  12. package/dist/cjs/modules/{file-uploader/file-uploader.service.js → file-upload/file-upload.service.js} +38 -38
  13. package/dist/cjs/modules/file-upload/file-upload.service.js.map +1 -0
  14. package/dist/cjs/modules/{file-uploader/utils/helpers/file-uploader.helpers.js → file-upload/utils/helpers/file-upload.helpers.js} +1 -1
  15. package/dist/cjs/modules/file-upload/utils/helpers/file-upload.helpers.js.map +1 -0
  16. package/dist/cjs/types/arkos-config.js.map +1 -1
  17. package/dist/cjs/utils/cli/build.js +8 -5
  18. package/dist/cjs/utils/cli/build.js.map +1 -1
  19. package/dist/cjs/utils/cli/generate.js +171 -0
  20. package/dist/cjs/utils/cli/generate.js.map +1 -0
  21. package/dist/cjs/utils/cli/index.js +41 -1
  22. package/dist/cjs/utils/cli/index.js.map +1 -1
  23. package/dist/cjs/utils/cli/utils/generators.js +200 -0
  24. package/dist/cjs/utils/cli/utils/generators.js.map +1 -0
  25. package/dist/cjs/utils/cli/utils/helpers.js +17 -0
  26. package/dist/cjs/utils/cli/utils/helpers.js.map +1 -0
  27. package/dist/cjs/utils/helpers/models.helpers.js +40 -30
  28. package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
  29. package/dist/es2020/app.js +1 -1
  30. package/dist/es2020/app.js.map +1 -1
  31. package/dist/es2020/exports/controllers/index.js +3 -2
  32. package/dist/es2020/exports/controllers/index.js.map +1 -1
  33. package/dist/es2020/exports/services/index.js +2 -2
  34. package/dist/es2020/exports/services/index.js.map +1 -1
  35. package/dist/es2020/modules/base/base.service.js.map +1 -1
  36. package/dist/es2020/modules/{file-uploader/file-uploader.controller.js → file-upload/file-upload.controller.js} +21 -21
  37. package/dist/es2020/modules/file-upload/file-upload.controller.js.map +1 -0
  38. package/dist/es2020/modules/{file-uploader/file-uploader.router.js → file-upload/file-upload.router.js} +6 -6
  39. package/dist/es2020/modules/file-upload/file-upload.router.js.map +1 -0
  40. package/dist/es2020/modules/{file-uploader/file-uploader.service.js → file-upload/file-upload.service.js} +31 -31
  41. package/dist/es2020/modules/file-upload/file-upload.service.js.map +1 -0
  42. package/dist/es2020/modules/{file-uploader/utils/helpers/file-uploader.helpers.js → file-upload/utils/helpers/file-upload.helpers.js} +1 -1
  43. package/dist/es2020/modules/file-upload/utils/helpers/file-upload.helpers.js.map +1 -0
  44. package/dist/es2020/types/arkos-config.js.map +1 -1
  45. package/dist/es2020/utils/cli/build.js +8 -5
  46. package/dist/es2020/utils/cli/build.js.map +1 -1
  47. package/dist/es2020/utils/cli/generate.js +165 -0
  48. package/dist/es2020/utils/cli/generate.js.map +1 -0
  49. package/dist/es2020/utils/cli/index.js +40 -1
  50. package/dist/es2020/utils/cli/index.js.map +1 -1
  51. package/dist/es2020/utils/cli/utils/generators.js +197 -0
  52. package/dist/es2020/utils/cli/utils/generators.js.map +1 -0
  53. package/dist/es2020/utils/cli/utils/helpers.js +10 -0
  54. package/dist/es2020/utils/cli/utils/helpers.js.map +1 -0
  55. package/dist/es2020/utils/helpers/models.helpers.js +38 -30
  56. package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
  57. package/dist/types/exports/controllers/index.d.ts +3 -2
  58. package/dist/types/exports/services/index.d.ts +2 -2
  59. package/dist/types/modules/{file-uploader/file-uploader.controller.d.ts → file-upload/file-upload.controller.d.ts} +3 -3
  60. package/dist/types/modules/file-upload/file-upload.router.d.ts +3 -0
  61. package/dist/types/modules/{file-uploader/file-uploader.service.d.ts → file-upload/file-upload.service.d.ts} +7 -7
  62. package/dist/types/types/arkos-config.d.ts +2 -2
  63. package/dist/types/utils/cli/generate.d.ts +12 -0
  64. package/dist/types/utils/cli/index.d.ts +2 -1
  65. package/dist/types/utils/cli/utils/generators.d.ts +17 -0
  66. package/dist/types/utils/cli/utils/helpers.d.ts +2 -0
  67. package/dist/types/utils/helpers/models.helpers.d.ts +2 -0
  68. package/package.json +2 -2
  69. package/dist/cjs/modules/file-uploader/file-uploader.controller.js.map +0 -1
  70. package/dist/cjs/modules/file-uploader/file-uploader.router.js.map +0 -1
  71. package/dist/cjs/modules/file-uploader/file-uploader.service.js.map +0 -1
  72. package/dist/cjs/modules/file-uploader/utils/helpers/file-uploader.helpers.js.map +0 -1
  73. package/dist/es2020/modules/file-uploader/file-uploader.controller.js.map +0 -1
  74. package/dist/es2020/modules/file-uploader/file-uploader.router.js.map +0 -1
  75. package/dist/es2020/modules/file-uploader/file-uploader.service.js.map +0 -1
  76. package/dist/es2020/modules/file-uploader/utils/helpers/file-uploader.helpers.js.map +0 -1
  77. package/dist/types/modules/file-uploader/file-uploader.router.d.ts +0 -3
  78. /package/dist/types/modules/{file-uploader/utils/helpers/file-uploader.helpers.d.ts → file-upload/utils/helpers/file-upload.helpers.d.ts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,WAAW,MAAM,sBAAsB,CAAC;AAC/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AI;QACjB,KAAK,EAAE,KAAK;QACZ,YAAY,EAAE,IAAI;KACnB,EACD,UAAU,EAAE,oBAAoB,IAAI,EAAE,CACvC,CACF,CACF,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,GAAG,YAAY,WAAW,EAC1B,WAAW,CAAC,2BAA2B,CACrC,QAAQ,EACR,WAAW,CAAC,qBAAqB,CAClC,EACD,WAAW,CAAC,mBAAmB,CAC7B,QAAQ,EACR,aAAa,EACb,WAAW,CAAC,aAAa,CAC1B,EACD,oBAAoB,CAAC,UAAU,CAChC,CAAC;IAEF,MAAM,CAAC,MAAM,CACX,GAAG,YAAY,qBAAqB,EACpC,WAAW,CAAC,2BAA2B,CACrC,QAAQ,EACR,WAAW,CAAC,qBAAqB,CAClC,EACD,WAAW,CAAC,mBAAmB,CAC7B,QAAQ,EACR,aAAa,EACb,WAAW,CAAC,aAAa,CAC1B,EACD,oBAAoB,CAAC,UAAU,CAChC,CAAC;IAEF,MAAM,CAAC,MAAM,CACX,GAAG,YAAY,qBAAqB,EACpC,WAAW,CAAC,2BAA2B,CACrC,QAAQ,EACR,WAAW,CAAC,qBAAqB,CAClC,EACD,WAAW,CAAC,mBAAmB,CAC7B,QAAQ,EACR,aAAa,EACb,WAAW,CAAC,aAAa,CAC1B,EACD,oBAAoB,CAAC,UAAU,CAChC,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport authService from \"../auth/auth.service\";\nimport fileUploadController from \"./file-upload.controller\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport path from \"path\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nconst router: Router = Router();\n\nexport async function getFileUploadRouter({ fileUpload }: ArkosConfig) {\n const modelModules = await importPrismaModelModules(\"file-upload\");\n let { middlewares = {}, authConfigs = {} as AuthConfigs } = {};\n\n if (modelModules) {\n ({ middlewares = {}, authConfigs = {} } = modelModules);\n }\n\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n router.use(\n basePathname,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n express.static(\n path.resolve(process.cwd(), fileUpload?.baseUploadDir || \"uploads\"),\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStaticOptions || {}\n )\n )\n );\n\n router.post(\n `${basePathname}:fileType`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n fileUploadController.uploadFile\n );\n\n router.delete(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n fileUploadController.deleteFile\n );\n\n router.delete(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n fileUploadController.updateFile\n );\n\n return router;\n}\n"]}
@@ -5,9 +5,9 @@ import AppError from "../error-handler/utils/app-error";
5
5
  import { promisify } from "util";
6
6
  import { getArkosConfig } from "../../server";
7
7
  import deepmerge from "../../utils/helpers/deepmerge.helper";
8
- import { processFile, processImage, } from "./utils/helpers/file-uploader.helpers";
8
+ import { processFile, processImage } from "./utils/helpers/file-upload.helpers";
9
9
  import { removeBothSlashes } from "../../utils/helpers/text.helpers";
10
- export class FileUploaderService {
10
+ export class FileUploadService {
11
11
  constructor(uploadDir, fileSizeLimit = 1024 * 1024 * 5, allowedFileTypes = /.*/, maxCount = 30) {
12
12
  this.fileFilter = (req, file, cb) => {
13
13
  const extName = this.allowedFileTypes.test(path.extname(file.originalname).toLowerCase());
@@ -38,7 +38,7 @@ export class FileUploaderService {
38
38
  },
39
39
  });
40
40
  }
41
- getUploader() {
41
+ getUpload() {
42
42
  return multer({
43
43
  storage: this.storage,
44
44
  fileFilter: this.fileFilter,
@@ -47,7 +47,7 @@ export class FileUploaderService {
47
47
  }
48
48
  handleSingleUpload(oldFilePath) {
49
49
  return (req, res, next) => {
50
- const upload = this.getUploader().single(this.getFieldName());
50
+ const upload = this.getUpload().single(this.getFieldName());
51
51
  upload(req, res, async (err) => {
52
52
  if (err instanceof multer.MulterError) {
53
53
  return next(err);
@@ -73,7 +73,7 @@ export class FileUploaderService {
73
73
  }
74
74
  handleMultipleUpload() {
75
75
  return (req, res, next) => {
76
- const upload = this.getUploader().array(this.getFieldName(), this.maxCount);
76
+ const upload = this.getUpload().array(this.getFieldName(), this.maxCount);
77
77
  upload(req, res, (err) => {
78
78
  if (err instanceof multer.MulterError)
79
79
  return next(err);
@@ -132,20 +132,20 @@ export class FileUploaderService {
132
132
  if (!fileType || !fileName) {
133
133
  throw new AppError("Unable to determine file type or file name from URL", 400);
134
134
  }
135
- const { documentUploaderService, fileUploaderService, imageUploaderService, videoUploaderService, } = getFileUploaderServices();
135
+ const { documentUploadService, fileUploadService, imageUploadService, videoUploadService, } = getFileUploadServices();
136
136
  let filePath;
137
137
  switch (fileType) {
138
138
  case "images":
139
- filePath = path.join(imageUploaderService.uploadDir, fileName);
139
+ filePath = path.join(imageUploadService.uploadDir, fileName);
140
140
  break;
141
141
  case "videos":
142
- filePath = path.join(videoUploaderService.uploadDir, fileName);
142
+ filePath = path.join(videoUploadService.uploadDir, fileName);
143
143
  break;
144
144
  case "documents":
145
- filePath = path.join(documentUploaderService.uploadDir, fileName);
145
+ filePath = path.join(documentUploadService.uploadDir, fileName);
146
146
  break;
147
147
  case "files":
148
- filePath = path.join(fileUploaderService.uploadDir, fileName);
148
+ filePath = path.join(fileUploadService.uploadDir, fileName);
149
149
  break;
150
150
  default:
151
151
  throw new AppError(`Unsupported file type: ${fileType}`, 400);
@@ -185,8 +185,8 @@ export class FileUploaderService {
185
185
  ? req.query.multiple[0] == "true"
186
186
  : req.query.multiple == "true";
187
187
  const uploadHandler = isMultiple
188
- ? this.getUploader().array(this.getFieldName(), this.maxCount)
189
- : this.getUploader().single(this.getFieldName());
188
+ ? this.getUpload().array(this.getFieldName(), this.maxCount)
189
+ : this.getUpload().single(this.getFieldName());
190
190
  uploadHandler(req, res, async (err) => {
191
191
  if (err)
192
192
  return reject(err);
@@ -201,8 +201,8 @@ export class FileUploaderService {
201
201
  : dirParts[dirParts.length - 1]) || "files";
202
202
  let data;
203
203
  if (req.files && Array.isArray(req.files) && req.files.length > 0) {
204
- const isImageUploader = this.uploadDir?.includes?.("/images");
205
- if (isImageUploader) {
204
+ const isImageUpload = this.uploadDir?.includes?.("/images");
205
+ if (isImageUpload) {
206
206
  data = await Promise.all(req.files.map((file) => processImage(req, file.path, options)));
207
207
  }
208
208
  else {
@@ -211,8 +211,8 @@ export class FileUploaderService {
211
211
  data = data.filter((url) => url !== null);
212
212
  }
213
213
  else if (req.file) {
214
- const isImageUploader = this.uploadDir?.includes?.("/images");
215
- if (isImageUploader) {
214
+ const isImageUpload = this.uploadDir?.includes?.("/images");
215
+ if (isImageUpload) {
216
216
  data = await processImage(req, req.file.path, options);
217
217
  }
218
218
  else {
@@ -238,20 +238,20 @@ export class FileUploaderService {
238
238
  if (!validFileTypes.includes(fileType)) {
239
239
  throw new AppError(`Invalid file type: ${fileType}. Must be one of: ${validFileTypes.join(", ")}`, 400);
240
240
  }
241
- const { documentUploaderService, fileUploaderService, imageUploaderService, videoUploaderService, } = getFileUploaderServices();
241
+ const { documentUploadService, fileUploadService, imageUploadService, videoUploadService, } = getFileUploadServices();
242
242
  let targetService;
243
243
  switch (fileType) {
244
244
  case "images":
245
- targetService = imageUploaderService;
245
+ targetService = imageUploadService;
246
246
  break;
247
247
  case "videos":
248
- targetService = videoUploaderService;
248
+ targetService = videoUploadService;
249
249
  break;
250
250
  case "documents":
251
- targetService = documentUploaderService;
251
+ targetService = documentUploadService;
252
252
  break;
253
253
  case "files":
254
- targetService = fileUploaderService;
254
+ targetService = fileUploadService;
255
255
  break;
256
256
  default:
257
257
  throw new AppError(`Unsupported file type: ${fileType}`, 400);
@@ -272,7 +272,7 @@ export class FileUploaderService {
272
272
  }
273
273
  }
274
274
  }
275
- export const getFileUploaderServices = () => {
275
+ export const getFileUploadServices = () => {
276
276
  const { fileUpload } = getArkosConfig();
277
277
  const baseUploadDir = fileUpload?.baseUploadDir || "/uploads";
278
278
  const defaultRestrictions = {
@@ -300,15 +300,15 @@ export const getFileUploaderServices = () => {
300
300
  const restrictions = fileUpload?.restrictions
301
301
  ? deepmerge(defaultRestrictions, fileUpload.restrictions)
302
302
  : defaultRestrictions;
303
- const imageUploaderService = new FileUploaderService(`${baseUploadDir}/images`, restrictions.images.maxSize, restrictions.images.supportedFilesRegex, restrictions.images.maxCount);
304
- const videoUploaderService = new FileUploaderService(`${baseUploadDir}/videos`, restrictions.videos.maxSize, restrictions.videos.supportedFilesRegex, restrictions.videos.maxCount);
305
- const documentUploaderService = new FileUploaderService(`${baseUploadDir}/documents`, restrictions.documents.maxSize, restrictions.documents.supportedFilesRegex, restrictions.documents.maxCount);
306
- const fileUploaderService = new FileUploaderService(`${baseUploadDir}/files`, restrictions.files.maxSize, restrictions.files.supportedFilesRegex, restrictions.files.maxCount);
303
+ const imageUploadService = new FileUploadService(`${baseUploadDir}/images`, restrictions.images.maxSize, restrictions.images.supportedFilesRegex, restrictions.images.maxCount);
304
+ const videoUploadService = new FileUploadService(`${baseUploadDir}/videos`, restrictions.videos.maxSize, restrictions.videos.supportedFilesRegex, restrictions.videos.maxCount);
305
+ const documentUploadService = new FileUploadService(`${baseUploadDir}/documents`, restrictions.documents.maxSize, restrictions.documents.supportedFilesRegex, restrictions.documents.maxCount);
306
+ const fileUploadService = new FileUploadService(`${baseUploadDir}/files`, restrictions.files.maxSize, restrictions.files.supportedFilesRegex, restrictions.files.maxCount);
307
307
  return {
308
- imageUploaderService,
309
- videoUploaderService,
310
- documentUploaderService,
311
- fileUploaderService,
308
+ imageUploadService,
309
+ videoUploadService,
310
+ documentUploadService,
311
+ fileUploadService,
312
312
  };
313
313
  };
314
- //# sourceMappingURL=file-uploader.service.js.map
314
+ //# sourceMappingURL=file-upload.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-upload.service.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.service.ts"],"names":[],"mappings":"AAAA,OAAO,MAAyB,MAAM,QAAQ,CAAC;AAC/C,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAE7D,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AAChF,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAMrE,MAAM,OAAO,iBAAiB;IAa5B,YACE,SAAiB,EACjB,gBAAwB,IAAI,GAAG,IAAI,GAAG,CAAC,EACvC,mBAA2B,IAAI,EAC/B,WAAmB,EAAE;QA+Bf,eAAU,GAAG,CAAC,GAAQ,EAAE,IAAS,EAAE,EAAO,EAAE,EAAE;YACpD,MAAM,OAAO,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CACxC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,CAA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AiB,CAC7C,GAAG,aAAa,QAAQ,EACxB,YAAY,CAAC,KAAK,CAAC,OAAO,EAC1B,YAAY,CAAC,KAAK,CAAC,mBAAmB,EACtC,YAAY,CAAC,KAAK,CAAC,QAAQ,CAC5B,CAAC;IAEF,OAAO;QACL,kBAAkB;QAClB,kBAAkB;QAClB,qBAAqB;QACrB,iBAAiB;KAClB,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import multer, { StorageEngine } from \"multer\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { NextFunction } from \"express\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { promisify } from \"util\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { ArkosRequest, ArkosResponse } from \"../../types\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { removeBothSlashes } from \"../../utils/helpers/text.helpers\";\n\n/**\n * Service to handle file uploads, including single and multiple file uploads,\n * file validation (type, size), and file deletion.\n */\nexport class FileUploadService {\n public readonly uploadDir: string;\n private fileSizeLimit: number;\n private allowedFileTypes: RegExp;\n private storage: StorageEngine;\n private maxCount: number;\n\n /**\n * Constructor to initialize the file uploader service.\n * @param {string} uploadDir - The directory where files will be uploaded.\n * @param {number} fileSizeLimit - The maximum allowed file size.\n * @param {RegExp} allowedFileTypes - The regular expression for allowed file types.\n */\n constructor(\n uploadDir: string,\n fileSizeLimit: number = 1024 * 1024 * 5,\n allowedFileTypes: RegExp = /.*/,\n maxCount: number = 30\n ) {\n uploadDir = uploadDir.startsWith(\"/\") ? uploadDir.substring(1) : uploadDir;\n uploadDir = uploadDir.endsWith(\"/\") ? uploadDir.slice(0, -1) : uploadDir;\n\n this.uploadDir = path.resolve(process.cwd(), `${uploadDir}/`);\n this.fileSizeLimit = fileSizeLimit;\n this.allowedFileTypes = allowedFileTypes;\n this.maxCount = maxCount;\n\n if (!fs.existsSync(this.uploadDir)) {\n fs.mkdirSync(this.uploadDir, { recursive: true });\n }\n\n this.storage = multer.diskStorage({\n destination: (req, file, cb) => {\n cb(null, this.uploadDir);\n },\n filename: (req, file, cb) => {\n const uniqueSuffix = Date.now() + \"-\" + Math.round(Math.random() * 1e9);\n cb(null, `${uniqueSuffix}${path.extname(file.originalname)}`);\n },\n });\n }\n\n /**\n * Validates the file's type and MIME type.\n * @param {Request} req - The Express request object.\n * @param {Express.Multer.File} file - The uploaded file.\n * @param {Function} cb - The callback function to indicate if file is valid.\n */\n private fileFilter = (req: any, file: any, cb: any) => {\n const extName = this.allowedFileTypes.test(\n path.extname(file.originalname).toLowerCase()\n );\n const mimeType = this.allowedFileTypes.test(file.mimetype);\n\n if (mimeType && extName) {\n cb(null, true);\n } else {\n cb(new AppError(\"Invalid file type\", 400));\n }\n };\n\n /**\n * Returns the multer upload configuration.\n * @returns {multer.Instance} The multer instance configured for file uploads.\n */\n public getUpload() {\n return multer({\n storage: this.storage,\n fileFilter: this.fileFilter,\n limits: { fileSize: this.fileSizeLimit },\n });\n }\n\n /**\n * Middleware to handle single file upload.\n * @param {string} [oldFilePath] - The path to the file to delete before uploading.\n * @returns {Function} Middleware function for handling file upload.\n */\n public handleSingleUpload(oldFilePath?: string) {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const upload = this.getUpload().single(this.getFieldName());\n upload(req, res, async (err) => {\n if (err instanceof multer.MulterError) {\n return next(err);\n } else if (err) {\n return next(err);\n }\n\n if (oldFilePath) {\n const { fileUpload: configs } = getArkosConfig();\n\n const filePath = path.resolve(\n process.cwd(),\n removeBothSlashes(configs?.baseUploadDir!),\n removeBothSlashes(oldFilePath)\n );\n try {\n const stats = await promisify(fs.stat)(filePath);\n if (stats) await promisify(fs.unlink)(filePath);\n } catch (err) {\n console.error(err);\n }\n }\n\n next();\n });\n };\n }\n\n /**\n * Middleware to handle multiple file uploads.\n * @param {number} maxCount - The maximum number of files allowed for upload.\n * @returns {Function} Middleware function for handling multiple file uploads.\n */\n public handleMultipleUpload() {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const upload = this.getUpload().array(this.getFieldName(), this.maxCount);\n upload(req, res, (err) => {\n if (err instanceof multer.MulterError) return next(err);\n else if (err) return next(err);\n next();\n });\n };\n }\n\n /**\n * Middleware to handle deletion of a single file from the filesystem.\n * @param {string} oldFilePath - The path to the file to be deleted.\n * @returns {Function} Middleware function for handling file deletion.\n */\n public handleDeleteSingleFile(oldFilePath: string) {\n return async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: NextFunction\n ) => {\n const filePath = path.join(oldFilePath);\n try {\n const stats = await promisify(fs.stat)(filePath);\n if (stats) {\n await promisify(fs.unlink)(filePath);\n }\n } catch (err) {\n console.error(err);\n }\n\n next();\n };\n }\n\n /**\n * Deletes a file based on its URL by identifying the appropriate uploader service\n * @param {string} fileUrl - The URL of the file to delete\n * @returns {Promise<boolean>} - True if deletion successful, false otherwise\n */\n public async deleteFileByUrl(fileUrl: string): Promise<boolean> {\n try {\n // Get configuration values\n const { fileUpload } = getArkosConfig();\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // Parse the URL to get the path\n let urlPath: string;\n if (fileUrl.startsWith(\"http\")) {\n const url = new URL(fileUrl);\n urlPath = url.pathname;\n } else {\n urlPath = fileUrl;\n }\n\n // Extract the path after the base route\n const baseRouteIndex = urlPath.indexOf(baseRoute);\n if (baseRouteIndex === -1) {\n throw new AppError(\"Invalid file URL: base route not found\", 400);\n }\n\n const pathAfterBaseRoute = urlPath.substring(\n baseRouteIndex + baseRoute.length\n );\n const cleanPath = pathAfterBaseRoute.startsWith(\"/\")\n ? pathAfterBaseRoute.substring(1)\n : pathAfterBaseRoute;\n\n // Determine file type and file name\n const fileTypes = [\"images\", \"videos\", \"documents\", \"files\"];\n let fileType: string | null = null;\n let fileName: string | null = null;\n\n for (const type of fileTypes) {\n const typeIndex = cleanPath.indexOf(type + \"/\");\n if (typeIndex !== -1) {\n fileType = type;\n fileName = cleanPath.substring(typeIndex + type.length + 1);\n break;\n }\n }\n\n if (!fileType || !fileName) {\n throw new AppError(\n \"Unable to determine file type or file name from URL\",\n 400\n );\n }\n\n // Get the appropriate uploader service based on file type\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let filePath: string;\n switch (fileType) {\n case \"images\":\n filePath = path.join(imageUploadService.uploadDir, fileName);\n break;\n case \"videos\":\n filePath = path.join(videoUploadService.uploadDir, fileName);\n break;\n case \"documents\":\n filePath = path.join(documentUploadService.uploadDir, fileName);\n break;\n case \"files\":\n filePath = path.join(fileUploadService.uploadDir, fileName);\n break;\n default:\n throw new AppError(`Unsupported file type: ${fileType}`, 400);\n }\n\n // Delete the file\n\n await promisify(fs.stat)(filePath);\n await promisify(fs.unlink)(filePath);\n\n return true;\n } catch (error: any) {\n if (error instanceof AppError) {\n throw error;\n }\n\n if (error.code === \"ENOENT\") {\n throw new AppError(\"File not found\", 404);\n }\n\n throw new AppError(`Failed to delete file: ${error.message}`, 500);\n }\n }\n\n private getFieldName() {\n let fieldName = \"files\";\n if (this.uploadDir.endsWith(\"images\") || this.uploadDir.endsWith(\"images/\"))\n fieldName = \"images\";\n if (this.uploadDir.endsWith(\"videos\") || this.uploadDir.endsWith(\"videos/\"))\n fieldName = \"videos\";\n if (\n this.uploadDir.endsWith(\"documents\") ||\n this.uploadDir.endsWith(\"documents/\")\n )\n fieldName = \"documents\";\n if (this.uploadDir.endsWith(\"files\") || this.uploadDir.endsWith(\"files/\"))\n fieldName = \"files\";\n return fieldName;\n }\n\n /**\n * Handles the upload process and returns the full URLs of uploaded files\n * @param {ArkosRequest} req - Arkos request object containing the files\n * @param {ArkosResponse} res - Arkos response object\n * @param {object} options - Optional parameters for image processing\n * @returns {Promise<string|string[]>} URL or array of URLs to the uploaded files\n */\n public async upload(\n req: ArkosRequest,\n res: ArkosResponse,\n options: {\n format?: string;\n width?: number;\n height?: number;\n resizeTo?: number;\n } = {}\n ): Promise<string | string[] | null> {\n const { fileUpload } = getArkosConfig();\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n return new Promise((resolve, reject) => {\n // Determine if it's a single or multiple file upload\n const isMultiple = Array.isArray(req.query.multiple)\n ? req.query.multiple[0] == \"true\"\n : req.query.multiple == \"true\";\n\n // Use appropriate upload handler\n const uploadHandler = isMultiple\n ? this.getUpload().array(this.getFieldName(), this.maxCount)\n : this.getUpload().single(this.getFieldName());\n\n uploadHandler(req, res, async (err) => {\n if (err) return reject(err);\n\n try {\n // Determine the base URL for file access\n const protocol = req.get(\"host\")?.includes?.(\"localhost\")\n ? \"http\"\n : \"https\";\n const baseURL = `${protocol}://${req.get(\"host\")}`;\n\n // Get file type from uploadDir path\n const dirParts = this.uploadDir.split(\"/\");\n const fileType =\n (this.uploadDir.endsWith(\"/\")\n ? dirParts[dirParts.length - 2]\n : dirParts[dirParts.length - 1]) || \"files\";\n\n // Process all uploaded files\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n // Process multiple files\n const isImageUpload = this.uploadDir?.includes?.(\"/images\");\n if (isImageUpload) {\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n const isImageUpload = this.uploadDir?.includes?.(\"/images\");\n if (isImageUpload) {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return reject(new AppError(\"No file uploaded\", 400));\n }\n\n resolve(data);\n } catch (error) {\n reject(error);\n }\n });\n });\n }\n\n /**\n * Deletes a file based on filename and file type from request parameters\n * @param {string} fileName - The name of the file to delete\n * @param {ArkosRequest} req - Arkos request object containing params.fileType\n * @returns {Promise<boolean>} - True if deletion successful, false otherwise\n */\n public async deleteFileByName(\n fileName: string,\n fileType: \"images\" | \"videos\" | \"documents\" | \"files\"\n ): Promise<boolean> {\n try {\n if (!fileType) throw new AppError(\"File type parameter is required\", 400);\n\n // Validate file type\n const validFileTypes = [\"images\", \"videos\", \"documents\", \"files\"];\n if (!validFileTypes.includes(fileType)) {\n throw new AppError(\n `Invalid file type: ${fileType}. Must be one of: ${validFileTypes.join(\n \", \"\n )}`,\n 400\n );\n }\n\n // Get the appropriate uploader service based on file type\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let targetService: FileUploadService;\n switch (fileType) {\n case \"images\":\n targetService = imageUploadService;\n break;\n case \"videos\":\n targetService = videoUploadService;\n break;\n case \"documents\":\n targetService = documentUploadService;\n break;\n case \"files\":\n targetService = fileUploadService;\n break;\n default:\n throw new AppError(`Unsupported file type: ${fileType}`, 400);\n }\n\n // Construct the full file path\n const filePath = path.join(targetService.uploadDir, fileName);\n\n // Check if file exists and delete it\n await promisify(fs.stat)(filePath);\n await promisify(fs.unlink)(filePath);\n\n return true;\n } catch (error: any) {\n if (error instanceof AppError) {\n throw error;\n }\n\n if (error.code === \"ENOENT\") {\n throw new AppError(\"File not found\", 404);\n }\n\n throw new AppError(`Failed to delete file: ${error.message}`, 500);\n }\n }\n}\n\n/**\n * Creates and returns all file uploader services based on config\n * @returns Object containing all specialized file uploader services\n */\nexport const getFileUploadServices = () => {\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Default upload restrictions\n const defaultRestrictions = {\n images: {\n maxCount: 30,\n maxSize: 1024 * 1024 * 15, // 15 MB\n supportedFilesRegex:\n /jpeg|jpg|png|gif|webp|svg|bmp|tiff|heif|heic|ico|jfif|raw|cr2|nef|orf|sr2|arw|dng|pef|raf|rw2|psd|ai|eps|xcf|jxr|wdp|hdp|jp2|j2k|jpf|jpx|jpm|mj2|avif/,\n },\n videos: {\n maxCount: 10,\n maxSize: 1024 * 1024 * 5096, // 5 GB\n supportedFilesRegex:\n /mp4|avi|mov|mkv|flv|wmv|webm|mpg|mpeg|3gp|m4v|ts|rm|rmvb|vob|ogv|dv|qt|asf|m2ts|mts|divx|f4v|swf|mxf|roq|nsv|mvb|svi|mpe|m2v|mp2|mpv|h264|h265|hevc/,\n },\n documents: {\n maxCount: 30,\n maxSize: 1024 * 1024 * 50, // 50 MB\n supportedFilesRegex:\n /pdf|doc|docx|xls|xlsx|ppt|pptx|odt|ods|odg|odp|txt|rtf|csv|epub|md|tex|pages|numbers|key|xml|json|yaml|yml|ini|cfg|conf|log|html|htm|xhtml|djvu|mobi|azw|azw3|fb2|lit|ps|wpd|wps|dot|dotx|xlt|xltx|pot|potx|oft|one|onetoc2|opf|oxps|hwp/,\n },\n files: {\n maxCount: 10,\n maxSize: 1024 * 1024 * 5096, // 5 GB\n supportedFilesRegex: /.*/,\n },\n };\n\n // Merge with user configuration (if any)\n const restrictions = fileUpload?.restrictions\n ? deepmerge(defaultRestrictions, fileUpload.restrictions)\n : defaultRestrictions;\n\n /**\n * Specialized file uploader service for handling image uploads.\n */\n const imageUploadService = new FileUploadService(\n `${baseUploadDir}/images`,\n restrictions.images.maxSize,\n restrictions.images.supportedFilesRegex,\n restrictions.images.maxCount\n );\n\n /**\n * Specialized file uploader service for handling video uploads.\n */\n const videoUploadService = new FileUploadService(\n `${baseUploadDir}/videos`,\n restrictions.videos.maxSize,\n restrictions.videos.supportedFilesRegex,\n restrictions.videos.maxCount\n );\n\n /**\n * Specialized file uploader service for handling document uploads.\n */\n const documentUploadService = new FileUploadService(\n `${baseUploadDir}/documents`,\n restrictions.documents.maxSize,\n restrictions.documents.supportedFilesRegex,\n restrictions.documents.maxCount\n );\n\n /**\n * Generic file uploader service for handling all file uploads.\n */\n const fileUploadService = new FileUploadService(\n `${baseUploadDir}/files`,\n restrictions.files.maxSize,\n restrictions.files.supportedFilesRegex,\n restrictions.files.maxCount\n );\n\n return {\n imageUploadService,\n videoUploadService,\n documentUploadService,\n fileUploadService,\n };\n};\n"]}
@@ -77,4 +77,4 @@ export const processImage = async (req, filePath, options) => {
77
77
  throw error;
78
78
  }
79
79
  };
80
- //# sourceMappingURL=file-uploader.helpers.js.map
80
+ //# sourceMappingURL=file-upload.helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-upload.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/file-upload/utils/helpers/file-upload.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,QAAQ,MAAM,UAAU,CAAC;AAGhC,MAAM,UAAU,kBAAkB,CAAC,GAA0B;IAC3D,MAAM,EAAE,UAAU,EAAE,GAAG,cAAc,EAAE,CAAC;IAGxC,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,CAAC,WAAW,CAAC;QACzD,CAAC,CAAC,MAAM;QACR,CAAC,CAAC,OAAO,CAAC;IACZ,MAAM,OAAO,GAAG,GAAG,QAAQ,MAAM,GAAG,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;IACrD,MAAM,SAAS,GAAG,UAAU,EAAE,SAAS,IAAI,cAAc,CAAC;IAC1D,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;AAChC,CAAC;AAKD,MAAM,oBAAoB,GAAG,CAAC,QAAgB,EAAE,QAAgB,EAAE,EAAE;IAClE,MAAM,EAAE,UAAU,EAAE,GAAG,cAAc,EAAE,CAAC;IAExC,MAAM,aAAa,GAAG,UAAU,EAAE,aAAa,IAAI,UAAU,CAAC;IAC9D,IAAI,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAEnC,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,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CACF,CAAC;QACJ,CAAC;QAGD,IAAI,YAAY,KAAK,MAAM,EAAE,CAAC;YAC5B,WAAW,GAAG,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QAC7C,CAAC;aAAM,IAAI,YAAY,KAAK,MAAM,IAAI,YAAY,KAAK,KAAK,EAAE,CAAC;YAC7D,WAAW,GAAG,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QAC7C,CAAC;QAGD,MAAM,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAGnC,MAAM,SAAS,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QAG/C,MAAM,YAAY,GAAG,oBAAoB,CAAC,QAAQ,EAAE,GAAG,EAAE,MAAO,CAAC,QAAQ,CAAC,CAAC;QAE3E,OAAO,GAAG,OAAO,GAAG,SAAS,IAAI,YAAY,EAAE,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAEf,IAAI,CAAC;YACH,MAAM,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC;YACnC,MAAM,SAAS,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;QAEf,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport sharp from \"sharp\";\nimport { promisify } from \"util\";\nimport { getArkosConfig } from \"../../../../server\";\nimport mimetype from \"mimetype\";\nimport { ArkosRequest } from \"../../../../types\";\n\nexport function extractRequestInfo(req: Partial<ArkosRequest>) {\n const { fileUpload } = getArkosConfig();\n\n // Determine the base URL for file access\n const protocol = req.get?.(\"host\")?.includes?.(\"localhost\")\n ? \"http\"\n : \"https\";\n const baseURL = `${protocol}://${req.get?.(\"host\")}`;\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n return { baseURL, baseRoute };\n}\n\n/**\n * Generates the correct relative path regardless of upload directory location\n */\nconst generateRelativePath = (filePath: string, fileType: string) => {\n const { fileUpload } = getArkosConfig();\n\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n if (baseUploadDir.startsWith(\"..\")) {\n // For paths outside project directory\n return path.join(fileType, path.basename(filePath));\n } else {\n // For paths within project\n return filePath\n .replace(`${baseUploadDir}/`, \"\")\n .replace(process.cwd() + \"/\", \"\");\n }\n};\n\n/**\n * Handles basic file processing for non-image files\n */\nexport const processFile = async (\n req: Partial<ArkosRequest>,\n filePath: string\n): Promise<string> => {\n const { baseURL, baseRoute } = extractRequestInfo(req);\n\n const relativePath = generateRelativePath(filePath, req.params!.fileType);\n return `${baseURL}${baseRoute === \"/\" ? \"\" : baseRoute}/${relativePath}`;\n};\n\n/**\n * Processes image files using Sharp for resizing and format conversion\n */\nexport const processImage = async (\n req: Partial<ArkosRequest>,\n filePath: string,\n options: Record<string, any>\n): Promise<string | null> => {\n const { baseURL, baseRoute } = extractRequestInfo(req);\n\n const ext = path.extname(filePath).toLowerCase();\n const originalFormat = ext.replace(\".\", \"\");\n const outputFormat = options.format || originalFormat;\n\n if (!mimetype.lookup(ext)?.includes?.(\"image\")) {\n const relativePath = generateRelativePath(filePath, req.params!.fileType);\n return `${baseURL}${baseRoute}/${relativePath}`;\n }\n\n // Create a temp filename with original name + random string\n const tempName = `${path.basename(filePath, ext)}_${Date.now()}${ext}`;\n const tempPath = path.join(path.dirname(filePath), tempName);\n\n try {\n let transformer = sharp(filePath);\n const metadata = await transformer.metadata();\n\n // Apply resize transformations if requested\n if (options.resizeTo && metadata.width && metadata.height) {\n const targetSize = options.resizeTo;\n const scaleFactor =\n targetSize / Math.min(metadata.width, metadata.height);\n const newWidth = Math.round(metadata.width * scaleFactor);\n const newHeight = Math.round(metadata.height * scaleFactor);\n transformer = transformer.resize(newWidth, newHeight);\n } else if (options.width || options.height) {\n transformer = transformer.resize(\n options.width || null,\n options.height || null,\n {\n fit: \"inside\",\n }\n );\n }\n\n // Apply format transformations if requested\n if (outputFormat === \"webp\") {\n transformer = transformer.toFormat(\"webp\");\n } else if (outputFormat === \"jpeg\" || outputFormat === \"jpg\") {\n transformer = transformer.toFormat(\"jpeg\");\n }\n\n // Save to temp file first\n await transformer.toFile(tempPath);\n\n // Rename temp file to original filename\n await promisify(fs.rename)(tempPath, filePath);\n\n // Return the public URL for the file\n const relativePath = generateRelativePath(filePath, req?.params!.fileType);\n\n return `${baseURL}${baseRoute}/${relativePath}`;\n } catch (error) {\n // Clean up temp file if it exists\n try {\n await promisify(fs.stat)(tempPath);\n await promisify(fs.unlink)(tempPath);\n } catch (err) {\n // If temp file doesn't exist, no need to clean up\n }\n throw error;\n }\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints](https://www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
1
+ {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-upload\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints](https://www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file upload router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUpload?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
@@ -12,8 +12,10 @@ export function buildCommand(options = {}) {
12
12
  const envFiles = loadEnvironmentVariables();
13
13
  const moduleType = validateModuleType(options.module);
14
14
  try {
15
- console.info(`🛠️ Using env variables from ${envFiles?.join(", ")}...`);
16
- console.info(`🚀 Building an optimized production ready project with ${moduleType} format...\n`);
15
+ console.info(`Using env variables from ${envFiles
16
+ ?.join(", ")
17
+ .replaceAll(process.cwd(), "")}...\n`);
18
+ console.info(`Building an optimized production ready project.\n`);
17
19
  ensureBuildDir();
18
20
  if (fileExt === "ts") {
19
21
  buildTypeScriptProject(options, moduleType);
@@ -21,7 +23,7 @@ export function buildCommand(options = {}) {
21
23
  else {
22
24
  buildJavaScriptProject(options, moduleType);
23
25
  }
24
- console.info(`✅ Build complete! \n`);
26
+ console.info(`Build complete! \n`);
25
27
  console.info(`Next step:\n`);
26
28
  console.info(`Run the generated build with the start command.\n`);
27
29
  }
@@ -71,6 +73,7 @@ function buildTypeScriptProject(options, moduleType) {
71
73
  ...tsconfig,
72
74
  compilerOptions: {
73
75
  ...(tsconfig.compilerOptions || {}),
76
+ rootDir: ".",
74
77
  outDir: path.join(`./${BUILD_DIR}`),
75
78
  },
76
79
  };
@@ -121,7 +124,7 @@ function buildJavaScriptProject(options, moduleType) {
121
124
  }
122
125
  }
123
126
  function copyAllNonSourceFiles(moduleType, skipExtensions) {
124
- const targetDir = path.join(BUILD_DIR, moduleType);
127
+ const targetDir = path.join(BUILD_DIR);
125
128
  const sourceDir = "src";
126
129
  try {
127
130
  function copyDirRecursive(dir) {
@@ -157,7 +160,7 @@ function copyAllNonSourceFiles(moduleType, skipExtensions) {
157
160
  fs.copyFileSync(path.join(process.cwd(), file), path.join(targetDir, file));
158
161
  }
159
162
  }
160
- console.info(`📦 Copied all non-source files to ${targetDir}`);
163
+ console.info(`Copied all non-source files to ${targetDir}`);
161
164
  }
162
165
  catch (error) {
163
166
  console.warn("Warning: Error copying project files:", error);
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAG7D,MAAM,SAAS,GAAG,QAAQ,CAAC;AAC3B,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,KAAK,CAAU,CAAC;AAW7C,MAAM,UAAU,YAAY,CAAC,UAAwB,EAAE;IACrD,MAAM,OAAO,GAAG,oBAAoB,EAAE,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,YAAY,CAAC;IACpC,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG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U,CAAC,UAAU,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["// src/utils/cli/build.ts\nimport path from \"path\";\nimport fs from \"fs\";\nimport { execSync } from \"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\n\n// Constants\nconst BUILD_DIR = \".build\";\nconst MODULE_TYPES = [\"cjs\", \"esm\"] as const;\ntype ModuleType = (typeof MODULE_TYPES)[number];\n\ninterface BuildOptions {\n config?: string;\n module?: string;\n}\n\n/**\n * Main build function for the arkos CLI\n */\nexport function buildCommand(options: BuildOptions = {}) {\n const fileExt = getUserFileExtension();\n process.env.NODE_ENV = \"production\";\n process.env.NODE_ENV = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\n console.info(`🛠️ Using env variables from ${envFiles?.join(\", \")}...`);\n console.info(\n `🚀 Building an optimized production ready project with ${moduleType} format...\\n`\n );\n\n ensureBuildDir();\n\n // Detect project type\n\n if (fileExt === \"ts\") {\n buildTypeScriptProject(options, moduleType);\n } else {\n buildJavaScriptProject(options, moduleType);\n }\n\n console.info(`✅ Build complete! \\n`);\n console.info(`Next step:\\n`);\n console.info(`Run the generated build with the start command.\\n`);\n } catch (error) {\n console.info(\"\\n\");\n console.error(\"❌ Build failed:\", error);\n process.exit(1);\n }\n}\n\n/**\n * Validates and normalizes module type option\n */\nfunction validateModuleType(moduleType?: string): ModuleType {\n if (!moduleType) return \"cjs\";\n\n const normalizedType = moduleType.toLowerCase();\n\n // Map common terms to our module types\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") {\n return \"cjs\";\n } else if (\n [\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType)\n ) {\n return \"esm\";\n }\n\n // Default to CJS if unrecognized\n console.warn(\n `⚠️ Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`\n );\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) {\n fs.mkdirSync(BUILD_DIR, { recursive: true });\n }\n\n // Create module-specific subdirectories\n for (const moduleType of MODULE_TYPES) {\n const moduleDir = path.join(BUILD_DIR, moduleType);\n if (!fs.existsSync(moduleDir)) {\n fs.mkdirSync(moduleDir, { recursive: true });\n }\n }\n}\n\n/**\n * Build a TypeScript project\n */\nfunction buildTypeScriptProject(options: BuildOptions, moduleType: ModuleType) {\n // Read the user's tsconfig.json\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n\n try {\n if (fs.existsSync(tsconfigPath)) {\n const tsconfigContent = fs.readFileSync(tsconfigPath, \"utf8\");\n tsconfig = JSON.parse(tsconfigContent);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n // Continue with default config\n }\n\n // Create a custom tsconfig that outputs to our build directory with the correct module type\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n outDir: path.join(`./${BUILD_DIR}`),\n // module: moduleType === \"esm\" ? \"ESNext\" : \"CommonJS\",\n },\n };\n\n const tempTsconfigPath = path.join(\n process.cwd(),\n `tsconfig.arkos-build.json`\n );\n fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));\n\n try {\n // Run TypeScript compiler\n execSync(`npx tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n // Copy non-TypeScript files\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n\n // Clean up temp config\n cleanupTempConfig(tempTsconfigPath);\n } catch (error) {\n cleanupTempConfig(tempTsconfigPath);\n throw error;\n }\n}\n\n/**\n * Build a JavaScript project\n */\nfunction buildJavaScriptProject(options: BuildOptions, moduleType: ModuleType) {\n // Target directory\n const targetDir = path.join(BUILD_DIR);\n\n try {\n // Copy JavaScript files based on module type\n if (moduleType === \"esm\") {\n // Copy JS files for ESM (skip .cjs files as they are CommonJS)\n\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n\n // Note about CommonJS files\n console.info(\"Note: .cjs files are skipped in ESM build\");\n } else {\n // Copy all JS files for CommonJS\n\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.cjs\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n }\n\n // Copy all non-JS files\n copyAllNonSourceFiles(moduleType, [\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n ]);\n\n // Create appropriate package.json in the build directory\n createModulePackageJson(moduleType);\n } catch (error) {\n console.error(\"❌ Error building JavaScript project:\", error);\n throw error;\n }\n}\n\n/**\n * Copy all non-source code files to the build directory\n * This function will copy everything except the specified source file extensions\n */\nfunction copyAllNonSourceFiles(\n moduleType: ModuleType,\n skipExtensions: string[]\n) {\n const targetDir = path.join(BUILD_DIR, moduleType);\n const sourceDir = \"src\";\n\n try {\n // Recursive function to copy files\n function copyDirRecursive(dir: string) {\n if (!fs.existsSync(dir)) return;\n\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const sourcePath = path.join(dir, item);\n const targetPath = path.join(\n targetDir,\n dir.replace(sourceDir, \"\"),\n item\n );\n\n // Get file stats\n const stats = fs.statSync(sourcePath);\n\n if (stats.isDirectory()) {\n // Ensure target directory exists\n if (!fs.existsSync(targetPath)) {\n fs.mkdirSync(targetPath, { recursive: true });\n }\n // Recurse into subdirectory\n copyDirRecursive(sourcePath);\n } else if (stats.isFile()) {\n // Check if this is a file we should skip\n const ext = path.extname(item).toLowerCase();\n if (!skipExtensions.includes(ext)) {\n // Ensure the target directory exists\n const targetDir = path.dirname(targetPath);\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n // Copy the file\n fs.copyFileSync(sourcePath, targetPath);\n }\n }\n }\n }\n\n // Start copying from src directory\n copyDirRecursive(sourceDir);\n\n // Copy project root files if needed\n const rootFilesToCopy = [\"README.md\", \"LICENSE\"];\n\n for (const file of rootFilesToCopy) {\n if (fs.existsSync(path.join(process.cwd(), file))) {\n fs.copyFileSync(\n path.join(process.cwd(), file),\n path.join(targetDir, file)\n );\n }\n }\n\n console.info(`📦 Copied all non-source files to ${targetDir}`);\n } catch (error) {\n console.warn(\"Warning: Error copying project files:\", error);\n console.error(error);\n }\n}\n\n/**\n * Create appropriate package.json in the build directory\n */\nfunction createModulePackageJson(moduleType: ModuleType) {\n const packageJsonPath = path.join(process.cwd(), \"package.json\");\n\n if (!fs.existsSync(packageJsonPath)) {\n return;\n }\n\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n const buildPackageJson: any = {\n name: packageJson.name,\n version: packageJson.version,\n description: packageJson.description,\n main: \"index.js\",\n dependencies: packageJson.dependencies,\n };\n\n // Set appropriate type field for ESM\n if (moduleType === \"esm\") {\n buildPackageJson.type = \"module\";\n }\n\n const targetDir = path.join(BUILD_DIR, moduleType);\n fs.writeFileSync(\n path.join(targetDir, \"package.json\"),\n JSON.stringify(buildPackageJson, null, 2)\n );\n } catch (error) {\n console.warn(\n \"Warning: Failed to create module-specific package.json\",\n error\n );\n }\n}\n\n/**\n * Clean up temporary tsconfig\n */\nfunction cleanupTempConfig(configPath: string) {\n try {\n if (fs.existsSync(configPath)) fs.unlinkSync(configPath);\n } catch (error) {\n console.warn(\"Warning: Error cleaning up temporary config:\", error);\n }\n}\n"]}
1
+ {"version":3,"file":"build.js","sourceRoot":"","sources":["../../../../src/utils/cli/build.ts"],"names":[],"m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C;QAGF,IAAI,UAAU,KAAK,KAAK,EAAE,CAAC;YACzB,gBAAgB,CAAC,IAAI,GAAG,QAAQ,CAAC;QACnC,CAAC;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;QACnD,EAAE,CAAC,aAAa,CACd,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,EACpC,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC,CAC1C,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CACV,wDAAwD,EACxD,KAAK,CACN,CAAC;IACJ,CAAC;AACH,CAAC;AAKD,SAAS,iBAAiB,CAAC,UAAkB;IAC3C,IAAI,CAAC;QACH,IAAI,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC;YAAE,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["// src/utils/cli/build.ts\nimport path from \"path\";\nimport fs from \"fs\";\nimport { execSync } from \"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\n\n// Constants\nconst BUILD_DIR = \".build\";\nconst MODULE_TYPES = [\"cjs\", \"esm\"] as const;\ntype ModuleType = (typeof MODULE_TYPES)[number];\n\ninterface BuildOptions {\n config?: string;\n module?: string;\n}\n\n/**\n * Main build function for the arkos CLI\n */\nexport function buildCommand(options: BuildOptions = {}) {\n const fileExt = getUserFileExtension();\n process.env.NODE_ENV = \"production\";\n process.env.NODE_ENV = \"true\";\n\n const envFiles = loadEnvironmentVariables();\n const moduleType = validateModuleType(options.module);\n\n try {\n console.info(\n `Using env variables from ${envFiles\n ?.join(\", \")\n .replaceAll(process.cwd(), \"\")}...\\n`\n );\n console.info(`Building an optimized production ready project.\\n`);\n\n ensureBuildDir();\n\n // Detect project type\n\n if (fileExt === \"ts\") {\n buildTypeScriptProject(options, moduleType);\n } else {\n buildJavaScriptProject(options, moduleType);\n }\n\n console.info(`Build complete! \\n`);\n console.info(`Next step:\\n`);\n console.info(`Run the generated build with the start command.\\n`);\n } catch (error) {\n console.info(\"\\n\");\n console.error(\"❌ Build failed:\", error);\n process.exit(1);\n }\n}\n\n/**\n * Validates and normalizes module type option\n */\nfunction validateModuleType(moduleType?: string): ModuleType {\n if (!moduleType) return \"cjs\";\n\n const normalizedType = moduleType.toLowerCase();\n\n // Map common terms to our module types\n if (normalizedType === \"cjs\" || normalizedType === \"commonjs\") {\n return \"cjs\";\n } else if (\n [\"esm\", \"es\", \"es2020\", \"esnext\", \"module\"].includes(normalizedType)\n ) {\n return \"esm\";\n }\n\n // Default to CJS if unrecognized\n console.warn(\n `⚠️ Unrecognized module type \"${moduleType}\", defaulting to \"cjs\"`\n );\n return \"cjs\";\n}\n\n/**\n * Ensure the build directory exists\n */\nfunction ensureBuildDir() {\n if (!fs.existsSync(BUILD_DIR)) {\n fs.mkdirSync(BUILD_DIR, { recursive: true });\n }\n\n // Create module-specific subdirectories\n for (const moduleType of MODULE_TYPES) {\n const moduleDir = path.join(BUILD_DIR, moduleType);\n if (!fs.existsSync(moduleDir)) {\n fs.mkdirSync(moduleDir, { recursive: true });\n }\n }\n}\n\n/**\n * Build a TypeScript project\n */\nfunction buildTypeScriptProject(options: BuildOptions, moduleType: ModuleType) {\n // Read the user's tsconfig.json\n const tsconfigPath = path.join(\n process.cwd(),\n options.config || \"tsconfig.json\"\n );\n let tsconfig: any = {};\n\n try {\n if (fs.existsSync(tsconfigPath)) {\n const tsconfigContent = fs.readFileSync(tsconfigPath, \"utf8\");\n tsconfig = JSON.parse(tsconfigContent);\n }\n } catch (error) {\n console.error(\"❌ Error reading tsconfig.json:\", error);\n // Continue with default config\n }\n\n // Create a custom tsconfig that outputs to our build directory with the correct module type\n const tempTsconfig = {\n ...tsconfig,\n compilerOptions: {\n ...(tsconfig.compilerOptions || {}),\n rootDir: \".\",\n outDir: path.join(`./${BUILD_DIR}`),\n // module: moduleType === \"esm\" ? \"ESNext\" : \"CommonJS\",\n },\n };\n\n const tempTsconfigPath = path.join(\n process.cwd(),\n `tsconfig.arkos-build.json`\n );\n fs.writeFileSync(tempTsconfigPath, JSON.stringify(tempTsconfig, null, 2));\n\n try {\n // Run TypeScript compiler\n execSync(`npx tsc -p ${tempTsconfigPath}`, {\n stdio: \"inherit\",\n cwd: process.cwd(),\n });\n\n // Copy non-TypeScript files\n\n copyAllNonSourceFiles(moduleType, [\".ts\", \".tsx\"]);\n\n // Clean up temp config\n cleanupTempConfig(tempTsconfigPath);\n } catch (error) {\n cleanupTempConfig(tempTsconfigPath);\n throw error;\n }\n}\n\n/**\n * Build a JavaScript project\n */\nfunction buildJavaScriptProject(options: BuildOptions, moduleType: ModuleType) {\n // Target directory\n const targetDir = path.join(BUILD_DIR);\n\n try {\n // Copy JavaScript files based on module type\n if (moduleType === \"esm\") {\n // Copy JS files for ESM (skip .cjs files as they are CommonJS)\n\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n\n // Note about CommonJS files\n console.info(\"Note: .cjs files are skipped in ESM build\");\n } else {\n // Copy all JS files for CommonJS\n\n execSync(\n `npx copyfiles -u 0 \"src/**/*.js\" \"src/**/*.jsx\" \"src/**/*.cjs\" \"src/**/*.mjs\" ${targetDir}`,\n {\n stdio: \"inherit\",\n cwd: process.cwd(),\n }\n );\n }\n\n // Copy all non-JS files\n copyAllNonSourceFiles(moduleType, [\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n ]);\n\n // Create appropriate package.json in the build directory\n createModulePackageJson(moduleType);\n } catch (error) {\n console.error(\"❌ Error building JavaScript project:\", error);\n throw error;\n }\n}\n\n/**\n * Copy all non-source code files to the build directory\n * This function will copy everything except the specified source file extensions\n */\nfunction copyAllNonSourceFiles(\n moduleType: ModuleType,\n skipExtensions: string[]\n) {\n const targetDir = path.join(BUILD_DIR);\n const sourceDir = \"src\";\n\n try {\n // Recursive function to copy files\n function copyDirRecursive(dir: string) {\n if (!fs.existsSync(dir)) return;\n\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const sourcePath = path.join(dir, item);\n const targetPath = path.join(\n targetDir,\n dir.replace(sourceDir, \"\"),\n item\n );\n\n // Get file stats\n const stats = fs.statSync(sourcePath);\n\n if (stats.isDirectory()) {\n // Ensure target directory exists\n if (!fs.existsSync(targetPath)) {\n fs.mkdirSync(targetPath, { recursive: true });\n }\n // Recurse into subdirectory\n copyDirRecursive(sourcePath);\n } else if (stats.isFile()) {\n // Check if this is a file we should skip\n const ext = path.extname(item).toLowerCase();\n if (!skipExtensions.includes(ext)) {\n // Ensure the target directory exists\n const targetDir = path.dirname(targetPath);\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n // Copy the file\n fs.copyFileSync(sourcePath, targetPath);\n }\n }\n }\n }\n\n // Start copying from src directory\n copyDirRecursive(sourceDir);\n\n // Copy project root files if needed\n const rootFilesToCopy = [\"README.md\", \"LICENSE\"];\n\n for (const file of rootFilesToCopy) {\n if (fs.existsSync(path.join(process.cwd(), file))) {\n fs.copyFileSync(\n path.join(process.cwd(), file),\n path.join(targetDir, file)\n );\n }\n }\n\n console.info(`Copied all non-source files to ${targetDir}`);\n } catch (error) {\n console.warn(\"Warning: Error copying project files:\", error);\n console.error(error);\n }\n}\n\n/**\n * Create appropriate package.json in the build directory\n */\nfunction createModulePackageJson(moduleType: ModuleType) {\n const packageJsonPath = path.join(process.cwd(), \"package.json\");\n\n if (!fs.existsSync(packageJsonPath)) {\n return;\n }\n\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n const buildPackageJson: any = {\n name: packageJson.name,\n version: packageJson.version,\n description: packageJson.description,\n main: \"index.js\",\n dependencies: packageJson.dependencies,\n };\n\n // Set appropriate type field for ESM\n if (moduleType === \"esm\") {\n buildPackageJson.type = \"module\";\n }\n\n const targetDir = path.join(BUILD_DIR, moduleType);\n fs.writeFileSync(\n path.join(targetDir, \"package.json\"),\n JSON.stringify(buildPackageJson, null, 2)\n );\n } catch (error) {\n console.warn(\n \"Warning: Failed to create module-specific package.json\",\n error\n );\n }\n}\n\n/**\n * Clean up temporary tsconfig\n */\nfunction cleanupTempConfig(configPath: string) {\n try {\n if (fs.existsSync(configPath)) fs.unlinkSync(configPath);\n } catch (error) {\n console.warn(\"Warning: Error cleaning up temporary config:\", error);\n }\n}\n"]}