pwi-plata-type 0.4.201 → 0.4.202

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +2 -2
  2. package/package.json +58 -58
  3. package/src/@types/build.d.ts +26 -26
  4. package/src/@types/cluster.actions.d.ts +27 -27
  5. package/src/@types/cluster.d.ts +55 -55
  6. package/src/@types/create-cli.d.ts +8 -8
  7. package/src/@types/exported.d.ts +34 -31
  8. package/src/@types/fs.d.ts +6 -6
  9. package/src/@types/global.d.ts +131 -131
  10. package/src/@types/knex.d.ts +13 -13
  11. package/src/@types/model.d.ts +143 -143
  12. package/src/@types/router.d.ts +107 -107
  13. package/src/@types/sql.d.ts +120 -120
  14. package/src/@types/swagger.d.ts +22 -22
  15. package/src/bin/extras/create-api-cli.ts +218 -218
  16. package/src/bin/extras/create-cluster-cli.ts +160 -160
  17. package/src/bin/extras/create-lib-cli.ts +84 -84
  18. package/src/bin/extras/plata-create-tools.ts +97 -97
  19. package/src/bin/plata-api.ts +189 -189
  20. package/src/bin/plata-build.ts +19 -19
  21. package/src/bin/plata-cluster.ts +42 -42
  22. package/src/bin/plata-cmd.ts +19 -19
  23. package/src/bin/plata-create.ts +50 -50
  24. package/src/bin/plata-runtime.ts +110 -110
  25. package/src/bin/plata-swagger.ts +104 -104
  26. package/src/index.ts +20 -20
  27. package/src/libs/axios.ts +32 -32
  28. package/src/libs/build.ts +234 -234
  29. package/src/libs/build_wasm.ts +169 -169
  30. package/src/libs/cluster/cluster-controller.ts +93 -93
  31. package/src/libs/cluster.ts +319 -319
  32. package/src/libs/custom.ts +21 -21
  33. package/src/libs/env.ts +10 -10
  34. package/src/libs/fs.ts +399 -399
  35. package/src/libs/hot-reload.ts +63 -63
  36. package/src/libs/job.ts +32 -32
  37. package/src/libs/models/index.ts +4 -4
  38. package/src/libs/models/model-template-combine.ts +93 -93
  39. package/src/libs/models/model-template-env.ts +58 -58
  40. package/src/libs/models/model-template-union.ts +87 -87
  41. package/src/libs/models/model-template.ts +111 -111
  42. package/src/libs/models/model-validations.ts +453 -453
  43. package/src/libs/models/tools.ts +196 -196
  44. package/src/libs/router.ts +184 -184
  45. package/src/libs/runtime.ts +328 -328
  46. package/src/libs/sql.ts +931 -931
  47. package/src/libs/swagger.ts +81 -81
  48. package/src/libs/tools.ts +236 -236
  49. package/src/misc/golang/wasm_exec.js +574 -574
  50. package/src/scripts/post-install/api.ts +32 -32
  51. package/src/scripts/post-install/cluster.ts +28 -28
  52. package/src/scripts/post-install/lib.ts +25 -25
  53. package/src/scripts/post-install.ts +64 -64
  54. package/src/scripts/pre-test.ts +33 -33
  55. package/src/tests/1-config.test.ts +12 -12
  56. package/src/tests/2-effect.test.ts +107 -107
  57. package/src/tests/3-model.env.test.ts +66 -66
  58. package/src/tests/4-model.test.ts +150 -150
  59. package/src/tests/5-model.union.test.ts +160 -160
  60. package/src/tests/6-router.test.ts +44 -44
  61. package/src/tests/7-switch.test.ts +75 -75
  62. package/src/tests/8-brands.test.ts +52 -52
  63. package/src/tests/9-sql.test.ts +639 -639
  64. package/src/tests/assets/sql/example.sql +94 -94
  65. package/templates/create-cli/class.ts +13 -13
  66. package/templates/create-cli/cluster.ts +14 -14
  67. package/templates/create-cli/cmd.ts +3 -3
  68. package/templates/create-cli/config.ts +2 -2
  69. package/templates/create-cli/lib.ts +3 -3
  70. package/templates/create-cli/model.ts +14 -14
  71. package/templates/create-cli/route.ts +8 -8
  72. package/templates/create-cli/task.ts +13 -13
  73. package/templates/postinstall/api/.vscode/launch.json +20 -20
  74. package/templates/postinstall/api/Dockerfile +22 -22
  75. package/templates/postinstall/api/configs/env.ts +2 -2
  76. package/templates/postinstall/api/envs/debug.env +15 -15
  77. package/templates/postinstall/api/envs/homolog.env +15 -15
  78. package/templates/postinstall/api/envs/prod.env +15 -15
  79. package/templates/postinstall/api/tsconfig.json +24 -24
  80. package/templates/postinstall/cluster/.vscode/launch.json +20 -20
  81. package/templates/postinstall/cluster/Dockerfile +24 -24
  82. package/templates/postinstall/cluster/configs/env.ts +2 -2
  83. package/templates/postinstall/cluster/envs/debug.env +10 -10
  84. package/templates/postinstall/cluster/envs/homolog.env +10 -10
  85. package/templates/postinstall/cluster/envs/prod.env +10 -10
  86. package/templates/postinstall/cluster/tsconfig.json +24 -24
  87. package/templates/postinstall/lib/postinstall-tools.mjs +111 -111
  88. package/templates/postinstall/lib/postinstall.js +33 -33
  89. package/templates/postinstall/lib/tsconfig.json +22 -22
  90. package/templates/swagger-cli/header.json +21 -21
  91. package/templates/swagger-cli/route/body.json +14 -14
  92. package/templates/swagger-cli/route/header.json +18 -18
  93. package/templates/swagger-cli/route/response.json +53 -53
  94. package/tsconfig.json +28 -28
