pwi-plata-type 0.3.17 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/__BUILD__/bin/extras/create-api-cli.js +96 -0
  2. package/__BUILD__/bin/extras/create-api-cli.js.map +1 -0
  3. package/__BUILD__/bin/extras/create-lib-cli.js +62 -0
  4. package/__BUILD__/bin/extras/create-lib-cli.js.map +1 -0
  5. package/__BUILD__/bin/extras/plata-create-tools.js +94 -0
  6. package/__BUILD__/bin/extras/plata-create-tools.js.map +1 -0
  7. package/__BUILD__/bin/plata-api.js +138 -0
  8. package/__BUILD__/bin/plata-api.js.map +1 -0
  9. package/__BUILD__/bin/plata-create.js +24 -0
  10. package/__BUILD__/bin/plata-create.js.map +1 -0
  11. package/__BUILD__/bin/plata-runtime.js +156 -0
  12. package/__BUILD__/bin/plata-runtime.js.map +1 -0
  13. package/__BUILD__/bin/plata-swagger.js +82 -0
  14. package/__BUILD__/bin/plata-swagger.js.map +1 -0
  15. package/__BUILD__/bin/runtime/_setupRuntime.js +43 -0
  16. package/__BUILD__/bin/runtime/_setupRuntime.js.map +1 -0
  17. package/__BUILD__/bin/runtime/class.js +18 -0
  18. package/__BUILD__/bin/runtime/class.js.map +1 -0
  19. package/__BUILD__/bin/runtime/dirs.js +16 -0
  20. package/__BUILD__/bin/runtime/dirs.js.map +1 -0
  21. package/__BUILD__/bin/runtime/promises.js +15 -0
  22. package/__BUILD__/bin/runtime/promises.js.map +1 -0
  23. package/__BUILD__/bin/runtime/require.js +88 -0
  24. package/__BUILD__/bin/runtime/require.js.map +1 -0
  25. package/__BUILD__/index.js +42 -0
  26. package/__BUILD__/index.js.map +1 -0
  27. package/__BUILD__/libs/axios.js +42 -0
  28. package/__BUILD__/libs/axios.js.map +1 -0
  29. package/__BUILD__/libs/cluster.js +160 -0
  30. package/__BUILD__/libs/cluster.js.map +1 -0
  31. package/__BUILD__/libs/fs.js +206 -0
  32. package/__BUILD__/libs/fs.js.map +1 -0
  33. package/__BUILD__/libs/model-validations.js +356 -0
  34. package/__BUILD__/libs/model-validations.js.map +1 -0
  35. package/__BUILD__/libs/model.js +185 -0
  36. package/__BUILD__/libs/model.js.map +1 -0
  37. package/__BUILD__/libs/router.js +127 -0
  38. package/__BUILD__/libs/router.js.map +1 -0
  39. package/__BUILD__/libs/swagger.js +64 -0
  40. package/__BUILD__/libs/swagger.js.map +1 -0
  41. package/__BUILD__/libs/tasks.js +134 -0
  42. package/__BUILD__/libs/tasks.js.map +1 -0
  43. package/__BUILD__/libs/tools.js +231 -0
  44. package/__BUILD__/libs/tools.js.map +1 -0
  45. package/__BUILD__/scripts/post-install/api.js +25 -0
  46. package/__BUILD__/scripts/post-install/api.js.map +1 -0
  47. package/__BUILD__/scripts/post-install/lib.js +25 -0
  48. package/__BUILD__/scripts/post-install/lib.js.map +1 -0
  49. package/__BUILD__/scripts/post-install.js +65 -0
  50. package/__BUILD__/scripts/post-install.js.map +1 -0
  51. package/__BUILD__/scripts/pre-test.js +25 -0
  52. package/__BUILD__/scripts/pre-test.js.map +1 -0
  53. package/package.json +18 -16
  54. package/src/@types/cluster.actions.d.ts +7 -0
  55. package/src/@types/cluster.d.ts +33 -0
  56. package/src/@types/create-cli.d.ts +9 -0
  57. package/src/@types/exported.d.ts +24 -0
  58. package/src/@types/global.d.ts +69 -0
  59. package/src/@types/model.d.ts +69 -0
  60. package/src/@types/router.d.ts +75 -0
  61. package/src/@types/swagger.d.ts +23 -0
  62. package/{bin/extras/plata-create-api.ts → src/bin/extras/create-api-cli.ts} +5 -6
  63. package/{bin/extras/plata-create-lib.ts → src/bin/extras/create-lib-cli.ts} +3 -4
  64. package/{bin → src/bin}/extras/plata-create-tools.ts +4 -4
  65. package/src/bin/plata-api.ts +172 -0
  66. package/src/bin/plata-create.ts +21 -0
  67. package/src/bin/plata-runtime.ts +188 -0
  68. package/src/bin/plata-swagger.ts +100 -0
  69. package/src/bin/runtime/_setupRuntime.ts +49 -0
  70. package/src/bin/runtime/_types.d.ts +4 -0
  71. package/src/bin/runtime/class.ts +21 -0
  72. package/src/bin/runtime/dirs.ts +26 -0
  73. package/src/bin/runtime/promises.ts +15 -0
  74. package/src/bin/runtime/require.ts +104 -0
  75. package/{index.ts → src/index.ts} +2 -4
  76. package/{libs → src/libs}/axios.ts +0 -0
  77. package/src/libs/cluster.ts +189 -0
  78. package/src/libs/fs.ts +382 -0
  79. package/{libs/model.ts → src/libs/model-validations.ts} +28 -262
  80. package/src/libs/model.ts +233 -0
  81. package/src/libs/router.ts +147 -0
  82. package/src/libs/swagger.ts +81 -0
  83. package/{libs → src/libs}/tasks.ts +0 -0
  84. package/{libs → src/libs}/tools.ts +3 -18
  85. package/src/scripts/post-install/api.ts +32 -0
  86. package/src/scripts/post-install/lib.ts +30 -0
  87. package/src/scripts/post-install.ts +65 -0
  88. package/src/scripts/pre-test.ts +34 -0
  89. package/src/tests/assets/config/test.txt +1 -0
  90. package/src/tests/config.test.ts +13 -0
  91. package/src/tests/model.test.ts +115 -0
  92. package/templates/create-cli/cluster.ts +7 -9
  93. package/templates/create-cli/config.ts +2 -8
  94. package/templates/create-cli/lib.ts +7 -17
  95. package/templates/create-cli/model.ts +10 -21
  96. package/templates/create-cli/route.ts +1 -3
  97. package/templates/postinstall/api/configs/env.ts +2 -8
  98. package/templates/postinstall/api/tsconfig.json +20 -37
  99. package/templates/postinstall/lib/postinstall-tools.mjs +1 -1
  100. package/templates/postinstall/lib/postinstall.js +1 -0
  101. package/templates/postinstall/lib/tsconfig.json +21 -38
  102. package/tsconfig.json +25 -37
  103. package/Dockerfile +0 -13
  104. package/bin/extras/plata-build-tool.ts +0 -151
  105. package/bin/plata-build.ts +0 -144
  106. package/bin/plata-create.ts +0 -28
  107. package/bin/plata-reload.ts +0 -13
  108. package/bin/plata-swagger-gen.ts +0 -183
  109. package/bin/plata.ts +0 -122
  110. package/libs/cluster.ts +0 -219
  111. package/libs/env.ts +0 -28
  112. package/libs/routes.ts +0 -275
  113. package/libs/swagger.ts +0 -79
  114. package/postinstall-tools.mjs +0 -115
  115. package/postinstall.mjs +0 -42
  116. package/templates/postinstall/api/_install.mjs +0 -34
  117. package/templates/postinstall/lib/_install.mjs +0 -30
