arkos 1.2.3-test → 1.2.4-beta
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.
- package/cli.js +0 -9
- package/dist/cjs/app.js +1 -1
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/exports/utils/index.js +26 -0
- package/dist/cjs/exports/utils/index.js.map +1 -1
- package/dist/cjs/modules/base/base.controller.js +12 -16
- package/dist/cjs/modules/base/base.controller.js.map +1 -1
- package/dist/cjs/modules/base/base.router.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +32 -18
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +1 -0
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js +16 -38
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +250 -0
- package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -0
- package/dist/cjs/modules/swagger/utils/helpers/get-system-json-schema-paths.js +66 -0
- package/dist/cjs/modules/swagger/utils/helpers/get-system-json-schema-paths.js.map +1 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js +41 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js.map +1 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js +22 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js.map +1 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js +29 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js.map +1 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js +439 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js.map +1 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js +162 -0
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js.map +1 -0
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js +90 -0
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -0
- package/dist/cjs/server.js +2 -2
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/types/arkos-config.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +2 -2
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/features/api.features.js +34 -22
- package/dist/cjs/utils/features/api.features.js.map +1 -1
- package/dist/cjs/utils/helpers/fs.helpers.js +2 -1
- package/dist/cjs/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +10 -2
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/cjs/utils/sheu.js +143 -0
- package/dist/cjs/utils/sheu.js.map +1 -0
- package/dist/es2020/app.js +1 -1
- package/dist/es2020/app.js.map +1 -1
- package/dist/es2020/exports/utils/index.js +2 -0
- package/dist/es2020/exports/utils/index.js.map +1 -1
- package/dist/es2020/modules/base/base.controller.js +12 -16
- package/dist/es2020/modules/base/base.controller.js.map +1 -1
- package/dist/es2020/modules/base/base.router.js.map +1 -1
- package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js +30 -18
- package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/es2020/modules/error-handler/error-handler.controller.js +1 -0
- package/dist/es2020/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/es2020/modules/swagger/swagger.router.js +16 -38
- package/dist/es2020/modules/swagger/swagger.router.js.map +1 -1
- package/dist/es2020/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +247 -0
- package/dist/es2020/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -0
- package/dist/es2020/modules/swagger/utils/helpers/get-system-json-schema-paths.js +63 -0
- package/dist/es2020/modules/swagger/utils/helpers/get-system-json-schema-paths.js.map +1 -0
- package/dist/es2020/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js +38 -0
- package/dist/es2020/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js.map +1 -0
- package/dist/es2020/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js +19 -0
- package/dist/es2020/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js.map +1 -0
- package/dist/es2020/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js +23 -0
- package/dist/es2020/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js.map +1 -0
- package/dist/es2020/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js +436 -0
- package/dist/es2020/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js.map +1 -0
- package/dist/es2020/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js +159 -0
- package/dist/es2020/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js.map +1 -0
- package/dist/es2020/modules/swagger/utils/helpers/swagger.router.helpers.js +83 -0
- package/dist/es2020/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -0
- package/dist/es2020/server.js +2 -2
- package/dist/es2020/server.js.map +1 -1
- package/dist/es2020/types/arkos-config.js.map +1 -1
- package/dist/es2020/utils/cli/dev.js +2 -2
- package/dist/es2020/utils/cli/dev.js.map +1 -1
- package/dist/es2020/utils/features/api.features.js +33 -22
- package/dist/es2020/utils/features/api.features.js.map +1 -1
- package/dist/es2020/utils/helpers/fs.helpers.js +2 -1
- package/dist/es2020/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/models.helpers.js +9 -1
- package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
- package/dist/es2020/utils/sheu.js +141 -0
- package/dist/es2020/utils/sheu.js.map +1 -0
- package/dist/types/exports/utils/index.d.ts +2 -0
- package/dist/types/modules/base/utils/helpers/base.router.helpers.d.ts +4 -1
- package/dist/types/modules/swagger/swagger.router.d.ts +1 -1
- package/dist/types/modules/swagger/utils/helpers/get-authentication-json-schema-paths.d.ts +2 -0
- package/dist/types/modules/swagger/utils/helpers/get-system-json-schema-paths.d.ts +2 -0
- package/dist/types/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.d.ts +1 -0
- package/dist/types/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.d.ts +1 -0
- package/dist/types/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.d.ts +1 -0
- package/dist/types/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.d.ts +2 -0
- package/dist/types/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.d.ts +2 -0
- package/dist/types/modules/swagger/utils/helpers/swagger.router.helpers.d.ts +7 -0
- package/dist/types/types/arkos-config.d.ts +7 -4
- package/dist/types/utils/features/api.features.d.ts +5 -4
- package/dist/types/utils/helpers/models.helpers.d.ts +10 -0
- package/dist/types/utils/sheu.d.ts +25 -0
- package/package.json +7 -3
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { plural } from "pluralize";
|
|
2
|
+
import { kebabCase, pascalCase } from "../../../../../../exports/utils";
|
|
3
|
+
import { getSchemaRef, kebabToHuman } from "../../swagger.router.helpers";
|
|
4
|
+
import { isParentEndpointAllowed } from "../../../../../base/utils/helpers/base.router.helpers";
|
|
5
|
+
export async function generatePrismaModelParentRoutePaths(paths, routeName, pascalModelName, humanReadableName, humanReadableNamePlural, routerConfig, mode) {
|
|
6
|
+
const parentModel = routerConfig.parent.model;
|
|
7
|
+
const parentRouteName = plural(kebabCase(parentModel));
|
|
8
|
+
const parentHumanName = kebabToHuman(kebabCase(parentModel));
|
|
9
|
+
if (isParentEndpointAllowed(routerConfig, "createOne")) {
|
|
10
|
+
paths[`/api/${parentRouteName}/{id}/${routeName}`] = {
|
|
11
|
+
post: {
|
|
12
|
+
tags: [humanReadableNamePlural],
|
|
13
|
+
summary: `Create ${humanReadableName} for ${parentHumanName}`,
|
|
14
|
+
description: `Creates a new ${humanReadableName} record associated with the specified ${parentHumanName}`,
|
|
15
|
+
operationId: `create${pascalModelName}For${pascalCase(parentModel)}`,
|
|
16
|
+
parameters: [
|
|
17
|
+
{
|
|
18
|
+
name: "id",
|
|
19
|
+
in: "path",
|
|
20
|
+
description: `Unique identifier of the ${parentHumanName}`,
|
|
21
|
+
required: true,
|
|
22
|
+
schema: {
|
|
23
|
+
type: "string",
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
],
|
|
27
|
+
requestBody: {
|
|
28
|
+
description: `${humanReadableName} data to create`,
|
|
29
|
+
required: true,
|
|
30
|
+
content: {
|
|
31
|
+
"application/json": {
|
|
32
|
+
schema: {
|
|
33
|
+
$ref: getSchemaRef(`Create${pascalModelName}`, mode),
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
responses: {
|
|
39
|
+
"201": {
|
|
40
|
+
description: `${humanReadableName} created successfully`,
|
|
41
|
+
content: {
|
|
42
|
+
"application/json": {
|
|
43
|
+
schema: {
|
|
44
|
+
$ref: getSchemaRef(`${pascalModelName}`, mode),
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
"400": {
|
|
50
|
+
description: "Invalid input data provided",
|
|
51
|
+
},
|
|
52
|
+
"401": {
|
|
53
|
+
description: "Authentication required",
|
|
54
|
+
},
|
|
55
|
+
"403": {
|
|
56
|
+
description: "Insufficient permissions",
|
|
57
|
+
},
|
|
58
|
+
"404": {
|
|
59
|
+
description: `${parentHumanName} not found`,
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
security: [{ BearerAuth: [] }],
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
if (isParentEndpointAllowed(routerConfig, "findMany")) {
|
|
67
|
+
if (!paths[`/api/${parentRouteName}/{id}/${routeName}`])
|
|
68
|
+
paths[`/api/${parentRouteName}/{id}/${routeName}`] = {};
|
|
69
|
+
paths[`/api/${parentRouteName}/{id}/${routeName}`].get = {
|
|
70
|
+
tags: [humanReadableNamePlural],
|
|
71
|
+
summary: `Get ${humanReadableNamePlural} for ${parentHumanName}`,
|
|
72
|
+
description: `Retrieves all ${humanReadableNamePlural} associated with the specified ${parentHumanName}`,
|
|
73
|
+
operationId: `get${plural(pascalModelName)}For${pascalCase(parentModel)}`,
|
|
74
|
+
parameters: [
|
|
75
|
+
{
|
|
76
|
+
name: "id",
|
|
77
|
+
in: "path",
|
|
78
|
+
description: `Unique identifier of the ${parentHumanName}`,
|
|
79
|
+
required: true,
|
|
80
|
+
schema: {
|
|
81
|
+
type: "string",
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
name: "filter",
|
|
86
|
+
in: "query",
|
|
87
|
+
description: "Additional filter criteria in JSON format",
|
|
88
|
+
schema: {
|
|
89
|
+
type: "string",
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
name: "sort",
|
|
94
|
+
in: "query",
|
|
95
|
+
description: "Sort field (prefix with '-' for descending order)",
|
|
96
|
+
schema: {
|
|
97
|
+
type: "string",
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
name: "page",
|
|
102
|
+
in: "query",
|
|
103
|
+
description: "Page number (starts from 1)",
|
|
104
|
+
schema: {
|
|
105
|
+
type: "integer",
|
|
106
|
+
minimum: 1,
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
name: "limit",
|
|
111
|
+
in: "query",
|
|
112
|
+
description: "Number of items per page",
|
|
113
|
+
schema: {
|
|
114
|
+
type: "integer",
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
responses: {
|
|
119
|
+
"200": {
|
|
120
|
+
description: `List of ${humanReadableNamePlural} retrieved successfully`,
|
|
121
|
+
content: {
|
|
122
|
+
"application/json": {
|
|
123
|
+
schema: {
|
|
124
|
+
type: "object",
|
|
125
|
+
properties: {
|
|
126
|
+
total: {
|
|
127
|
+
type: "integer",
|
|
128
|
+
description: "Total number of records",
|
|
129
|
+
},
|
|
130
|
+
results: {
|
|
131
|
+
type: "integer",
|
|
132
|
+
description: "Number of records in current page",
|
|
133
|
+
},
|
|
134
|
+
data: {
|
|
135
|
+
type: "array",
|
|
136
|
+
items: {
|
|
137
|
+
$ref: getSchemaRef(`${pascalModelName}`, mode),
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
},
|
|
145
|
+
"401": {
|
|
146
|
+
description: "Authentication required",
|
|
147
|
+
},
|
|
148
|
+
"403": {
|
|
149
|
+
description: "Insufficient permissions",
|
|
150
|
+
},
|
|
151
|
+
"404": {
|
|
152
|
+
description: `${parentHumanName} not found`,
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
security: [{ BearerAuth: [] }],
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
//# sourceMappingURL=generate-prisma-model-parent-routes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-prisma-model-parent-routes.js","sourceRoot":"","sources":["../../../../../../../../src/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACn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C;gBACD,KAAK,EAAE;oBACL,WAAW,EAAE,0BAA0B;iBACxC;gBACD,KAAK,EAAE;oBACL,WAAW,EAAE,GAAG,eAAe,YAAY;iBAC5C;aACF;YACD,QAAQ,EAAE,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;SAC/B,CAAC;IACJ,CAAC;AAGH,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { plural } from \"pluralize\";\nimport { kebabCase, pascalCase } from \"../../../../../../exports/utils\";\nimport { getSchemaRef, kebabToHuman } from \"../../swagger.router.helpers\";\nimport { isParentEndpointAllowed } from \"../../../../../base/utils/helpers/base.router.helpers\";\n\nexport async function generatePrismaModelParentRoutePaths(\n paths: OpenAPIV3.PathsObject,\n routeName: string,\n pascalModelName: string,\n humanReadableName: string,\n humanReadableNamePlural: string,\n routerConfig: any,\n mode: string\n) {\n const parentModel = routerConfig.parent.model;\n const parentRouteName = plural(kebabCase(parentModel));\n const parentHumanName = kebabToHuman(kebabCase(parentModel));\n // const foreignKeyField =\n // routerConfig.parent.foreignKeyField || `${kebabCase(parentModel)}Id`;\n\n // Create One (Parent)\n if (isParentEndpointAllowed(routerConfig, \"createOne\")) {\n paths[`/api/${parentRouteName}/{id}/${routeName}`] = {\n post: {\n tags: [humanReadableNamePlural],\n summary: `Create ${humanReadableName} for ${parentHumanName}`,\n description: `Creates a new ${humanReadableName} record associated with the specified ${parentHumanName}`,\n operationId: `create${pascalModelName}For${pascalCase(parentModel)}`,\n parameters: [\n {\n name: \"id\",\n in: \"path\",\n description: `Unique identifier of the ${parentHumanName}`,\n required: true,\n schema: {\n type: \"string\",\n },\n },\n ],\n requestBody: {\n description: `${humanReadableName} data to create`,\n required: true,\n content: {\n \"application/json\": {\n schema: {\n $ref: getSchemaRef(`Create${pascalModelName}`, mode),\n },\n },\n },\n },\n responses: {\n \"201\": {\n description: `${humanReadableName} created successfully`,\n content: {\n \"application/json\": {\n schema: {\n $ref: getSchemaRef(`${pascalModelName}`, mode),\n },\n },\n },\n },\n \"400\": {\n description: \"Invalid input data provided\",\n },\n \"401\": {\n description: \"Authentication required\",\n },\n \"403\": {\n description: \"Insufficient permissions\",\n },\n \"404\": {\n description: `${parentHumanName} not found`,\n },\n },\n security: [{ BearerAuth: [] }],\n },\n };\n }\n\n // Find Many (Parent)\n if (isParentEndpointAllowed(routerConfig, \"findMany\")) {\n if (!paths[`/api/${parentRouteName}/{id}/${routeName}`])\n paths[`/api/${parentRouteName}/{id}/${routeName}`] = {};\n paths[`/api/${parentRouteName}/{id}/${routeName}`]!.get = {\n tags: [humanReadableNamePlural],\n summary: `Get ${humanReadableNamePlural} for ${parentHumanName}`,\n description: `Retrieves all ${humanReadableNamePlural} associated with the specified ${parentHumanName}`,\n operationId: `get${plural(pascalModelName)}For${pascalCase(parentModel)}`,\n parameters: [\n {\n name: \"id\",\n in: \"path\",\n description: `Unique identifier of the ${parentHumanName}`,\n required: true,\n schema: {\n type: \"string\",\n },\n },\n {\n name: \"filter\",\n in: \"query\",\n description: \"Additional filter criteria in JSON format\",\n schema: {\n type: \"string\",\n },\n },\n {\n name: \"sort\",\n in: \"query\",\n description: \"Sort field (prefix with '-' for descending order)\",\n schema: {\n type: \"string\",\n },\n },\n {\n name: \"page\",\n in: \"query\",\n description: \"Page number (starts from 1)\",\n schema: {\n type: \"integer\",\n minimum: 1,\n },\n },\n {\n name: \"limit\",\n in: \"query\",\n description: \"Number of items per page\",\n schema: {\n type: \"integer\",\n },\n },\n ],\n responses: {\n \"200\": {\n description: `List of ${humanReadableNamePlural} retrieved successfully`,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n total: {\n type: \"integer\",\n description: \"Total number of records\",\n },\n results: {\n type: \"integer\",\n description: \"Number of records in current page\",\n },\n data: {\n type: \"array\",\n items: {\n $ref: getSchemaRef(`${pascalModelName}`, mode),\n },\n },\n },\n },\n },\n },\n },\n \"401\": {\n description: \"Authentication required\",\n },\n \"403\": {\n description: \"Insufficient permissions\",\n },\n \"404\": {\n description: `${parentHumanName} not found`,\n },\n },\n security: [{ BearerAuth: [] }],\n };\n }\n\n // Add other parent endpoints (findOne, updateOne, deleteOne, etc.) following the same pattern...\n}\n"]}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { getModels, importPrismaModelModules, } from "../../../../utils/helpers/models.helpers";
|
|
2
|
+
import { kebabCase, pascalCase } from "../../../../exports/utils";
|
|
3
|
+
import { plural } from "pluralize";
|
|
4
|
+
import { getSystemJsonSchemaPaths } from "./get-system-json-schema-paths";
|
|
5
|
+
import { getAuthenticationJsonSchemaPaths } from "./get-authentication-json-schema-paths";
|
|
6
|
+
import { generateZodJsonSchemas } from "./json-schema-generators/generate-zod-json-schema";
|
|
7
|
+
import { generateClassValidatorJsonSchemas } from "./json-schema-generators/generate-class-validator-json-schemas";
|
|
8
|
+
import { generatePrismaJsonSchemas } from "./json-schema-generators/generate-prisma-json-schemas";
|
|
9
|
+
import { generatePrismaModelMainRoutesPaths } from "./json-schema-generators/prisma-models/generate-prisma-model-main-routes";
|
|
10
|
+
import { generatePrismaModelParentRoutePaths } from "./json-schema-generators/prisma-models/generate-prisma-model-parent-routes";
|
|
11
|
+
export async function getOpenAPIJsonSchemasByConfigMode(swaggerConfig) {
|
|
12
|
+
switch (swaggerConfig.mode) {
|
|
13
|
+
case "prisma":
|
|
14
|
+
return await generatePrismaJsonSchemas();
|
|
15
|
+
case "class-validator":
|
|
16
|
+
return await generateClassValidatorJsonSchemas();
|
|
17
|
+
case "zod":
|
|
18
|
+
return await generateZodJsonSchemas();
|
|
19
|
+
default:
|
|
20
|
+
throw Error("Unknown mode for auto documentation, supported values are prisma, class-validator, zod or json-schemas");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function getCorrectJsonSchemaName(type, modelName, suffix) {
|
|
24
|
+
const pascalModelName = pascalCase(modelName);
|
|
25
|
+
const map = {
|
|
26
|
+
model: pascalModelName,
|
|
27
|
+
create: `Create${pascalModelName}`,
|
|
28
|
+
createMany: `CreateMany${pascalModelName}`,
|
|
29
|
+
findOne: `FindOne${pascalModelName}`,
|
|
30
|
+
findMany: `FindMany${pascalModelName}`,
|
|
31
|
+
update: `Update${pascalModelName}`,
|
|
32
|
+
updateMany: `UpdateMany${pascalModelName}`,
|
|
33
|
+
query: `Query${pascalModelName}`,
|
|
34
|
+
login: "Login",
|
|
35
|
+
signup: "Signup",
|
|
36
|
+
updateMe: "UpdateMe",
|
|
37
|
+
updatePassword: "UpdatePassword",
|
|
38
|
+
};
|
|
39
|
+
const baseName = map[type] ?? pascalCase(type);
|
|
40
|
+
return `${baseName}${suffix}`;
|
|
41
|
+
}
|
|
42
|
+
export function kebabToHuman(kebabStr) {
|
|
43
|
+
return kebabStr
|
|
44
|
+
.split("-")
|
|
45
|
+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
46
|
+
.join(" ");
|
|
47
|
+
}
|
|
48
|
+
export function getSchemaRef(schemaName, mode) {
|
|
49
|
+
switch (mode) {
|
|
50
|
+
case "prisma":
|
|
51
|
+
case "zod":
|
|
52
|
+
return `#/components/schemas/${schemaName}Schema`;
|
|
53
|
+
case "class-validator":
|
|
54
|
+
return `#/components/schemas/${schemaName}Dto`;
|
|
55
|
+
default:
|
|
56
|
+
return `#/components/schemas/${schemaName}`;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export async function generatePathsForModels(swaggerConfig) {
|
|
60
|
+
if (!swaggerConfig)
|
|
61
|
+
return {};
|
|
62
|
+
let paths = {};
|
|
63
|
+
const models = getModels();
|
|
64
|
+
const mode = swaggerConfig.mode;
|
|
65
|
+
for (const model of models) {
|
|
66
|
+
const modelName = kebabCase(model);
|
|
67
|
+
const routeName = plural(modelName);
|
|
68
|
+
const pascalModelName = pascalCase(model);
|
|
69
|
+
const humanReadableName = kebabToHuman(modelName);
|
|
70
|
+
const humanReadableNamePlural = plural(humanReadableName);
|
|
71
|
+
const modelModules = await importPrismaModelModules(model);
|
|
72
|
+
const routerConfig = modelModules.router?.config;
|
|
73
|
+
if (routerConfig?.disable === true)
|
|
74
|
+
continue;
|
|
75
|
+
await generatePrismaModelMainRoutesPaths(paths, routeName, pascalModelName, humanReadableName, humanReadableNamePlural, routerConfig, mode);
|
|
76
|
+
if (routerConfig?.parent)
|
|
77
|
+
await generatePrismaModelParentRoutePaths(paths, routeName, pascalModelName, humanReadableName, humanReadableNamePlural, routerConfig, mode);
|
|
78
|
+
}
|
|
79
|
+
paths = { ...paths, ...getSystemJsonSchemaPaths() };
|
|
80
|
+
paths = { ...paths, ...getAuthenticationJsonSchemaPaths() };
|
|
81
|
+
return paths;
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=swagger.router.helpers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"swagger.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/swagger.router.helpers.ts"],"names":[],"mappings":"AACA,OAAO,EACL,SAAS,EACT,wBAAwB,GACzB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAElE,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,gCAAgC,EAAE,MAAM,wCAAwC,CAAC;AAC1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,mDAAmD,CAAC;AAC3F,OAAO,EAAE,iCAAiC,EAAE,MAAM,gEAAgE,CAAC;AACnH,OAAO,EAAE,yBAAyB,EAAE,MAAM,uDAAuD,CAAC;AAClG,OAAO,EAAE,kCAAkC,EAAE,MAAM,0EAA0E,CAAC;AAC9H,OAAO,EAAE,mCAAmC,EAAE,MAAM,4EAA4E,CAAC;AAEjI,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,aAAqC;IAErC,QAAQ,aAAc,CAAC,IAAI,EAAE,CAAC;Q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B,EACvB,YAAY,EACZ,IAAI,CACL,CAAC;IACN,CAAC;IAGD,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,GAAG,wBAAwB,EAAE,EAAE,CAAC;IAGpD,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,GAAG,gCAAgC,EAAE,EAAE,CAAC;IAE5D,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { ArkosConfig } from \"../../../../exports\";\nimport {\n getModels,\n importPrismaModelModules,\n} from \"../../../../utils/helpers/models.helpers\";\nimport { kebabCase, pascalCase } from \"../../../../exports/utils\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { plural } from \"pluralize\";\nimport { getSystemJsonSchemaPaths } from \"./get-system-json-schema-paths\";\nimport { getAuthenticationJsonSchemaPaths } from \"./get-authentication-json-schema-paths\";\nimport { generateZodJsonSchemas } from \"./json-schema-generators/generate-zod-json-schema\";\nimport { generateClassValidatorJsonSchemas } from \"./json-schema-generators/generate-class-validator-json-schemas\";\nimport { generatePrismaJsonSchemas } from \"./json-schema-generators/generate-prisma-json-schemas\";\nimport { generatePrismaModelMainRoutesPaths } from \"./json-schema-generators/prisma-models/generate-prisma-model-main-routes\";\nimport { generatePrismaModelParentRoutePaths } from \"./json-schema-generators/prisma-models/generate-prisma-model-parent-routes\";\n\nexport async function getOpenAPIJsonSchemasByConfigMode(\n swaggerConfig: ArkosConfig[\"swagger\"]\n) {\n switch (swaggerConfig!.mode) {\n case \"prisma\":\n return await generatePrismaJsonSchemas();\n case \"class-validator\":\n return await generateClassValidatorJsonSchemas();\n case \"zod\":\n return await generateZodJsonSchemas();\n default:\n throw Error(\n \"Unknown mode for auto documentation, supported values are prisma, class-validator, zod or json-schemas\"\n );\n }\n}\n\nexport function getCorrectJsonSchemaName(\n type: string,\n modelName: string,\n suffix: \"Dto\" | \"Schema\"\n): string {\n const pascalModelName = pascalCase(modelName);\n\n const map: Record<string, string> = {\n model: pascalModelName,\n create: `Create${pascalModelName}`,\n createMany: `CreateMany${pascalModelName}`,\n findOne: `FindOne${pascalModelName}`,\n findMany: `FindMany${pascalModelName}`,\n update: `Update${pascalModelName}`,\n updateMany: `UpdateMany${pascalModelName}`,\n query: `Query${pascalModelName}`,\n login: \"Login\",\n signup: \"Signup\",\n updateMe: \"UpdateMe\",\n updatePassword: \"UpdatePassword\",\n };\n\n const baseName = map[type] ?? pascalCase(type);\n return `${baseName}${suffix}`;\n}\n\nexport function kebabToHuman(kebabStr: string): string {\n return kebabStr\n .split(\"-\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nexport function getSchemaRef(schemaName: string, mode: string): string {\n switch (mode) {\n case \"prisma\":\n case \"zod\":\n return `#/components/schemas/${schemaName}Schema`;\n case \"class-validator\":\n return `#/components/schemas/${schemaName}Dto`;\n default:\n return `#/components/schemas/${schemaName}`;\n }\n}\n\nexport async function generatePathsForModels(\n swaggerConfig: ArkosConfig[\"swagger\"]\n): Promise<OpenAPIV3.PathsObject> {\n if (!swaggerConfig) return {};\n\n let paths: OpenAPIV3.PathsObject = {};\n const models = getModels();\n const mode = swaggerConfig!.mode;\n\n for (const model of models) {\n const modelName = kebabCase(model);\n const routeName = plural(modelName);\n const pascalModelName = pascalCase(model);\n const humanReadableName = kebabToHuman(modelName);\n const humanReadableNamePlural = plural(humanReadableName);\n\n // Import model modules to get router config\n const modelModules = await importPrismaModelModules(model);\n const routerConfig = modelModules.router?.config;\n\n // Skip if router is completely disabled\n if (routerConfig?.disable === true) continue;\n\n // Generate main routes\n await generatePrismaModelMainRoutesPaths(\n paths,\n routeName,\n pascalModelName,\n humanReadableName,\n humanReadableNamePlural,\n routerConfig,\n mode\n );\n\n // Generate parent routes if configured\n if (routerConfig?.parent)\n await generatePrismaModelParentRoutePaths(\n paths,\n routeName,\n pascalModelName,\n humanReadableName,\n humanReadableNamePlural,\n routerConfig,\n mode\n );\n }\n\n // Add system routes\n paths = { ...paths, ...getSystemJsonSchemaPaths() };\n\n // Add authentication routes\n paths = { ...paths, ...getAuthenticationJsonSchemaPaths() };\n\n return paths;\n}\n"]}
|
package/dist/es2020/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";import{bootstrap as
|
|
1
|
+
"use strict";import{bootstrap as p}from"./app";import i from"./utils/helpers/deepmerge.helper";import c from"http";import s from"./utils/sheu";process.on("uncaughtException",o=>{o.message.includes("EPIPE")||(console.error(`
|
|
2
2
|
UNCAUGHT EXCEPTION! SHUTTING DOWN...
|
|
3
|
-
`),console.error(
|
|
3
|
+
`),console.error(o.name,o.message),console.error(o),process.exit(1))});let r,t,e={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:Number(process.env.CLI_PORT)||Number(process.env.PORT)||8e3,host:process.env.CLI_HOST||process.env.HOST||"localhost",fileUpload:{baseUploadDir:"uploads",baseRoute:"/api/uploads"},available:!1};async function l(o={}){e.available=!0,e=i(e,o);const n=process.env.CLI_PORT||e.port||process.env.PORT||"port"in e?e.port:8e3;t=await p(e);const a=new Date().toTimeString().split(" ")[0];return n?(r=c.createServer(t),e?.configureServer&&await e.configureServer(r),r.listen(Number(n),e.host,()=>{s.ready(`${s.gray(a)} server waiting on http://${e.host||"localhost"}:${n}`)})):s.warn(`${s.gray(a)} port set to undefined, hence no internal http server was setup.`),t}process.on("unhandledRejection",o=>{console.error("UNHANDLED REJECTION! SHUTTING DOWN..."),console.error(o.name,o.message),console.error(o),r?.close(()=>{process.exit(1)})});export function terminateApplicationRunningProcessAndServer(){r?.close(()=>{process.exit(1)})}export function getArkosConfig(){return e}export function getExpressApp(){return t}export{r as server,l as initApp};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,IAAI,MAAM,MAAM,CA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AK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAOH,MAAM,UAAU,2CAA2C;IACzD,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAOD,MAAM,UAAU,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\nimport sheu from \"./utils/sheu\";\n\nprocess.on(\"uncaughtException\", (err) => {\n if (err.message.includes(\"EPIPE\")) return;\n\n console.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nlet _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n _arkosConfig.available = true;\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port =\n process.env.CLI_PORT ||\n _arkosConfig.port ||\n process.env.PORT ||\n \"port\" in _arkosConfig\n ? _arkosConfig.port\n : 8000;\n\n _app = await bootstrap(_arkosConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (port) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(Number(port), _arkosConfig.host!, () => {\n sheu.ready(\n `${sheu.gray(time)} server waiting on http://${_arkosConfig.host || \"localhost\"}:${port}`\n );\n });\n } else {\n sheu.warn(\n `${sheu.gray(time)} port set to undefined, hence no internal http server was setup.`\n );\n }\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\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 /**\n * Defines allowed origins to acess the API.\n */\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 * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * })\n * ```\n *\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod`\": Uses OpenAPI-compliant schemas directly\n * - \"json-schema\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\" | \"json-schema\";\n /**\n *\n */\n options: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Local server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description: string;\n }[];\n\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Custom Swagger UI options.\n *\n * See: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md\n */\n swaggerUiOptions?: Record<string, any>;\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\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\";\nimport { OpenAPIV3 } from \"openapi-types\";\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 /**\n * Defines allowed origins to acess the API.\n */\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 * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n *\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Custom Swagger UI options.\n *\n * See: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md\n */\n swaggerUiOptions?: Record<string, any>;\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n };\n};\n"]}
|
|
@@ -6,6 +6,7 @@ import { loadEnvironmentVariables } from "../dotenv.helpers";
|
|
|
6
6
|
import { importModule } from "../helpers/global.helpers";
|
|
7
7
|
import fs from "fs";
|
|
8
8
|
import path from "path";
|
|
9
|
+
import sheu from "../sheu";
|
|
9
10
|
let child = null;
|
|
10
11
|
let envFiles;
|
|
11
12
|
export async function devCommand(options = {}) {
|
|
@@ -101,7 +102,7 @@ export async function devCommand(options = {}) {
|
|
|
101
102
|
clearTimeout(restartTimeout);
|
|
102
103
|
const now = new Date();
|
|
103
104
|
const time = now.toTimeString().split(" ")[0];
|
|
104
|
-
|
|
105
|
+
sheu.info(`\x1b[90m${time}\x1b[0m Restarting: ${reason.toLowerCase()}`);
|
|
105
106
|
isRestarting = true;
|
|
106
107
|
if (child) {
|
|
107
108
|
child.kill();
|
|
@@ -204,7 +205,6 @@ export async function devCommand(options = {}) {
|
|
|
204
205
|
};
|
|
205
206
|
waitForConfig();
|
|
206
207
|
const cleanup = () => {
|
|
207
|
-
console.info("\nShutting down development server...");
|
|
208
208
|
if (restartTimeout)
|
|
209
209
|
clearTimeout(restartTimeout);
|
|
210
210
|
if (envWatcher)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev.js","sourceRoot":"","sources":["../../../../src/utils/cli/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAgB,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAOxB,IAAI,KAAK,GAAwB,IAAI,CAAC;AACtC,IAAI,QAA8B,CAAC;AAKnC,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,UAAsB,EAAE;IACvD,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,aAAa,CAAC;IACrC,QAAQ,GAAG,wBAAwB,EAAE,CAAC;IACtC,KAAK,GAAG,IAAI,CAAC;IACb,IAAI,cAAc,GAA0B,IAAI,CAAC;IAEjD,IAAI,CAAC;QACH,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;QAC/B,IAAI,YAAY,GAAG,KAAK,CAAC;QAEzB,MAAM,OAAO,GAAG,oBAAoB,EAAE,CAAC;QAGvC,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,WAAW,OAAO,EAAE,CAAC,CAAC;QAErE,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAC/B,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,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import { spawn, ChildProcess } from \"child_process\";\nimport { watch } from \"chokidar\";\nimport { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { getVersion } from \"./utils/cli.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { importModule } from \"../helpers/global.helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\n\ninterface DevOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Dev server command for the arkos CLI\n */\nexport async function devCommand(options: DevOptions = {}) {\n process.env.NODE_ENV = \"development\";\n envFiles = loadEnvironmentVariables();\n child = null;\n let restartTimeout: NodeJS.Timeout | null = null;\n\n try {\n const { port, host } = options;\n let isRestarting = false;\n // Detect if project uses TypeScript or JavaScript\n const fileExt = getUserFileExtension();\n\n // Find the application entry point\n const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);\n\n if (!fs.existsSync(entryPoint)) {\n console.error(\"Could not find application entry point.\");\n process.exit(1);\n }\n\n // Set environment variables\n const getEnv = () =>\n ({\n NODE_ENV: \"development\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n }) as { [x: string]: string };\n\n // Function to start the child process\n const startServer = () => {\n if (child) {\n child.kill();\n child = null;\n }\n\n const env = getEnv();\n\n if (fileExt === \"ts\") {\n // Enhanced ts-node-dev configuration\n child = spawn(\n \"npx\",\n [\n \"ts-node-dev\",\n \"--respawn\",\n \"--notify=false\", // Disable desktop notifications\n \"--ignore-watch\",\n \"node_modules\",\n \"--ignore-watch\",\n \"dist\",\n \"--ignore-watch\",\n \"build\",\n \"--ignore-watch\",\n \".dist\",\n \"--ignore-watch\",\n \".build\",\n \"--watch\",\n \"src\", // Explicitly watch src directory\n entryPoint,\n ],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n } else {\n // Enhanced nodemon configuration\n child = spawn(\n \"npx\",\n [\n \"nodemon\",\n \"--watch\",\n \"src\",\n \"--ext\",\n \"js,json\",\n \"--ignore\",\n \"node_modules/\",\n \"--ignore\",\n \"dist/\",\n \"--ignore\",\n \"build/\",\n \"--ignore\",\n \".dist/\",\n \"--ignore\",\n \".build/\",\n \"--delay\",\n \"1000ms\",\n entryPoint,\n ],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n }\n\n if (child) {\n child.on(\"error\", (error) => {\n console.error(\"Failed to start server:\", error);\n });\n\n child.on(\"exit\", (code, signal) => {\n if (!isRestarting && signal !== \"SIGTERM\" && signal !== \"SIGINT\") {\n console.info(`Server exited with code ${code}, restarting...`);\n startServer();\n }\n });\n }\n };\n\n // Function to handle server restart with debouncing\n const scheduleRestart = (reason: string) => {\n if (restartTimeout) clearTimeout(restartTimeout);\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n console.info(\n `[\\x1b[36mINFO\\x1b[0m] \\x1b[90m${time}\\x1b[0m Restarting: ${reason.toLowerCase()}`\n );\n\n isRestarting = true;\n if (child) {\n child.kill();\n child = null;\n }\n restartTimeout = setTimeout(() => {\n startServer();\n restartTimeout = null;\n }, 1000);\n };\n\n // Setup environment file watching\n const setupEnvWatcher = () => {\n const envWatcher = watch(\n fullCleanCwd(envFiles?.join(\",\") || \"\")\n .replaceAll(\"/\", \"\")\n .split(\",\") || [],\n {\n ignoreInitial: true,\n persistent: true,\n }\n );\n\n envWatcher.on(\"all\", (event, filePath) => {\n try {\n envFiles = loadEnvironmentVariables();\n\n // Restart server to pick up new env vars\n scheduleRestart(\"Environments files changed\");\n } catch (error) {\n console.error(`Error reloading ${filePath}:`, error);\n }\n });\n\n return envWatcher;\n };\n\n // Setup additional file watching for better new file detection\n const setupAdditionalWatcher = () => {\n const additionalWatcher = watch(\n [\n \"src\",\n \"package.json\",\n \"tsconfig.json\",\n \"arkos.config.ts\",\n \"arkos.config.js\",\n ],\n {\n ignoreInitial: true,\n ignored: [\n /node_modules/,\n /\\.git/,\n /\\.dist/,\n /\\.build/,\n /dist/,\n /build/,\n /\\.env.*/,\n ],\n }\n );\n\n additionalWatcher.on(\"add\", (filePath) => {\n scheduleRestart(`${fullCleanCwd(filePath)} has been created`);\n });\n\n additionalWatcher.on(\"unlink\", (filePath) => {\n scheduleRestart(`${fullCleanCwd(filePath)} has been deleted`);\n });\n\n return additionalWatcher;\n };\n\n // Start the server\n startServer();\n\n // Setup watchers if enabled\n const envWatcher = setupEnvWatcher();\n const additionalWatcher = setupAdditionalWatcher();\n\n const checkConfig = async () => {\n try {\n // Import the config getter\n const { getArkosConfig } = await importModule(\"../../server\");\n const config = getArkosConfig();\n if (config && config.available) {\n // Config is ready, display the info with actual values\n const env = getEnv();\n console.info(\"\\n\");\n console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n console.info(\n ` - Local: http://${\n env.CLI_HOST || config.host || env.HOST || \"localhost\"\n }:${env.CLI_PORT || config.port || env.PORT || \"8000\"}`\n );\n console.info(\n ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n .replaceAll(`${process.cwd()}/`, \"\")\n .replaceAll(\"/\", \"\")}`\n );\n console.info(\"\\n\");\n return true;\n }\n return false;\n } catch (error) {\n return false;\n }\n };\n\n // Try to get config periodically\n const waitForConfig = async () => {\n let attempts = 0;\n const maxAttempts = 15;\n while (attempts < maxAttempts) {\n const ready = await checkConfig();\n if (ready) break;\n await new Promise((resolve) => setTimeout(resolve, 300));\n attempts++;\n }\n\n // Fall back to defaults if config never became available\n if (attempts >= maxAttempts) {\n const env = getEnv();\n console.info(\"\\n\");\n console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n console.info(\n ` - Local: http://${\n env.CLI_HOST || env.HOST || \"localhost\"\n }:${env.CLI_PORT || env.PORT || \"8000\"}`\n );\n console.info(\n ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n .replaceAll(`${process.cwd()}/`, \"\")\n .replaceAll(\"/\", \"\")}`\n );\n console.info(\"\\n\");\n }\n };\n\n waitForConfig();\n\n // Enhanced cleanup function\n const cleanup = () => {\n console.info(\"\\nShutting down development server...\");\n\n if (restartTimeout) clearTimeout(restartTimeout);\n\n if (envWatcher) envWatcher.close();\n\n if (additionalWatcher) additionalWatcher.close();\n\n if (child) {\n child.kill(\"SIGTERM\");\n\n // Force kill after 5 seconds if still running\n setTimeout(() => {\n if (child && !child.killed) {\n child.kill(\"SIGKILL\");\n }\n }, 5000);\n }\n\n process.exit(0);\n };\n\n // Handle process exit\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Handle uncaught exceptions\n process.on(\"uncaughtException\", (error) => {\n console.error(\"Uncaught Exception:\", error);\n cleanup();\n });\n } catch (error) {\n console.error(\"Development server failed to start:\", error);\n\n if (child) {\n (child as ChildProcess)?.kill?.();\n child = null;\n }\n\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the development server child process\n */\nexport function killDevelopmentServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"dev.js","sourceRoot":"","sources":["../../../../src/utils/cli/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAgB,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,SAAS,CAAC;AAO3B,IAAI,KAAK,GA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C,CAAC;QAG/B,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,KAAK,EAAE,EAAE;YACxC,OAAO,CAAC,KAAK,CAAC,qBAAqB,EAAE,KAAK,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAE5D,IAAI,KAAK,EAAE,CAAC;YACT,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;YAClC,KAAK,GAAG,IAAI,CAAC;QACf,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,MAAM,UAAU,iCAAiC;IAC9C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import { spawn, ChildProcess } from \"child_process\";\nimport { watch } from \"chokidar\";\nimport { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { getVersion } from \"./utils/cli.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { importModule } from \"../helpers/global.helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport sheu from \"../sheu\";\n\ninterface DevOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Dev server command for the arkos CLI\n */\nexport async function devCommand(options: DevOptions = {}) {\n process.env.NODE_ENV = \"development\";\n envFiles = loadEnvironmentVariables();\n child = null;\n let restartTimeout: NodeJS.Timeout | null = null;\n\n try {\n const { port, host } = options;\n let isRestarting = false;\n // Detect if project uses TypeScript or JavaScript\n const fileExt = getUserFileExtension();\n\n // Find the application entry point\n const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);\n\n if (!fs.existsSync(entryPoint)) {\n console.error(\"Could not find application entry point.\");\n process.exit(1);\n }\n\n // Set environment variables\n const getEnv = () =>\n ({\n NODE_ENV: \"development\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n }) as { [x: string]: string };\n\n // Function to start the child process\n const startServer = () => {\n if (child) {\n child.kill();\n child = null;\n }\n\n const env = getEnv();\n\n if (fileExt === \"ts\") {\n // Enhanced ts-node-dev configuration\n child = spawn(\n \"npx\",\n [\n \"ts-node-dev\",\n \"--respawn\",\n \"--notify=false\", // Disable desktop notifications\n \"--ignore-watch\",\n \"node_modules\",\n \"--ignore-watch\",\n \"dist\",\n \"--ignore-watch\",\n \"build\",\n \"--ignore-watch\",\n \".dist\",\n \"--ignore-watch\",\n \".build\",\n \"--watch\",\n \"src\", // Explicitly watch src directory\n entryPoint,\n ],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n } else {\n // Enhanced nodemon configuration\n child = spawn(\n \"npx\",\n [\n \"nodemon\",\n \"--watch\",\n \"src\",\n \"--ext\",\n \"js,json\",\n \"--ignore\",\n \"node_modules/\",\n \"--ignore\",\n \"dist/\",\n \"--ignore\",\n \"build/\",\n \"--ignore\",\n \".dist/\",\n \"--ignore\",\n \".build/\",\n \"--delay\",\n \"1000ms\",\n entryPoint,\n ],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n }\n\n if (child) {\n child.on(\"error\", (error) => {\n console.error(\"Failed to start server:\", error);\n });\n\n child.on(\"exit\", (code, signal) => {\n if (!isRestarting && signal !== \"SIGTERM\" && signal !== \"SIGINT\") {\n console.info(`Server exited with code ${code}, restarting...`);\n startServer();\n }\n });\n }\n };\n\n // Function to handle server restart with debouncing\n const scheduleRestart = (reason: string) => {\n if (restartTimeout) clearTimeout(restartTimeout);\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n sheu.info(`\\x1b[90m${time}\\x1b[0m Restarting: ${reason.toLowerCase()}`);\n\n isRestarting = true;\n if (child) {\n child.kill();\n child = null;\n }\n restartTimeout = setTimeout(() => {\n startServer();\n restartTimeout = null;\n }, 1000);\n };\n\n // Setup environment file watching\n const setupEnvWatcher = () => {\n const envWatcher = watch(\n fullCleanCwd(envFiles?.join(\",\") || \"\")\n .replaceAll(\"/\", \"\")\n .split(\",\") || [],\n {\n ignoreInitial: true,\n persistent: true,\n }\n );\n\n envWatcher.on(\"all\", (event, filePath) => {\n try {\n envFiles = loadEnvironmentVariables();\n\n // Restart server to pick up new env vars\n scheduleRestart(\"Environments files changed\");\n } catch (error) {\n console.error(`Error reloading ${filePath}:`, error);\n }\n });\n\n return envWatcher;\n };\n\n // Setup additional file watching for better new file detection\n const setupAdditionalWatcher = () => {\n const additionalWatcher = watch(\n [\n \"src\",\n \"package.json\",\n \"tsconfig.json\",\n \"arkos.config.ts\",\n \"arkos.config.js\",\n ],\n {\n ignoreInitial: true,\n ignored: [\n /node_modules/,\n /\\.git/,\n /\\.dist/,\n /\\.build/,\n /dist/,\n /build/,\n /\\.env.*/,\n ],\n }\n );\n\n additionalWatcher.on(\"add\", (filePath) => {\n scheduleRestart(`${fullCleanCwd(filePath)} has been created`);\n });\n\n additionalWatcher.on(\"unlink\", (filePath) => {\n scheduleRestart(`${fullCleanCwd(filePath)} has been deleted`);\n });\n\n return additionalWatcher;\n };\n\n // Start the server\n startServer();\n\n // Setup watchers if enabled\n const envWatcher = setupEnvWatcher();\n const additionalWatcher = setupAdditionalWatcher();\n\n const checkConfig = async () => {\n try {\n // Import the config getter\n const { getArkosConfig } = await importModule(\"../../server\");\n const config = getArkosConfig();\n if (config && config.available) {\n // Config is ready, display the info with actual values\n const env = getEnv();\n console.info(\"\\n\");\n console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n console.info(\n ` - Local: http://${\n env.CLI_HOST || config.host || env.HOST || \"localhost\"\n }:${env.CLI_PORT || config.port || env.PORT || \"8000\"}`\n );\n console.info(\n ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n .replaceAll(`${process.cwd()}/`, \"\")\n .replaceAll(\"/\", \"\")}`\n );\n console.info(\"\\n\");\n return true;\n }\n return false;\n } catch (error) {\n return false;\n }\n };\n\n // Try to get config periodically\n const waitForConfig = async () => {\n let attempts = 0;\n const maxAttempts = 15;\n while (attempts < maxAttempts) {\n const ready = await checkConfig();\n if (ready) break;\n await new Promise((resolve) => setTimeout(resolve, 300));\n attempts++;\n }\n\n // Fall back to defaults if config never became available\n if (attempts >= maxAttempts) {\n const env = getEnv();\n console.info(\"\\n\");\n console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n console.info(\n ` - Local: http://${\n env.CLI_HOST || env.HOST || \"localhost\"\n }:${env.CLI_PORT || env.PORT || \"8000\"}`\n );\n console.info(\n ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n .replaceAll(`${process.cwd()}/`, \"\")\n .replaceAll(\"/\", \"\")}`\n );\n console.info(\"\\n\");\n }\n };\n\n waitForConfig();\n\n // Enhanced cleanup function\n const cleanup = () => {\n // console.info(\"\\nShutting down development server...\");\n\n if (restartTimeout) clearTimeout(restartTimeout);\n\n if (envWatcher) envWatcher.close();\n\n if (additionalWatcher) additionalWatcher.close();\n\n if (child) {\n child.kill(\"SIGTERM\");\n\n // Force kill after 5 seconds if still running\n setTimeout(() => {\n if (child && !child.killed) {\n child.kill(\"SIGKILL\");\n }\n }, 5000);\n }\n\n process.exit(0);\n };\n\n // Handle process exit\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Handle uncaught exceptions\n process.on(\"uncaughtException\", (error) => {\n console.error(\"Uncaught Exception:\", error);\n cleanup();\n });\n } catch (error) {\n console.error(\"Development server failed to start:\", error);\n\n if (child) {\n (child as ChildProcess)?.kill?.();\n child = null;\n }\n\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the development server child process\n */\nexport function killDevelopmentServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
|