@@ -1,43 +1,43 @@
1
- import { PlataClusterManager } from "++/libs/cluster"
2
-
3
- export async function main() {
4
- const cluster = new PlataClusterManager()
5
-
6
- if (cluster.isPrimary()) {
7
- const clustersPromise: RequireFolderReturn<{ default: Cluster.WorkerConfig }> = require("@@/clusters/*.*")
8
- const clusters = await clustersPromise
9
-
10
- if (clusters.errorID !== undefined) {
11
- console.log(clusters)
12
- process.exit(0)
13
- }
14
-
15
- const promises: Promise<void>[] = []
16
-
17
- clusters.forEach(c => {
18
- const config = c.exports.default
19
- promises.push(cluster._startCluster(config).then(r => {
20
- if (r !== null) {
21
- console.log(r)
22
- process.exit(0)
23
- }
24
- }))
25
- })
26
-
27
- await Promise.all(promises)
28
- } else {
29
- if (Plata.config._PLATA_WORKER_NAME === undefined) {
30
- await cluster.send({
31
- action: 'KILL',
32
- msg: 'tried to start a Worker without _PLATA_WORKER_NAME'
33
- })
34
-
35
- return
36
- }
37
-
38
- await cluster._onStartCluster(
39
- Plata.config._PLATA_WORKER_NAME,
40
- Plata.config._PLATA_WORKER_TYPE,
41
- )
42
- }
1
+ import { PlataClusterManager } from "++/libs/cluster"
2
+
3
+ export async function main() {
4
+ const cluster = new PlataClusterManager()
5
+
6
+ if (cluster.isPrimary()) {
7
+ const clustersPromise: RequireFolderReturn<{ default: Cluster.WorkerConfig }> = require("@@/clusters/*.*")
8
+ const clusters = await clustersPromise
9
+
10
+ if (clusters.errorID !== undefined) {
11
+ console.log(clusters)
12
+ process.exit(0)
13
+ }
14
+
15
+ const promises: Promise<void>[] = []
16
+
17
+ clusters.forEach(c => {
18
+ const config = c.exports.default
19
+ promises.push(cluster._startCluster(config).then(r => {
20
+ if (r !== null) {
21
+ console.log(r)
22
+ process.exit(0)
23
+ }
24
+ }))
25
+ })
26
+
27
+ await Promise.all(promises)
28
+ } else {
29
+ if (Plata.config._PLATA_WORKER_NAME === undefined) {
30
+ await cluster.send({
31
+ action: 'KILL',
32
+ msg: 'tried to start a Worker without _PLATA_WORKER_NAME'
33
+ })
34
+
35
+ return
36
+ }
37
+
38
+ await cluster._onStartCluster(
39
+ Plata.config._PLATA_WORKER_NAME,
40
+ Plata.config._PLATA_WORKER_TYPE,
41
+ )
42
+ }
43
43
  }
@@ -1,20 +1,20 @@
1
- export async function main() {
2
- const args = process.argv.slice(
3
- process.argv.indexOf('+')
4
- )
5
-
6
- const run = args.slice(
7
- args.indexOf('plata-cmd') + 1
8
- )[0]?.toLowerCase()
9
-
10
- if (!run) {
11
- console.log('Comando inválido')
12
- console.log(process.argv.join(' '))
13
- process.exit(0)
14
- }
15
-
16
- const cmd: { main: () => Promise<void> } = require(`@@/cmds/${run}`)
17
-
18
- await cmd.main()
19
- process.exit(0)
1
+ export async function main() {
2
+ const args = process.argv.slice(
3
+ process.argv.indexOf('+')
4
+ )
5
+
6
+ const run = args.slice(
7
+ args.indexOf('plata-cmd') + 1
8
+ )[0]?.toLowerCase()
9
+
10
+ if (!run) {
11
+ console.log('Comando inválido')
12
+ console.log(process.argv.join(' '))
13
+ process.exit(0)
14
+ }
15
+
16
+ const cmd: { main: () => Promise<void> } = require(`@@/cmds/${run}`)
17
+
18
+ await cmd.main()
19
+ process.exit(0)
20
20
  }
@@ -1,51 +1,51 @@
1
- import { PlataBuild } from "++/libs/build"
2
- import type { Command } from "commander"
3
-
4
- export const main = async () => {
5
- if (Plata.ProjectJson.plata_no_setup !== undefined) {
6
- console.log('Plata não configurada remova o plata_no_setup do package.json')
7
- process.exit(0)
8
- }
9
-
10
- const args = process.argv.slice(process.argv.indexOf('+'))
11
- let cli: Command | null = null
12
-
13
- switch (Plata.ProjectJson.plata_type ?? 'api') {
14
- case 'api':
15
- cli = await (require('++/bin/extras/create-api-cli') as CreateCli.ImportedCreateCli).cli
16
- break
17
- case 'lib':
18
- cli = await (require('++/bin/extras/create-lib-cli') as CreateCli.ImportedCreateCli).cli
19
- break
20
- case 'cluster':
21
- cli = await (require('++/bin/extras/create-cluster-cli') as CreateCli.ImportedCreateCli).cli
22
- break
23
- default:
24
- console.log(`${Plata.ProjectJson.plata_type} not supported`)
25
- process.exit(0)
26
- break
27
- }
28
-
29
- const config = await PlataBuild.getBuildConfig()
30
-
31
- if (config.errorID !== undefined) {
32
- console.log(`⚠️ - Não foi possivel carregar a config - ${config.errorID}`)
33
-
34
- return cli.parseAsync(args)
35
- }
36
-
37
- if (config.plugins?.length) {
38
- for (let i = 0; i < config.plugins.length; i++) {
39
- const plugin = config.plugins[i];
40
-
41
- if (plugin.cliCreate !== undefined) {
42
- cli = await plugin.cliCreate(cli)
43
- }
44
- }
45
-
46
- console.log(`✅ - Plugins carregados`)
47
- }
48
-
49
- await cli.parseAsync(args)
50
- process.exit(0)
1
+ import { PlataBuild } from "++/libs/build"
2
+ import type { Command } from "commander"
3
+
4
+ export const main = async () => {
5
+ if (Plata.ProjectJson.plata_no_setup !== undefined) {
6
+ console.log('Plata não configurada remova o plata_no_setup do package.json')
7
+ process.exit(0)
8
+ }
9
+
10
+ const args = process.argv.slice(process.argv.indexOf('+'))
11
+ let cli: Command | null = null
12
+
13
+ switch (Plata.ProjectJson.plata_type ?? 'api') {
14
+ case 'api':
15
+ cli = await (require('++/bin/extras/create-api-cli') as CreateCli.ImportedCreateCli).cli
16
+ break
17
+ case 'lib':
18
+ cli = await (require('++/bin/extras/create-lib-cli') as CreateCli.ImportedCreateCli).cli
19
+ break
20
+ case 'cluster':
21
+ cli = await (require('++/bin/extras/create-cluster-cli') as CreateCli.ImportedCreateCli).cli
22
+ break
23
+ default:
24
+ console.log(`${Plata.ProjectJson.plata_type} not supported`)
25
+ process.exit(0)
26
+ break
27
+ }
28
+
29
+ const config = await PlataBuild.getBuildConfig()
30
+
31
+ if (config.errorID !== undefined) {
32
+ console.log(`⚠️ - Não foi possivel carregar a config - ${config.errorID}`)
33
+
34
+ return cli.parseAsync(args)
35
+ }
36
+
37
+ if (config.plugins?.length) {
38
+ for (let i = 0; i < config.plugins.length; i++) {
39
+ const plugin = config.plugins[i];
40
+
41
+ if (plugin.cliCreate !== undefined) {
42
+ cli = await plugin.cliCreate(cli)
43
+ }
44
+ }
45
+
46
+ console.log(`✅ - Plugins carregados`)
47
+ }
48
+
49
+ await cli.parseAsync(args)
50
+ process.exit(0)
51
51
  }
@@ -1,111 +1,111 @@
1
- #!/usr/bin/env node
2
- import path from 'node:path'
3
- import { PlataEnvLoader } from '../libs/env'
4
- import { PlataBuild } from '../libs/build'
5
- import { PlataBuildWasm } from '../libs/build_wasm'
6
-
7
- async function compile() {
8
- if (Plata.cluster.isPrimary !== true) return
9
-
10
- await PlataBuild.compile({
11
- basePath: Plata.ProjectDir,
12
- mapFiles: true,
13
- packageJsonSetup: false,
14
- otimizar: false,
15
- })
16
- }
17
-
18
- const shouldCompile = async () => { // TODO Colocar a compilição e essa função em um arquivo separado
19
- if (process.argv.findIndex(p => p === '--skip-recompile') !== -1 || Plata.ProjectJson['plata_skip_recompile'] !== undefined)
20
- return Plata.files.access(path.join(Plata.ProjectDir, '__BUILD__')).then(r => !r)
21
- ;
22
-
23
- return true
24
- }
25
-
26
- const main = async () => {
27
- const g = global as any
28
-
29
- const { PlataGlobalRuntime } = require('../libs/runtime')
30
-
31
- g.Plata = new PlataGlobalRuntime()
32
-
33
- if (await shouldCompile())
34
- await compile()
35
- ;
36
-
37
- module.constructor.prototype.require = function (pathRequire) {
38
- const self = this;
39
- if (typeof pathRequire !== 'string') {
40
- throw new Error('path must be a string')
41
- }
42
-
43
- if (!pathRequire) {
44
- throw new Error('missing path')
45
- }
46
-
47
- try {
48
- switch (pathRequire.slice(0,2)) {
49
- case '@@':
50
- pathRequire = pathRequire.replace('@@', `${Plata.ProjectDir}/__BUILD__`)
51
- break
52
- case '++':
53
- pathRequire = pathRequire.replace('++', `${Plata.PlataDir}/__BUILD__`)
54
- break
55
- }
56
-
57
- pathRequire = pathRequire.replace(/\\/g, '/')
58
-
59
- switch (path.extname(pathRequire)) {
60
- case '.env':
61
- return Plata.FastPromise(() => Plata.ReadEnvFileToPromise(pathRequire))
62
- break
63
- case '.*':
64
- return Plata.FastPromise(() => Plata.RequireFolder(path.dirname(pathRequire)))
65
- break
66
- default:
67
- return self.constructor._load(pathRequire, self)
68
- break
69
- }
70
-
71
-
72
- } catch (err) {
73
- // if module not found, we have nothing to do, simply throw it back.
74
- if (err.code === 'MODULE_NOT_FOUND') {
75
- throw err;
76
- }
77
- // resolve the path to get absolute path
78
- pathRequire = path.resolve(__dirname, pathRequire)
79
-
80
- // Write to log or whatever
81
- console.log('Error in file: ' + pathRequire);
82
- }
83
- }
84
-
85
- const envFile = await PlataEnvLoader.load()
86
-
87
- if (envFile.errorID !== undefined) {
88
- console.log(envFile)
89
- process.exit(1)
90
- }
91
-
92
- for (const key in envFile) {
93
- Plata.config[key] = envFile[key]
94
- }
95
-
96
- await PlataBuildWasm.loadFilesWasm()
97
-
98
- // roda o sript solicitado
99
- const run = process.argv[process.argv.indexOf('+') + 1]
100
-
101
- if (global.gc !== undefined) {
102
- // Se disponivel tenta limpar a memoria para reduzir uso de RAM
103
- setTimeout(global.gc, 60_000)
104
- }
105
-
106
- const app: { main: () => Promise<void> } = require(`++/bin/${run}`)
107
-
108
- await app.main()
109
- }
110
-
1
+ #!/usr/bin/env node
2
+ import path from 'node:path'
3
+ import { PlataEnvLoader } from '../libs/env'
4
+ import { PlataBuild } from '../libs/build'
5
+ import { PlataBuildWasm } from '../libs/build_wasm'
6
+
7
+ async function compile() {
8
+ if (Plata.cluster.isPrimary !== true) return
9
+
10
+ await PlataBuild.compile({
11
+ basePath: Plata.ProjectDir,
12
+ mapFiles: true,
13
+ packageJsonSetup: false,
14
+ otimizar: false,
15
+ })
16
+ }
17
+
18
+ const shouldCompile = async () => { // TODO Colocar a compilição e essa função em um arquivo separado
19
+ if (process.argv.findIndex(p => p === '--skip-recompile') !== -1 || Plata.ProjectJson['plata_skip_recompile'] !== undefined)
20
+ return Plata.files.access(path.join(Plata.ProjectDir, '__BUILD__')).then(r => !r)
21
+ ;
22
+
23
+ return true
24
+ }
25
+
26
+ const main = async () => {
27
+ const g = global as any
28
+
29
+ const { PlataGlobalRuntime } = require('../libs/runtime')
30
+
31
+ g.Plata = new PlataGlobalRuntime()
32
+
33
+ if (await shouldCompile())
34
+ await compile()
35
+ ;
36
+
37
+ module.constructor.prototype.require = function (pathRequire) {
38
+ const self = this;
39
+ if (typeof pathRequire !== 'string') {
40
+ throw new Error('path must be a string')
41
+ }
42
+
43
+ if (!pathRequire) {
44
+ throw new Error('missing path')
45
+ }
46
+
47
+ try {
48
+ switch (pathRequire.slice(0,2)) {
49
+ case '@@':
50
+ pathRequire = pathRequire.replace('@@', `${Plata.ProjectDir}/__BUILD__`)
51
+ break
52
+ case '++':
53
+ pathRequire = pathRequire.replace('++', `${Plata.PlataDir}/__BUILD__`)
54
+ break
55
+ }
56
+
57
+ pathRequire = pathRequire.replace(/\\/g, '/')
58
+
59
+ switch (path.extname(pathRequire)) {
60
+ case '.env':
61
+ return Plata.FastPromise(() => Plata.ReadEnvFileToPromise(pathRequire))
62
+ break
63
+ case '.*':
64
+ return Plata.FastPromise(() => Plata.RequireFolder(path.dirname(pathRequire)))
65
+ break
66
+ default:
67
+ return self.constructor._load(pathRequire, self)
68
+ break
69
+ }
70
+
71
+
72
+ } catch (err) {
73
+ // if module not found, we have nothing to do, simply throw it back.
74
+ if (err.code === 'MODULE_NOT_FOUND') {
75
+ throw err;
76
+ }
77
+ // resolve the path to get absolute path
78
+ pathRequire = path.resolve(__dirname, pathRequire)
79
+
80
+ // Write to log or whatever
81
+ console.log('Error in file: ' + pathRequire);
82
+ }
83
+ }
84
+
85
+ const envFile = await PlataEnvLoader.load()
86
+
87
+ if (envFile.errorID !== undefined) {
88
+ console.log(envFile)
89
+ process.exit(1)
90
+ }
91
+
92
+ for (const key in envFile) {
93
+ Plata.config[key] = envFile[key]
94
+ }
95
+
96
+ await PlataBuildWasm.loadFilesWasm()
97
+
98
+ // roda o sript solicitado
99
+ const run = process.argv[process.argv.indexOf('+') + 1]
100
+
101
+ if (global.gc !== undefined) {
102
+ // Se disponivel tenta limpar a memoria para reduzir uso de RAM
103
+ setTimeout(global.gc, 60_000)
104
+ }
105
+
106
+ const app: { main: () => Promise<void> } = require(`++/bin/${run}`)
107
+
108
+ await app.main()
109
+ }
110
+
111
111
  main()
@@ -1,105 +1,105 @@
1
- import path from 'node:path'
2
- import fs from 'node:fs'
3
- import { buildExpressRouter, loadRoutesFromProject } from "++/libs/router"
4
- import { getCustomExpress } from '++/libs/custom'
5
-
6
- export async function dumpRoutes() {
7
- const requiredRoutes = await loadRoutesFromProject()
8
-
9
- if (requiredRoutes.errorID !== undefined) {
10
- console.log(requiredRoutes)
11
- process.exit(1)
12
- }
13
-
14
- const { router } = await getCustomExpress()
15
-
16
- const buildedRouter = await buildExpressRouter(requiredRoutes, router)
17
-
18
- if (buildedRouter.errorID !== undefined) {
19
- console.log(buildedRouter)
20
- process.exit(1)
21
- }
22
-
23
- const dumpedRoutes: SwaggerGen.Route[] = []
24
- const regex = /:(.*?)\??\//g
25
-
26
- for (const r of buildedRouter.routes) {
27
- if (r.swaggerHide) {
28
- continue
29
- }
30
-
31
- r.path = path.normalize(`${r.path ?? '/'}/`).replace(/\\/g, '/')
32
-
33
- const dumpedRouteParams: SwaggerGen.RouteParameter[] = []
34
- const urlParms = r.path.match(regex) ?? []
35
-
36
- for (const p of urlParms) {
37
- dumpedRouteParams.push({
38
- name: p.replace(regex, '$1'),
39
- required: p[p.length - 2] !== '?',
40
- in: 'path',
41
- type: 'string'
42
- })
43
- }
44
-
45
- dumpedRoutes.push({
46
- httpRoute: r.path.replace(regex, '{$1}/'),
47
- method: r.method,
48
- params: dumpedRouteParams,
49
- })
50
- }
51
-
52
- return dumpedRoutes
53
- }
54
-
55
- export async function toProjectSwagger(file: string, content: any): Promise<void> {
56
- try {
57
- const p = path.resolve(Plata.ProjectDir, 'swagger', file)
58
-
59
- if (!fs.existsSync(p)) {
60
- fs.mkdirSync(path.dirname(p), { recursive: true })
61
- fs.writeFileSync(p, JSON.stringify(content, null, 4))
62
- }
63
-
64
- } catch (e) {
65
- console.log(e)
66
- process.exit(1)
67
- }
68
- }
69
-
70
- export const main = async () => {
71
- const routes = await dumpRoutes()
72
-
73
- const templateFolder = path.join(Plata.PlataDir, 'templates', 'swagger-cli')
74
-
75
- const files: SwaggerGen.Files = {
76
- swaggerHeader: require(path.join(templateFolder, 'header.json')),
77
- route: {
78
- header: require(path.join(templateFolder, 'route', 'header.json')),
79
- body: require(path.join(templateFolder, 'route', 'body.json')),
80
- response: require(path.join(templateFolder, 'route', 'response.json')),
81
- }
82
- }
83
-
84
- for (const route of routes) {
85
-
86
- // https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy
87
- const fileCopy:SwaggerGen.Files = JSON.parse(JSON.stringify(files))
88
-
89
- for(const json in fileCopy.route) {
90
- await toProjectSwagger(
91
- path.join('routes', route.httpRoute, route.method.toLowerCase(), `${json}.json`),
92
- fileCopy.route[json]
93
- )
94
- }
95
- }
96
-
97
- await toProjectSwagger(
98
- 'header.json',
99
- files.swaggerHeader
100
- )
101
-
102
- console.log('Done')
103
-
104
- process.exit(0)
1
+ import path from 'node:path'
2
+ import fs from 'node:fs'
3
+ import { buildExpressRouter, loadRoutesFromProject } from "++/libs/router"
4
+ import { getCustomExpress } from '++/libs/custom'
5
+
6
+ export async function dumpRoutes() {
7
+ const requiredRoutes = await loadRoutesFromProject()
8
+
9
+ if (requiredRoutes.errorID !== undefined) {
10
+ console.log(requiredRoutes)
11
+ process.exit(1)
12
+ }
13
+
14
+ const { router } = await getCustomExpress()
15
+
16
+ const buildedRouter = await buildExpressRouter(requiredRoutes, router)
17
+
18
+ if (buildedRouter.errorID !== undefined) {
19
+ console.log(buildedRouter)
20
+ process.exit(1)
21
+ }
22
+
23
+ const dumpedRoutes: SwaggerGen.Route[] = []
24
+ const regex = /:(.*?)\??\//g
25
+
26
+ for (const r of buildedRouter.routes) {
27
+ if (r.swaggerHide) {
28
+ continue
29
+ }
30
+
31
+ r.path = path.normalize(`${r.path ?? '/'}/`).replace(/\\/g, '/')
32
+
33
+ const dumpedRouteParams: SwaggerGen.RouteParameter[] = []
34
+ const urlParms = r.path.match(regex) ?? []
35
+
36
+ for (const p of urlParms) {
37
+ dumpedRouteParams.push({
38
+ name: p.replace(regex, '$1'),
39
+ required: p[p.length - 2] !== '?',
40
+ in: 'path',
41
+ type: 'string'
42
+ })
43
+ }
44
+
45
+ dumpedRoutes.push({
46
+ httpRoute: r.path.replace(regex, '{$1}/'),
47
+ method: r.method,
48
+ params: dumpedRouteParams,
49
+ })
50
+ }
51
+
52
+ return dumpedRoutes
53
+ }
54
+
55
+ export async function toProjectSwagger(file: string, content: any): Promise<void> {
56
+ try {
57
+ const p = path.resolve(Plata.ProjectDir, 'swagger', file)
58
+
59
+ if (!fs.existsSync(p)) {
60
+ fs.mkdirSync(path.dirname(p), { recursive: true })
61
+ fs.writeFileSync(p, JSON.stringify(content, null, 4))
62
+ }
63
+
64
+ } catch (e) {
65
+ console.log(e)
66
+ process.exit(1)
67
+ }
68
+ }
69
+
70
+ export const main = async () => {
71
+ const routes = await dumpRoutes()
72
+
73
+ const templateFolder = path.join(Plata.PlataDir, 'templates', 'swagger-cli')
74
+
75
+ const files: SwaggerGen.Files = {
76
+ swaggerHeader: require(path.join(templateFolder, 'header.json')),
77
+ route: {
78
+ header: require(path.join(templateFolder, 'route', 'header.json')),
79
+ body: require(path.join(templateFolder, 'route', 'body.json')),
80
+ response: require(path.join(templateFolder, 'route', 'response.json')),
81
+ }
82
+ }
83
+
84
+ for (const route of routes) {
85
+
86
+ // https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy
87
+ const fileCopy:SwaggerGen.Files = JSON.parse(JSON.stringify(files))
88
+
89
+ for(const json in fileCopy.route) {
90
+ await toProjectSwagger(
91
+ path.join('routes', route.httpRoute, route.method.toLowerCase(), `${json}.json`),
92
+ fileCopy.route[json]
93
+ )
94
+ }
95
+ }
96
+
97
+ await toProjectSwagger(
98
+ 'header.json',
99
+ files.swaggerHeader
100
+ )
101
+
102
+ console.log('Done')
103
+
104
+ process.exit(0)
105
105
  }