@@ -0,0 +1,69 @@
1
+ declare namespace Model {
2
+
3
+ type ValidateReturn = PlataError | null
4
+
5
+ interface PrimitiveValidationTypeReturn {
6
+ error?: PlataError
7
+ continua: boolean
8
+ }
9
+
10
+ type PrimitiveValidationType<T = any, D = undefined> =
11
+ (nome: string, valor: T | D) => Promise<PrimitiveValidationTypeReturn>
12
+ ;
13
+
14
+ interface Template {
15
+ readonly [name: string]:
16
+ readonly PrimitiveValidationType<unknown, unknown>[] |
17
+ readonly Template[] |
18
+ Template |
19
+ readonly (readonly PrimitiveValidationType[])[]
20
+ }
21
+
22
+ type GetTemplateParamType<T> =
23
+ T extends readonly [ PrimitiveValidationType<infer G, infer H> ] ? G | H :
24
+ T extends readonly [ PrimitiveValidationType<any, infer H>, PrimitiveValidationType<infer G, any> ] ? G | H :
25
+ T extends readonly [ PrimitiveValidationType<any, infer H>, ...any[], PrimitiveValidationType<infer G, any> ] ? G | H :
26
+ never
27
+ ;
28
+
29
+ type ExtractTemplateParamType<T> = Exclude<GetTemplateParamType<T>, undefined>
30
+
31
+ type ExtractTemplateType<T extends Template> = {
32
+ [P in keyof T]: T[P] extends Template ? ExtractTemplateType<T[P]> :
33
+ T[P] extends readonly Template[] ? ExtractTemplateType<T[P][0]>[] :
34
+ T[P] extends readonly (readonly PrimitiveValidationType[])[] ? ExtractTemplateParamType<T[P][0]>[] :
35
+ T[P] extends readonly PrimitiveValidationType<unknown, unknown>[] ? ExtractTemplateParamType<T[P]> :
36
+ number | boolean | string | null
37
+ }
38
+
39
+ type ExtractTemplateTypeNotValid<T extends Template> = {
40
+ [P in keyof T]: T[P] extends Template ? ExtractTemplateTypeNotValid<T[P]> :
41
+ T[P] extends readonly Template[] ? ExtractTemplateTypeNotValid<T[P][0]>[] :
42
+ T[P] extends readonly (readonly PrimitiveValidationType[])[] ? (number | boolean | string | null)[] :
43
+ number | boolean | string | null
44
+ }
45
+
46
+ type ParcialTemplateType<T extends Template> = Partial<ExtractTemplateType<T>>
47
+
48
+ type ModelTemplateValidation<T extends Template> = (value: ExtractTemplateType<T>) => Promise<PlataError | null>
49
+
50
+ type ModelTemplateFilter<T extends Template> = (value: ExtractTemplateTypeNotValid<T>) => ExtractTemplateTypeNotValid<T>
51
+
52
+ type ModelValidateReturn<T extends Template> = {
53
+ errors: undefined
54
+ value: ExtractTemplateType<T>
55
+ } | {
56
+ errors: PlataError[]
57
+ value: ExtractTemplateTypeNotValid<T>
58
+ }
59
+
60
+ type ConvertFunction<T extends Template, O> = (x: ExtractTemplateType<T>) => O
61
+
62
+ type Converters<T extends Template> = (AnyRecord<Model.ConvertFunction<T, any>>)
63
+
64
+ type GetConverterType<T extends Template, F> = F extends ConvertFunction<T, infer G> ? G : never
65
+
66
+ type ModelConvertFuntion<T extends Template, C extends Converters<T>> =
67
+ <K extends keyof C>(value: ExtractTemplateType<T>, to: K) => PlataResult<GetConverterType<T, C[K]>>
68
+ ;
69
+ }
@@ -0,0 +1,75 @@
1
+ /// <reference types="express" />
2
+
3
+ import express from 'express'
4
+
5
+ declare global {
6
+ namespace Router {
7
+ interface Request extends express.Request {
8
+ user: any
9
+ extras: any
10
+ }
11
+
12
+ interface Response extends express.Response {
13
+ oldJson(body?: any): this
14
+ error(error: PlataError | PlataError[]): this
15
+ }
16
+
17
+ type RequestHandler = (req: Request, res: Response, next: express.NextFunction) => Promise<any>
18
+
19
+ type HttpMethods =
20
+ "all"
21
+ | "get"
22
+ | "post"
23
+ | "put"
24
+ | "delete"
25
+ | "patch"
26
+ | "options"
27
+ | "head"
28
+ | "checkout"
29
+ | "connect"
30
+ | "copy"
31
+ | "lock"
32
+ | "merge"
33
+ | "mkactivity"
34
+ | "mkcol"
35
+ | "move"
36
+ | "notify"
37
+ | "propfind"
38
+ | "proppatch"
39
+ | "purge"
40
+ | "report"
41
+ | "search"
42
+ | "subscribe"
43
+ | "trace"
44
+ | "unlock"
45
+ | "unsubscribe"
46
+ | "use"
47
+ ;
48
+
49
+ type RouterFunction = (
50
+ (path: string | RequestHandler, ...handlers: RequestHandler[]) => void | Promise<void>
51
+ )
52
+
53
+ interface Route {
54
+ path?: string
55
+ method: string
56
+ handlers: RequestHandler[],
57
+ swaggerHide?: boolean | undefined
58
+ }
59
+
60
+ type RouterConfig = {
61
+ swaggerHide?: boolean
62
+ routes: Route[]
63
+ }
64
+
65
+ type Router = RouterConfig & {
66
+ [method in HttpMethods]: RouterFunction
67
+ }
68
+
69
+ type RouterBuilder = (r: Router) => Promise<Router>
70
+
71
+ export interface RequiredRoute extends RequiredInterface<RouterBuilder> {
72
+ httpRoute: string
73
+ }
74
+ }
75
+ }
@@ -0,0 +1,23 @@
1
+ declare namespace SwaggerGen {
2
+ interface RouteParameter {
3
+ name: string,
4
+ required: boolean,
5
+ in: 'path',
6
+ type: 'string'
7
+ }
8
+
9
+ interface Route {
10
+ httpRoute: string
11
+ method: string
12
+ params: RouteParameter[]
13
+ }
14
+
15
+ interface Files {
16
+ swaggerHeader: any
17
+ route: {
18
+ header: any,
19
+ body: any,
20
+ response: any,
21
+ }
22
+ }
23
+ }
@@ -1,5 +1,4 @@
1
1
  import { tools } from "./plata-create-tools";
2
- import { PlataDirs } from "../../libs/tools"
3
2
  import { Command } from 'commander'
4
3
  import path from 'node:path'
5
4
 
@@ -7,7 +6,7 @@ const program = new Command()
7
6
 
8
7
  program.name('Plata Create cli')
9
8
  program.description('CLI usada para criar rotas, libs, models e muito mais na plata')
10
- program.version(PlataDirs.PlataJson.version)
9
+ program.version(Plata.PlataJson.version)
11
10
 
12
11
  program.command('route <routes...>')
13
12
  .description('Cria uma rota utilizando o templete da plata')
@@ -17,7 +16,7 @@ program.command('route <routes...>')
17
16
  }
18
17
 
19
18
  const promises: any[] = []
20
- const plataName = PlataDirs.ProjectJson.plata_name
19
+ const plataName = Plata.ProjectJson.plata_name
21
20
 
22
21
  for (const route of routes) {
23
22
  const r = `${route}/`.replace(/:(.*?)(?:\/|$)/g, (_, parm) => {
@@ -103,7 +102,7 @@ program.command('model <models...>')
103
102
  }
104
103
 
105
104
  const promises: any[] = []
106
- const plataName = PlataDirs.ProjectJson.plata_name
105
+ const plataName = Plata.ProjectJson.plata_name
107
106
 
108
107
  for (const model of models) {
109
108
  promises.push(tools.files.deployFileToProject(
@@ -126,7 +125,7 @@ program.command('task <tasks...>')
126
125
  }
127
126
 
128
127
  const promises: any[] = []
129
- const plataName = PlataDirs.ProjectJson.plata_name
128
+ const plataName = Plata.ProjectJson.plata_name
130
129
 
131
130
  for (const task of tasks) {
132
131
  promises.push(tools.files.deployFileToProject(
@@ -147,7 +146,7 @@ program.command('cluster <clusters...>')
147
146
  if (!Array.isArray(clusters)) return
148
147
 
149
148
  const promises: any[] = []
150
- const plataName = PlataDirs.ProjectJson.plata_name
149
+ const plataName = Plata.ProjectJson.plata_name
151
150
 
152
151
  for (const cluster of clusters) {
153
152
  promises.push(tools.files.deployFileToProject(
@@ -1,12 +1,11 @@
1
1
  import { tools } from "./plata-create-tools";
2
- import { PlataDirs } from "../../libs/tools"
3
2
  import { Command } from 'commander'
4
3
 
5
4
  const program = new Command()
6
5
 
7
6
  program.name('Plata Create cli')
8
7
  program.description('CLI usada para criar rotas, libs, models e muito mais na plata')
9
- program.version(PlataDirs.PlataJson.version)
8
+ program.version(Plata.PlataJson.version)
10
9
 
11
10
  program.command('lib <libs...>')
12
11
  .description('Cria uma config com e uma lib utilizando o templete da plata')
@@ -68,7 +67,7 @@ program.command('model <models...>')
68
67
  }
69
68
 
70
69
  const promises: any[] = []
71
- const plataName = PlataDirs.ProjectJson.plata_name
70
+ const plataName = Plata.ProjectJson.plata_name
72
71
 
73
72
  for (const model of models) {
74
73
  promises.push(tools.files.deployFileToProject(
@@ -91,7 +90,7 @@ program.command('task <tasks...>')
91
90
  }
92
91
 
93
92
  const promises: any[] = []
94
- const plataName = PlataDirs.ProjectJson.plata_name
93
+ const plataName = Plata.ProjectJson.plata_name
95
94
 
96
95
  for (const task of tasks) {
97
96
  promises.push(tools.files.deployFileToProject(
@@ -34,7 +34,7 @@ export namespace tools {
34
34
 
35
35
  export async function copyFileToProject(projectFolder: string, templateFile: string, fileName: string): Promise<string> {
36
36
  const s = path.resolve(PlataDirs.getPlataTempleteDir('create-cli', `${templateFile}.ts`))
37
- let d = path.resolve(PlataDirs.getProjectDir(), projectFolder)
37
+ let d = path.resolve(Plata.ProjectDir, projectFolder)
38
38
 
39
39
  await mkdirIfNotExists(d)
40
40
  d = path.join(d, fileName)
@@ -58,13 +58,13 @@ export namespace tools {
58
58
  // Procura por texto para subistituir esse texto que esta no formato ç__PARAMETRO__ç
59
59
  let lastIndex = 0
60
60
  while(lastIndex !== -1) {
61
- lastIndex = line.indexOf('ç__', lastIndex)
61
+ lastIndex = line.indexOf('$__', lastIndex)
62
62
 
63
63
  if (lastIndex !== -1) {
64
- const pIndex = line.indexOf('__ç', lastIndex)
64
+ const pIndex = line.indexOf('__$', lastIndex)
65
65
  const param = line.slice(lastIndex + 3, pIndex)
66
66
 
67
- line = line.replace(new RegExp(__${param}__ç`, 'g'), args[param])
67
+ line = line.replace(new RegExp(`\\$__${param}__\\$`, 'g'), args[param])
68
68
  }
69
69
  }
70
70
 
@@ -0,0 +1,172 @@
1
+ import express from 'express'
2
+ import { PlataClusterManager } from '++/libs/cluster'
3
+ import { createServer } from 'node:https'
4
+ import fs from 'node:fs/promises'
5
+ import path from 'node:path'
6
+ import { buildExpressRouter, loadRoutesFromProject } from '++/libs/router'
7
+
8
+ export const main = async () => {
9
+ const cluster = new PlataClusterManager()
10
+
11
+ if (cluster.isPrimary()) {
12
+
13
+ let workers: number | undefined = undefined
14
+
15
+ if (Plata.config._PLATA_API_WORKERS !== undefined) {
16
+ workers = +Plata.config._PLATA_API_WORKERS || undefined
17
+ }
18
+
19
+ const clustersPromise: RequireFolderReturn<{ default: Cluster.WorkerConfig }> = require("@@/clusters/*.*")
20
+
21
+ cluster.startCluster({
22
+ name: '__PLATA_EXPRESS__',
23
+ env: Plata.config.ENV ?? 'prod',
24
+ onStart: async () => {},
25
+ workers: workers,
26
+ })
27
+
28
+ const clusters = await clustersPromise
29
+
30
+ if (clusters.errorID !== undefined) {
31
+ console.log(clusters)
32
+ process.exit(0)
33
+ }
34
+ // start Clusters
35
+ {
36
+ const promises: any = []
37
+
38
+ clusters.forEach(c => {
39
+ const config = c.exports.default
40
+ promises.push(cluster.startCluster(config).then(r => {
41
+ if (r !== null) {
42
+ console.log(r)
43
+ process.exit(0)
44
+ }
45
+ }))
46
+ })
47
+
48
+ await promises
49
+ }
50
+ } else {
51
+ if (Plata.config._PLATA_WORKER_NAME === '__PLATA_EXPRESS__') {
52
+ const projectRoutesPromise = Plata.FastPromise(() => loadRoutesFromProject())
53
+ const app = express()
54
+
55
+ app.disable('x-powered-by')
56
+
57
+ const apiRoots = Plata.config._PLATA_API_ROOT ?? '/api'
58
+
59
+ app.use(express.json({ limit: Plata.config._PLATA_API_JSON_SIZE ?? '100kb' }))
60
+
61
+
62
+ const requiredRoutes = await projectRoutesPromise
63
+
64
+ if (requiredRoutes.errorID !== undefined) {
65
+ console.log(requiredRoutes)
66
+
67
+ await cluster.send({
68
+ action: 'KILL',
69
+ msg: 'Erro enquanto carregava as rotas'
70
+ })
71
+
72
+ return
73
+ }
74
+
75
+ {
76
+ const result = await buildExpressRouter(requiredRoutes)
77
+
78
+ if (result.errorID !== undefined) {
79
+ console.log(result)
80
+
81
+ await cluster.send({
82
+ action: 'KILL',
83
+ msg: 'Erro enquanto carregava as rotas'
84
+ })
85
+
86
+ return
87
+ }
88
+
89
+ app.use(apiRoots.split(','), result as any)
90
+ }
91
+
92
+ app.use((err, _req, res, _next) => {
93
+ return res.status(500).json({
94
+ errorID: 'PRAPI0001',
95
+ error: 'Erro interno inesperado',
96
+ msg: err.message
97
+ })
98
+ })
99
+
100
+ app.all('*', (req, res) => {
101
+ return res.status(404).json({
102
+ errorID: 'PRAPI0002',
103
+ error: 'Rota não encontrada',
104
+ msg: req.path
105
+ })
106
+ })
107
+
108
+ const port = process.env.PORT ?? 3050
109
+
110
+ if (!Plata.config._PLATA_API_SSL_KEY || !Plata.config._PLATA_API_SSL_CERT) {
111
+
112
+ console.log(`Nenhum certificado configurado na env ${process.env.ENV}:`)
113
+ console.log(`_PLATA_API_SSL_KEY: ${process.env._PLATA_API_SSL_KEY}`)
114
+ console.log(`_PLATA_API_SSL_CERT: ${process.env._PLATA_API_SSL_CERT}`)
115
+
116
+ app.listen(port, () => {
117
+ console.log(`Iniciando Worker Express na porta ${port}`)
118
+ setTimeout(() => process.removeAllListeners('exit'), 500)
119
+ })
120
+
121
+ } else {
122
+
123
+ console.log('Iniciando a Plata com ssl usando os arquivos:')
124
+ console.log(`key: ${process.env._PLATA_API_SSL_KEY}`)
125
+ console.log(`cert: ${process.env._PLATA_API_SSL_CERT}`)
126
+
127
+ const [ cert, key ] = await Promise.all([
128
+ fs.readFile(path.normalize(path.join(
129
+ Plata.ProjectDir,
130
+ Plata.config._PLATA_API_SSL_CERT
131
+ ))),
132
+ fs.readFile(path.normalize(path.join(
133
+ Plata.ProjectDir,
134
+ Plata.config._PLATA_API_SSL_KEY
135
+ )))
136
+ ]).catch(err => {
137
+ console.log({
138
+ errorID: 'PRAPI0003',
139
+ msg: 'Erro ao ler o certifica e chave ssl',
140
+ error: err
141
+ } satisfies PlataError)
142
+
143
+ process.exit(1)
144
+ })
145
+
146
+ const https = createServer({
147
+ cert,
148
+ key,
149
+ passphrase: process.env._PLATA_API_SSL_PASS
150
+ }, app)
151
+
152
+ https.listen(port, () => {
153
+ console.log(`Iniciando Worker Express na porta ${port} com SSL`)
154
+ setTimeout(() => process.removeAllListeners('exit'), 500)
155
+ })
156
+ }
157
+ } else {
158
+ if (Plata.config._PLATA_WORKER_NAME === undefined) {
159
+ await cluster.send({
160
+ action: 'KILL',
161
+ msg: 'tried to start a Worker without _PLATA_WORKER_NAME'
162
+ })
163
+
164
+ return
165
+ }
166
+
167
+ const c: { default: Cluster.WorkerConfig } = require(`@@/clusters/${Plata.config._PLATA_WORKER_NAME}`)
168
+
169
+ await c.default.onStart()
170
+ }
171
+ }
172
+ }
@@ -0,0 +1,21 @@
1
+ export const main = async () => {
2
+ if (Plata.ProjectJson.plata_no_setup !== undefined) {
3
+ console.log('Plata not configurated remove plata_no_setup from package.json')
4
+ process.exit(0)
5
+ }
6
+
7
+ const args = process.argv.slice(process.argv.indexOf('+'))
8
+
9
+ switch (Plata.ProjectJson.plata_type ?? 'api') {
10
+ case 'api':
11
+ await (require('++/bin/extras/create-api-cli') as CreateCli.ImportedCreateCli).cli.parseAsync(args)
12
+ break
13
+ case 'lib':
14
+ await (require('++/bin/extras/create-lib-cli') as CreateCli.ImportedCreateCli).cli.parseAsync(args)
15
+ break
16
+ default:
17
+ console.log(`${Plata.ProjectJson.plata_type} not supported`)
18
+ process.exit(0)
19
+ break
20
+ }
21
+ }
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env node
2
+
3
+ import path from 'node:path'
4
+ import fs from 'node:fs'
5
+ import { ok } from 'node:assert'
6
+ import readline from 'node:readline'
7
+ import cluster from 'node:cluster'
8
+ import { build } from 'tsc-prog'
9
+ import glob from 'glob'
10
+ import { loadRuntimeLibs } from './runtime/_setupRuntime'
11
+
12
+ export function compile() {
13
+ if (!cluster.isPrimary) return
14
+
15
+ build({
16
+ basePath: Plata.ProjectDir,
17
+ configFilePath: 'tsconfig.json',
18
+ compilerOptions: {
19
+ newLine: 'LF',
20
+ rootDir: '.'
21
+ },
22
+ include: [
23
+ './**/*'
24
+ ],
25
+ exclude: [
26
+ './__BUILD__',
27
+ './node_modules',
28
+ './.vscode'
29
+ ],
30
+ copyOtherToOutDir: true,
31
+ clean: {
32
+ outDir: true,
33
+ declarationDir: true,
34
+ outFile: true
35
+ },
36
+ })
37
+ }
38
+
39
+ const main = async () => {
40
+ const g = global as any
41
+
42
+ g.Plata = await loadRuntimeLibs()
43
+
44
+ g.Plata.files = new Object(null)
45
+
46
+ g.Plata.files.ReadFileSync = (file: string, callback: (line: string) => string): PlataPromise<string> => {
47
+ return new Promise(resolve => {
48
+ try {
49
+ const content: string[] = []
50
+ const stream = readline.createInterface({
51
+ input: fs.createReadStream(file),
52
+ crlfDelay: Infinity
53
+ })
54
+
55
+ stream.on('close', () => {
56
+ resolve(content.join('\n'))
57
+ })
58
+
59
+ stream.on('line', (line) => {
60
+ content.push(callback(line))
61
+ })
62
+
63
+ } catch(e) {
64
+ resolve({
65
+ errorID: 'PLTRF0004',
66
+ msg: `Error while reading file: ${file}`,
67
+ error: e
68
+ })
69
+ }
70
+ })
71
+ }
72
+
73
+ g.Plata.files.ReadFileAsync = async (file: string, callback: (line: string) => Promise<void>): Promise<MaybePlataError> => {
74
+ return new Promise(resolve => {
75
+ try {
76
+ const promises: any = []
77
+
78
+ const stream = readline.createInterface({
79
+ input: fs.createReadStream(file),
80
+ crlfDelay: Infinity
81
+ })
82
+
83
+ stream.on('close', () => {
84
+ Promise.all(promises).then(
85
+ () => resolve(null),
86
+ e => resolve({
87
+ errorID: 'PPFRFA0002',
88
+ msg: `Unexpected error while reading file: ${file}`,
89
+ error: e
90
+ }),
91
+ )
92
+ })
93
+
94
+ stream.on('line', line => {
95
+ promises.push(Plata.FastPromise(() => callback(line)))
96
+ })
97
+
98
+ } catch (e) {
99
+ return resolve({
100
+ errorID: 'PPFRFA0001',
101
+ msg: `Unexpected error while reading file: ${file}`,
102
+ error: e
103
+ })
104
+ }
105
+ })
106
+ }
107
+
108
+ g.Plata.files.FindFiles = async (folders: string[], file: string): Promise<string[]> => {
109
+ const files: string[] = []
110
+
111
+ for (const folder of folders) {
112
+ files.push(...glob.sync(`${folder.replace(/\\/g, '/')}/**/${file}`))
113
+ }
114
+
115
+ return files
116
+ }
117
+
118
+ compile()
119
+
120
+ module.constructor.prototype.require = function (pathRequire) {
121
+ const self = this;
122
+ ok(typeof pathRequire === 'string', 'path must be a string');
123
+ ok(pathRequire, 'missing path');
124
+
125
+ try {
126
+ switch (pathRequire.slice(0,2)) {
127
+ case '@@':
128
+ pathRequire = pathRequire.replace('@@', `${Plata.ProjectDir}/__BUILD__`)
129
+ break
130
+ case '++':
131
+ pathRequire = pathRequire.replace('++', `${Plata.PlataDir}/__BUILD__`)
132
+ break
133
+ }
134
+
135
+ pathRequire = pathRequire.replace(/\\/g, '/')
136
+
137
+ switch (path.extname(pathRequire)) {
138
+ case '.env':
139
+ return Plata.FastPromise(() => Plata.ReadEnvFileToPromise(pathRequire))
140
+ break
141
+ case '.*':
142
+ return Plata.FastPromise(() => Plata.RequireFolder(path.dirname(pathRequire)))
143
+ break
144
+ default:
145
+ return self.constructor._load(pathRequire, self)
146
+ break
147
+ }
148
+
149
+
150
+ } catch (err) {
151
+ // if module not found, we have nothing to do, simply throw it back.
152
+ if (err.code === 'MODULE_NOT_FOUND') {
153
+ throw err;
154
+ }
155
+ // resolve the path to get absolute path
156
+ pathRequire = path.resolve(__dirname, pathRequire)
157
+
158
+ // Write to log or whatever
159
+ console.log('Error in file: ' + pathRequire);
160
+ }
161
+ }
162
+
163
+ // inicializa a config da plata
164
+ g.Plata.config = new Object(null)
165
+
166
+ const configEnv: EnvConfig = require('@@/configs/env').envConfig
167
+ const envFilePromise: PlataPromise<any> = require(`@@/envs/${configEnv.env}.env`)
168
+
169
+ for (const key in process.env) {
170
+ g.Plata.config[key] = process.env[key]
171
+ }
172
+
173
+ const envFile = await envFilePromise
174
+
175
+ for (const key in envFile) {
176
+ g.Plata.config[key] = envFile[key]
177
+ }
178
+
179
+ // roda o sript solicitado
180
+ const run = process.argv[process.argv.indexOf('+') + 1]
181
+
182
+ const app: { main: () => Promise<void> } = require(`++/bin/${run}`)
183
+
184
+ await app.main()
185
+
186
+ }
187
+
188
+ main()