@mahameru/diatrema 0.0.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 (101) hide show
  1. package/README.md +1 -0
  2. package/container-error.cjs +45 -0
  3. package/container-error.cjs.map +1 -0
  4. package/container-error.d.cts +7 -0
  5. package/container-error.d.ts +7 -0
  6. package/container-error.js +22 -0
  7. package/container-error.js.map +1 -0
  8. package/container.cjs +322 -0
  9. package/container.cjs.map +1 -0
  10. package/container.d.cts +62 -0
  11. package/container.d.ts +62 -0
  12. package/container.js +289 -0
  13. package/container.js.map +1 -0
  14. package/diatrema.cjs +130 -0
  15. package/diatrema.cjs.map +1 -0
  16. package/diatrema.d.cts +73 -0
  17. package/diatrema.d.ts +71 -0
  18. package/diatrema.js +107 -0
  19. package/diatrema.js.map +1 -0
  20. package/event-emitter.cjs +68 -0
  21. package/event-emitter.cjs.map +1 -0
  22. package/event-emitter.d.cts +11 -0
  23. package/event-emitter.d.ts +11 -0
  24. package/event-emitter.js +45 -0
  25. package/event-emitter.js.map +1 -0
  26. package/helpers.cjs +93 -0
  27. package/helpers.cjs.map +1 -0
  28. package/helpers.d.cts +22 -0
  29. package/helpers.d.ts +22 -0
  30. package/helpers.js +67 -0
  31. package/helpers.js.map +1 -0
  32. package/http-server-error.cjs +44 -0
  33. package/http-server-error.cjs.map +1 -0
  34. package/http-server-error.d.cts +7 -0
  35. package/http-server-error.d.ts +7 -0
  36. package/http-server-error.js +21 -0
  37. package/http-server-error.js.map +1 -0
  38. package/http-server.cjs +382 -0
  39. package/http-server.cjs.map +1 -0
  40. package/http-server.d.cts +81 -0
  41. package/http-server.d.ts +81 -0
  42. package/http-server.js +359 -0
  43. package/http-server.js.map +1 -0
  44. package/index.cjs +66 -0
  45. package/index.cjs.map +1 -0
  46. package/index.d.cts +19 -0
  47. package/index.d.ts +19 -0
  48. package/index.js +19 -0
  49. package/index.js.map +1 -0
  50. package/logger.cjs +52 -0
  51. package/logger.cjs.map +1 -0
  52. package/logger.d.cts +9 -0
  53. package/logger.d.ts +9 -0
  54. package/logger.js +29 -0
  55. package/logger.js.map +1 -0
  56. package/mahameru-error.cjs +42 -0
  57. package/mahameru-error.cjs.map +1 -0
  58. package/mahameru-error.d.cts +5 -0
  59. package/mahameru-error.d.ts +5 -0
  60. package/mahameru-error.js +19 -0
  61. package/mahameru-error.js.map +1 -0
  62. package/mahameru-request.cjs +79 -0
  63. package/mahameru-request.cjs.map +1 -0
  64. package/mahameru-request.d.cts +3 -0
  65. package/mahameru-request.d.ts +3 -0
  66. package/mahameru-request.js +56 -0
  67. package/mahameru-request.js.map +1 -0
  68. package/mahameru-response.cjs +71 -0
  69. package/mahameru-response.cjs.map +1 -0
  70. package/mahameru-response.d.cts +17 -0
  71. package/mahameru-response.d.ts +17 -0
  72. package/mahameru-response.js +48 -0
  73. package/mahameru-response.js.map +1 -0
  74. package/mahameru-server-error.cjs +54 -0
  75. package/mahameru-server-error.cjs.map +1 -0
  76. package/mahameru-server-error.d.cts +19 -0
  77. package/mahameru-server-error.d.ts +19 -0
  78. package/mahameru-server-error.js +31 -0
  79. package/mahameru-server-error.js.map +1 -0
  80. package/module-error.cjs +46 -0
  81. package/module-error.cjs.map +1 -0
  82. package/module-error.d.cts +12 -0
  83. package/module-error.d.ts +12 -0
  84. package/module-error.js +23 -0
  85. package/module-error.js.map +1 -0
  86. package/package.json +40 -0
  87. package/route.cjs +128 -0
  88. package/route.cjs.map +1 -0
  89. package/route.d.cts +46 -0
  90. package/route.d.ts +46 -0
  91. package/route.js +105 -0
  92. package/route.js.map +1 -0
  93. package/scripts/preinstall.js +9 -0
  94. package/types-BRwWYiUN.d.ts +108 -0
  95. package/types-CipcRmc9.d.cts +108 -0
  96. package/types.cjs +40 -0
  97. package/types.cjs.map +1 -0
  98. package/types.d.cts +3 -0
  99. package/types.d.ts +3 -0
  100. package/types.js +16 -0
  101. package/types.js.map +1 -0
package/container.js ADDED
@@ -0,0 +1,289 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ import path, { basename, dirname, join, relative, resolve } from "node:path";
4
+ import { readdir } from "node:fs/promises";
5
+ import { dynamicRequire, exists } from "./helpers.js";
6
+ class Container {
7
+ static {
8
+ __name(this, "Container");
9
+ }
10
+ #initialized = false;
11
+ classes = /* @__PURE__ */ new Map();
12
+ _modules = /* @__PURE__ */ new Map();
13
+ _errorHandler;
14
+ _notFoundHandler;
15
+ _protectedRoutes = [];
16
+ dependencies;
17
+ _initiatorHandler;
18
+ options;
19
+ containerRegistry = /* @__PURE__ */ new Map();
20
+ constructor(arg1, arg2) {
21
+ if (typeof arg2 !== "undefined") {
22
+ this.options = this.buildOptions(arg1);
23
+ this.dependencies = arg2;
24
+ } else {
25
+ this.dependencies = arg1;
26
+ this.options = this.buildOptions();
27
+ }
28
+ }
29
+ get notFoundHandler() {
30
+ return this._notFoundHandler;
31
+ }
32
+ getRouteItems() {
33
+ return Array.from(this.containerRegistry.values()).filter((item) => item.type === "route").map((item) => item.item);
34
+ }
35
+ get middlewareHandler() {
36
+ return this.containerRegistry.values().find((item) => item.type === "middleware")?.item;
37
+ }
38
+ get errorHandler() {
39
+ return this._errorHandler;
40
+ }
41
+ get protectedRoutes() {
42
+ return this._protectedRoutes;
43
+ }
44
+ get initialized() {
45
+ return this.#initialized;
46
+ }
47
+ get mahameruContainer() {
48
+ const camelCaseName = /* @__PURE__ */ __name((name) => name.charAt(0).toLowerCase() + name.slice(1), "camelCaseName");
49
+ return new Proxy({}, {
50
+ get: /* @__PURE__ */ __name((_target, prop) => {
51
+ if (typeof prop !== "string")
52
+ return void 0;
53
+ for (const registry of this.containerRegistry.values()) {
54
+ if (registry.type === "module-service" || registry.type === "module-controller" || registry.type === "instance") {
55
+ const key = camelCaseName(registry.name);
56
+ if (key === prop) {
57
+ return registry.item;
58
+ }
59
+ }
60
+ }
61
+ return void 0;
62
+ }, "get")
63
+ });
64
+ }
65
+ async discover() {
66
+ await this.loadRoutes();
67
+ await this.loadInitiator();
68
+ await this.loadModules();
69
+ await this.loadMiddlewareHandler();
70
+ await this.loadNotFoundHandlers();
71
+ await this.loadErrorHandler();
72
+ await this.loadProtectedRoutes();
73
+ this.#initialized = true;
74
+ }
75
+ async loadRoutes(currentDir) {
76
+ const baseDir = this.options.routesPath;
77
+ if (!currentDir)
78
+ currentDir = baseDir;
79
+ const items = await readdir(currentDir, { withFileTypes: true }).catch((error) => {
80
+ if (error.code === "ENOENT")
81
+ return [];
82
+ throw error;
83
+ });
84
+ for (const item of items) {
85
+ const fullPath = join(currentDir, item.name);
86
+ if (item.isDirectory()) {
87
+ await this.loadRoutes(fullPath);
88
+ continue;
89
+ }
90
+ if (!item.isFile() || !["route.js", "route.ts"].includes(item.name))
91
+ continue;
92
+ await this.loadSingleRoute(fullPath, currentDir, baseDir, { parentPath: item.parentPath, name: item.name });
93
+ }
94
+ }
95
+ async loadSingleRoute(fullPath, currentDir, baseDir, item) {
96
+ const relativePath = relative(baseDir, currentDir);
97
+ let path2 = "/" + relativePath.replace(/\\/g, "/");
98
+ path2 = path2.replace(/\/+/g, "/");
99
+ if (path2.length > 1 && path2.endsWith("/"))
100
+ path2 = path2.slice(0, -1);
101
+ const paramNames = [];
102
+ const paramMatches = path2.match(/\[([^\]]+)\]/g);
103
+ if (paramMatches)
104
+ paramMatches.forEach((match) => {
105
+ paramNames.push(match.slice(1, -1));
106
+ });
107
+ const escaped = path2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
108
+ const regexPattern = escaped.replace(/\\\[([^\\\]]+)\\\]/g, "([^/]+)");
109
+ const regex = new RegExp(`^${regexPattern}$`);
110
+ const pathFS = resolve(fullPath);
111
+ const routeHandlers = await dynamicRequire(this.options.moduleType, fullPath, this.options.dev);
112
+ if (routeHandlers) {
113
+ this.containerRegistry.set(fullPath, {
114
+ name: dirname(item.parentPath),
115
+ path: fullPath,
116
+ type: "route",
117
+ item: {
118
+ paramNames: [...paramNames],
119
+ path: path2,
120
+ pathFS,
121
+ regex,
122
+ routeHandlers
123
+ }
124
+ });
125
+ return true;
126
+ }
127
+ return false;
128
+ }
129
+ async loadModules() {
130
+ const items = await readdir(this.options.modulesPath, { withFileTypes: true }).catch((error) => {
131
+ if (error.code === "ENOENT")
132
+ return [];
133
+ throw error;
134
+ });
135
+ for (const item of items) {
136
+ if (!item.isDirectory())
137
+ continue;
138
+ const directory = item;
139
+ let controllerPath;
140
+ const controllerPathCandidate = [
141
+ path.join(this.options.modulesPath, directory.name, `controller.js`),
142
+ path.join(this.options.modulesPath, directory.name, `controller.ts`)
143
+ ];
144
+ for (const candidate of controllerPathCandidate) {
145
+ if (await exists(candidate)) {
146
+ controllerPath = candidate;
147
+ break;
148
+ }
149
+ }
150
+ if (controllerPath && await exists(controllerPath)) {
151
+ const controllerModule = await dynamicRequire(this.options.moduleType, controllerPath, this.options.dev);
152
+ if (controllerModule) {
153
+ const { name, clazz } = this.getDefaultExportClass(controllerModule, controllerPath);
154
+ const item2 = new clazz(this.mahameruContainer);
155
+ const containerRegistryID = `${controllerPath}:${name}`;
156
+ if (!this.containerRegistry.has(containerRegistryID))
157
+ this.containerRegistry.set(containerRegistryID, {
158
+ name,
159
+ path: controllerPath,
160
+ type: "module-controller",
161
+ item: item2
162
+ });
163
+ }
164
+ }
165
+ let servicePath;
166
+ const servicePathCandidate = [
167
+ path.join(this.options.modulesPath, directory.name, `service.js`),
168
+ path.join(this.options.modulesPath, directory.name, `service.ts`)
169
+ ];
170
+ for (const candidate of servicePathCandidate) {
171
+ if (await exists(candidate)) {
172
+ servicePath = candidate;
173
+ break;
174
+ }
175
+ }
176
+ if (servicePath && await exists(servicePath)) {
177
+ const serviceModule = await dynamicRequire(this.options.moduleType, servicePath, this.options.dev);
178
+ if (serviceModule) {
179
+ const { name, clazz } = this.getDefaultExportClass(serviceModule, servicePath);
180
+ const item2 = new clazz(this.mahameruContainer);
181
+ const containerRegistryID = `${controllerPath}:${name}`;
182
+ if (!this.containerRegistry.has(containerRegistryID))
183
+ this.containerRegistry.set(containerRegistryID, {
184
+ name,
185
+ path: servicePath,
186
+ type: "module-service",
187
+ item: item2
188
+ });
189
+ }
190
+ }
191
+ }
192
+ }
193
+ async loadMiddlewareHandler() {
194
+ const middlawareHandlerPath = join(this.options.appPath, "middleware.js");
195
+ const result = await dynamicRequire(this.options.moduleType, middlawareHandlerPath, this.options.dev);
196
+ const containerID = `${middlawareHandlerPath}:default`;
197
+ if (!this.containerRegistry.has(containerID) && result?.default)
198
+ this.containerRegistry.set(containerID, {
199
+ name: "default",
200
+ path: middlawareHandlerPath,
201
+ type: "middleware",
202
+ item: result?.default
203
+ });
204
+ }
205
+ async loadNotFoundHandlers() {
206
+ const notFoundHandlerPath = join(this.options.appPath, "routes", "not-found.js");
207
+ this._notFoundHandler = await dynamicRequire(this.options.moduleType, notFoundHandlerPath, this.options.dev);
208
+ }
209
+ async loadErrorHandler() {
210
+ const errorHandlerPath = join(this.options.appPath, "error.js");
211
+ const result = await dynamicRequire(this.options.moduleType, errorHandlerPath, this.options.dev);
212
+ this._errorHandler = result?.default;
213
+ }
214
+ async loadProtectedRoutes() {
215
+ const middlewarePath = join(this.options.appPath, "middleware.js");
216
+ const result = await dynamicRequire(this.options.moduleType, middlewarePath, this.options.dev);
217
+ if (result && result.protectedRoutes)
218
+ this._protectedRoutes = result.protectedRoutes;
219
+ }
220
+ async loadInitiator() {
221
+ const initiatorPath = join(this.options.appPath, "initiator.js");
222
+ const result = await dynamicRequire(this.options.moduleType, initiatorPath, this.options.dev);
223
+ const handler = result?.default;
224
+ if (handler) {
225
+ this._initiatorHandler = handler;
226
+ const instances = await this._initiatorHandler();
227
+ Object.keys(instances).forEach((key) => {
228
+ this.containerRegistry.set(`${initiatorPath}:${key}`, {
229
+ name: key,
230
+ path: initiatorPath,
231
+ type: "instance",
232
+ item: instances[key]
233
+ });
234
+ });
235
+ }
236
+ }
237
+ async onFileChanged(filePath) {
238
+ filePath = filePath.endsWith(".ts") ? filePath.replace(".ts", ".js") : filePath;
239
+ if (filePath.includes("\\src\\"))
240
+ filePath = filePath.replace("\\src\\", `\\.mahameru\\`);
241
+ const found = this.containerRegistry.values().find((containerItem) => containerItem.path === filePath);
242
+ if (found) {
243
+ let module;
244
+ if (found.type === "route") {
245
+ return await this.loadSingleRoute(filePath, dirname(filePath), this.options.routesPath, { parentPath: dirname(filePath), name: basename(filePath) });
246
+ } else if (found.type === "middleware") {
247
+ module = await dynamicRequire(this.options.moduleType, filePath, this.options.dev);
248
+ if (module) {
249
+ this.containerRegistry.set(`${filePath}:default`, {
250
+ ...found,
251
+ item: module.default
252
+ });
253
+ return true;
254
+ }
255
+ }
256
+ }
257
+ return false;
258
+ }
259
+ getDefaultExportClass(module, filePath) {
260
+ const defaultExportName = Object.keys(module).find((key) => key === "default");
261
+ if (!defaultExportName)
262
+ throw new this.dependencies.ModuleError(`Module in file '${filePath}' does not have a default export.`, { path: filePath, moduleName: Object.keys(module)[0] });
263
+ return {
264
+ name: module[defaultExportName].name,
265
+ clazz: module[defaultExportName]
266
+ };
267
+ }
268
+ buildOptions(initialOptions) {
269
+ const appPath = join(process.cwd(), ".mahameru");
270
+ const defaultOptions = {
271
+ appPath,
272
+ modulesPath: join(appPath, "modules"),
273
+ moduleType: "esm",
274
+ dev: initialOptions?.dev ? true : false,
275
+ routesPath: join(appPath, "routes")
276
+ };
277
+ if (!initialOptions)
278
+ return defaultOptions;
279
+ return {
280
+ ...defaultOptions,
281
+ appPath,
282
+ ...initialOptions
283
+ };
284
+ }
285
+ }
286
+ export {
287
+ Container
288
+ };
289
+ //# sourceMappingURL=container.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/container.ts"],"sourcesContent":["import path, { basename, dirname, join, relative, resolve } from 'node:path';\nimport { readdir } from 'node:fs/promises';\n\nimport { dynamicRequire, exists } from './helpers';\nimport type { ContainerError } from './container-error';\nimport type { ClassConstructor, ContainerItemID, ContainerRegistry, ErrorHandler, HTTPMethod, InitiatorHandler, MahameruContainer, MahameruMiddleware, ProtectedRoute, RouteHandler, RouteItem } from './types';\nimport type { ModuleError } from './module-error';\n\n/**\n * Container options\n */\nexport type ContainerOptions = {\n modulesPath: string;\n routesPath: string;\n appPath: string;\n dev: boolean;\n moduleType: \"commonjs\" | \"esm\";\n}\n\nexport type ContainerDependencies = {\n dataSources?: Record<string, any>;\n ContainerError: typeof ContainerError;\n ModuleError: typeof ModuleError;\n}\n\nexport class Container {\n #initialized = false;\n protected classes = new Map<string, ClassConstructor>();\n protected _modules = new Map<ClassConstructor, any>();\n protected _errorHandler?: ErrorHandler;\n protected _notFoundHandler?: Record<HTTPMethod, RouteHandler>;\n protected _protectedRoutes: ProtectedRoute = [];\n protected dependencies: ContainerDependencies;\n protected _initiatorHandler?: InitiatorHandler;\n public readonly options: ContainerOptions;\n public containerRegistry: ContainerRegistry = new Map();\n\n constructor(dependencies: ContainerDependencies);\n constructor(initialOptions: Partial<ContainerOptions>, dependencies: ContainerDependencies);\n constructor(arg1: Partial<ContainerOptions> | ContainerDependencies, arg2?: ContainerDependencies) {\n if (typeof arg2 !== 'undefined') {\n this.options = this.buildOptions(arg1 as Partial<ContainerOptions>);\n this.dependencies = arg2;\n } else {\n this.dependencies = arg1 as ContainerDependencies;\n this.options = this.buildOptions();\n }\n }\n\n get notFoundHandler() {\n return this._notFoundHandler;\n }\n\n getRouteItems(): RouteItem[] {\n return Array.from(this.containerRegistry.values()).filter((item) => item.type === 'route').map((item) => item.item);\n }\n\n get middlewareHandler(): MahameruMiddleware | undefined {\n return this.containerRegistry.values().find((item) => item.type === 'middleware')?.item;\n }\n\n get errorHandler() {\n return this._errorHandler;\n }\n\n get protectedRoutes() {\n return this._protectedRoutes;\n }\n\n get initialized() {\n return this.#initialized;\n }\n\n get mahameruContainer(): MahameruContainer {\n const camelCaseName = (name: string) => name.charAt(0).toLowerCase() + name.slice(1);\n\n return new Proxy({} as Record<string, unknown>, {\n get: (_target, prop) => {\n if (typeof prop !== 'string')\n return undefined;\n\n for (const registry of this.containerRegistry.values()) {\n if (registry.type === 'module-service' || registry.type === 'module-controller' || registry.type === 'instance') {\n const key = camelCaseName(registry.name);\n\n if (key === prop) {\n return registry.item;\n }\n }\n }\n\n return undefined;\n }\n }) as MahameruContainer;\n\n\n // const instances = this.containerRegistry.values().find((item) => item.type === 'instance');\n\n // if (instances) {\n // (result as any) = {\n // ...result,\n // ...instances.item\n // };\n // }\n\n // return result;\n }\n\n async discover() {\n await this.loadRoutes();\n await this.loadInitiator();\n await this.loadModules();\n await this.loadMiddlewareHandler();\n await this.loadNotFoundHandlers();\n await this.loadErrorHandler();\n await this.loadProtectedRoutes();\n\n this.#initialized = true;\n }\n\n protected async loadRoutes(currentDir?: string) {\n const baseDir = this.options.routesPath;\n\n if (!currentDir)\n currentDir = baseDir;\n\n const items = await readdir(currentDir, { withFileTypes: true }).catch(error => {\n if (error.code === 'ENOENT')\n return [];\n\n throw error;\n });\n\n for (const item of items) {\n\n const fullPath = join(currentDir, item.name);\n\n if (item.isDirectory()) {\n await this.loadRoutes(fullPath);\n\n continue;\n }\n\n if (!item.isFile() || (!['route.js', 'route.ts'].includes(item.name)))\n continue;\n\n await this.loadSingleRoute(fullPath, currentDir, baseDir, { parentPath: item.parentPath, name: item.name })\n }\n }\n\n protected async loadSingleRoute(fullPath: string, currentDir: string, baseDir: string, item: { parentPath: string, name: string }): Promise<boolean> {\n const relativePath = relative(baseDir, currentDir);\n\n let path = '/' + relativePath.replace(/\\\\/g, '/');\n path = path.replace(/\\/+/g, '/');\n\n if (path.length > 1 && path.endsWith('/'))\n path = path.slice(0, -1);\n\n const paramNames: RouteItem['paramNames'] = [];\n const paramMatches = path.match(/\\[([^\\]]+)\\]/g);\n\n if (paramMatches)\n paramMatches.forEach((match) => {\n paramNames.push(match.slice(1, -1));\n });\n\n const escaped = path.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const regexPattern = escaped.replace(/\\\\\\[([^\\\\\\]]+)\\\\\\]/g, '([^/]+)');\n const regex = new RegExp(`^${regexPattern}$`);\n const pathFS = resolve(fullPath);\n const routeHandlers = await dynamicRequire<Record<HTTPMethod, RouteHandler>>(this.options.moduleType, fullPath, this.options.dev);\n\n if (routeHandlers) {\n this.containerRegistry.set(fullPath, {\n name: dirname(item.parentPath),\n path: fullPath,\n type: 'route',\n item: {\n paramNames: [...paramNames],\n path,\n pathFS,\n regex,\n routeHandlers\n }\n });\n\n return true;\n }\n\n return false;\n }\n\n protected async loadModules() {\n const items = await readdir(this.options.modulesPath, { withFileTypes: true }).catch(error => {\n if (error.code === 'ENOENT')\n return [];\n\n throw error;\n });\n\n for (const item of items) {\n if (!item.isDirectory())\n continue;\n\n const directory = item;\n\n let controllerPath;\n const controllerPathCandidate = [\n path.join(this.options.modulesPath, directory.name, `controller.js`),\n path.join(this.options.modulesPath, directory.name, `controller.ts`)\n ];\n\n for (const candidate of controllerPathCandidate) {\n if (await exists(candidate)) {\n controllerPath = candidate;\n break;\n }\n }\n\n if (controllerPath && await exists(controllerPath)) {\n const controllerModule = await dynamicRequire<Record<string, ClassConstructor>>(this.options.moduleType, controllerPath, this.options.dev);\n\n if (controllerModule) {\n const { name, clazz } = this.getDefaultExportClass(controllerModule, controllerPath);\n const item = new clazz(this.mahameruContainer);\n const containerRegistryID = `${controllerPath}:${name}`;\n\n if (!this.containerRegistry.has(containerRegistryID))\n this.containerRegistry.set(containerRegistryID, {\n name,\n path: controllerPath,\n type: 'module-controller',\n item\n })\n }\n }\n\n let servicePath;\n const servicePathCandidate = [\n path.join(this.options.modulesPath, directory.name, `service.js`),\n path.join(this.options.modulesPath, directory.name, `service.ts`)\n ];\n\n for (const candidate of servicePathCandidate) {\n if (await exists(candidate)) {\n servicePath = candidate;\n break;\n }\n }\n\n if (servicePath && await exists(servicePath)) {\n const serviceModule = await dynamicRequire<Record<string, ClassConstructor>>(this.options.moduleType, servicePath, this.options.dev);\n\n if (serviceModule) {\n const { name, clazz } = this.getDefaultExportClass(serviceModule, servicePath);\n const item = new clazz(this.mahameruContainer);\n const containerRegistryID = `${controllerPath}:${name}`;\n\n if (!this.containerRegistry.has(containerRegistryID))\n this.containerRegistry.set(containerRegistryID, {\n name,\n path: servicePath,\n type: 'module-service',\n item\n })\n }\n }\n }\n }\n\n protected async loadMiddlewareHandler() {\n const middlawareHandlerPath = join(this.options.appPath, 'middleware.js');\n const result = await dynamicRequire<Record<'default', MahameruMiddleware>>(this.options.moduleType, middlawareHandlerPath, this.options.dev);\n const containerID: ContainerItemID = `${middlawareHandlerPath}:default`;\n\n if (!this.containerRegistry.has(containerID) && result?.default)\n this.containerRegistry.set(containerID, {\n name: 'default',\n path: middlawareHandlerPath,\n type: 'middleware',\n item: result?.default\n });\n }\n\n protected async loadNotFoundHandlers() {\n const notFoundHandlerPath = join(this.options.appPath, 'routes', 'not-found.js');\n\n this._notFoundHandler = await dynamicRequire<Record<HTTPMethod, RouteHandler>>(this.options.moduleType, notFoundHandlerPath, this.options.dev);\n }\n\n protected async loadErrorHandler() {\n const errorHandlerPath = join(this.options.appPath, 'error.js');\n const result = await dynamicRequire<Record<'default', ErrorHandler>>(this.options.moduleType, errorHandlerPath, this.options.dev);\n\n this._errorHandler = result?.default;\n }\n\n protected async loadProtectedRoutes() {\n const middlewarePath = join(this.options.appPath, 'middleware.js');\n const result = await dynamicRequire<Record<'protectedRoutes' | 'default', ProtectedRoute>>(this.options.moduleType, middlewarePath, this.options.dev);\n\n if (result && result.protectedRoutes)\n this._protectedRoutes = result.protectedRoutes;\n }\n\n protected async loadInitiator() {\n const initiatorPath = join(this.options.appPath, 'initiator.js');\n const result = await dynamicRequire<Record<'default', InitiatorHandler>>(this.options.moduleType, initiatorPath, this.options.dev);\n const handler = result?.default;\n\n if (handler) {\n this._initiatorHandler = handler;\n const instances = await this._initiatorHandler();\n\n Object.keys(instances).forEach((key) => {\n this.containerRegistry.set(`${initiatorPath}:${key}`, {\n name: key,\n path: initiatorPath,\n type: 'instance',\n item: (instances as any)[key]\n })\n })\n }\n }\n\n public async onFileChanged(filePath: string): Promise<boolean> {\n filePath = filePath.endsWith('.ts') ? filePath.replace('.ts', '.js') : filePath;\n\n if (filePath.includes('\\\\src\\\\'))\n filePath = filePath.replace('\\\\src\\\\', `\\\\.mahameru\\\\`);\n\n const found = this.containerRegistry.values().find((containerItem) => containerItem.path === filePath);\n\n if (found) {\n let module;\n\n if (found.type === 'route') {\n return await this.loadSingleRoute(filePath, dirname(filePath), this.options.routesPath, { parentPath: dirname(filePath), name: basename(filePath) });\n } else if (found.type === 'middleware') {\n module = await dynamicRequire<Record<'default', MahameruMiddleware>>(this.options.moduleType, filePath, this.options.dev);\n\n if (module) {\n this.containerRegistry.set(`${filePath}:default`, {\n ...found,\n item: module.default\n });\n\n return true\n }\n }\n }\n\n return false;\n }\n\n protected getDefaultExportClass(module: Record<string, ClassConstructor<unknown>>, filePath: string) {\n const defaultExportName = Object.keys(module).find((key) => key === 'default');\n\n if (!defaultExportName)\n throw new this.dependencies.ModuleError(`Module in file '${filePath}' does not have a default export.`, { path: filePath, moduleName: Object.keys(module)[0] });\n\n return {\n name: module[defaultExportName].name,\n clazz: module[defaultExportName]\n };\n }\n\n protected buildOptions(initialOptions?: Partial<ContainerOptions>): ContainerOptions {\n const appPath = join(process.cwd(), '.mahameru');\n const defaultOptions: ContainerOptions = {\n appPath,\n modulesPath: join(appPath, 'modules'),\n moduleType: 'esm',\n dev: initialOptions?.dev ? true : false,\n routesPath: join(appPath, 'routes')\n };\n\n if (!initialOptions)\n return defaultOptions;\n\n return {\n ...defaultOptions,\n appPath,\n ...initialOptions\n };\n }\n}\n"],"mappings":";;AAAA,OAAO,QAAQ,UAAU,SAAS,MAAM,UAAU,eAAe;AACjE,SAAS,eAAe;AAExB,SAAS,gBAAgB,cAAc;AAsBhC,MAAM,UAAU;AAAA,EAzBvB,OAyBuB;AAAA;AAAA;AAAA,EACnB,eAAe;AAAA,EACL,UAAU,oBAAI,IAA8B;AAAA,EAC5C,WAAW,oBAAI,IAA2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,MAAM,EAAE,KAAK,CAAC,QAAQ,QAAQ,SAAS;AAE7E,QAAI,CAAC;AACD,YAAM,IAAI,KAAK,aAAa,YAAY,mBAAmB,QAAQ,qCAAqC,EAAE,MAAM,UAAU,YAAY,OAAO,KAAK,MAAM,EAAE,CAAC,EAAE,CAAC;AAElK,WAAO;AAAA,MACH,MAAM,OAAO,iBAAiB,EAAE;AAAA,MAChC,OAAO,OAAO,iBAAiB;AAAA,IACnC;AAAA,EACJ;AAAA,EAEU,aAAa,gBAA8D;AACjF,UAAM,UAAU,KAAK,QAAQ,IAAI,GAAG,WAAW;AAC/C,UAAM,iBAAmC;AAAA,MACrC;AAAA,MACA,aAAa,KAAK,SAAS,SAAS;AAAA,MACpC,YAAY;AAAA,MACZ,KAAK,gBAAgB,MAAM,OAAO;AAAA,MAClC,YAAY,KAAK,SAAS,QAAQ;AAAA,IACtC;AAEA,QAAI,CAAC;AACD,aAAO;AAEX,WAAO;AAAA,MACH,GAAG;AAAA,MACH;AAAA,MACA,GAAG;AAAA,IACP;AAAA,EACJ;AACJ;","names":["path","item"]}
package/diatrema.cjs ADDED
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var diatrema_exports = {};
21
+ __export(diatrema_exports, {
22
+ default: () => Diatrema,
23
+ diatremaDefaultConfig: () => diatremaDefaultConfig
24
+ });
25
+ module.exports = __toCommonJS(diatrema_exports);
26
+ var import_node_path = require("node:path");
27
+ var import_http_server = require('./http-server.cjs');
28
+ var import_event_emitter = require('./event-emitter.cjs');
29
+ const diatremaDefaultConfig = {
30
+ dev: false,
31
+ isStandalone: false,
32
+ rootPath: process.cwd(),
33
+ get appPath() {
34
+ if (this.isStandalone)
35
+ return this.rootPath;
36
+ return (0, import_node_path.join)(this.rootPath, this.dev ? this.developmentDir : this.productionDir);
37
+ },
38
+ productionDir: ".mahameru",
39
+ developmentDir: ".mahameru",
40
+ routesDir: "routes"
41
+ };
42
+ class Diatrema extends import_event_emitter.EventEmitter {
43
+ static {
44
+ __name(this, "Diatrema");
45
+ }
46
+ #initialized = false;
47
+ #isShuttingDown = false;
48
+ options = diatremaDefaultConfig;
49
+ dependencies;
50
+ constructor(arg1, arg2) {
51
+ super();
52
+ if (typeof arg2 !== "undefined")
53
+ this.options = { ...this.options, ...arg1 };
54
+ if (typeof arg2 !== "undefined") {
55
+ this.dependencies = arg2;
56
+ } else {
57
+ this.dependencies = arg1;
58
+ }
59
+ }
60
+ /**
61
+ * Indicates whether the Mahameru server has been initialized or not.
62
+ * @returns {boolean}
63
+ */
64
+ get initialized() {
65
+ return this.#initialized;
66
+ }
67
+ /**
68
+ * Indicates whether the Mahameru server is shutting down or not.
69
+ * @returns {boolean}
70
+ */
71
+ get isShuttingDown() {
72
+ return this.#isShuttingDown;
73
+ }
74
+ /**
75
+ * Initialize the Mahameru server.
76
+ */
77
+ async initialize() {
78
+ try {
79
+ if (this.#initialized)
80
+ return;
81
+ await this.dependencies.container.discover();
82
+ } catch (error) {
83
+ throw error;
84
+ }
85
+ const { port, host } = await this.dependencies.httpServer.listen();
86
+ this.#initialized = true;
87
+ this.emit("ready", { mode: this.options.dev ? "development" : "production", port, host });
88
+ }
89
+ /**
90
+ * Hot reload the middleware and routes when a file changes in development mode.
91
+ */
92
+ async devHRM(changedFile) {
93
+ if (!this.#initialized)
94
+ return;
95
+ if (changedFile) {
96
+ if (await this.dependencies.container.onFileChanged(changedFile))
97
+ this.dependencies.logger.debug(`File changed: ${changedFile}`);
98
+ }
99
+ }
100
+ /**
101
+ * Shut down the Mahameru server gracefully.
102
+ * @returns {Promise<void>}
103
+ */
104
+ async shutdown() {
105
+ if (this.#isShuttingDown)
106
+ return;
107
+ this.#isShuttingDown = true;
108
+ this.dependencies.logger.info("Shutting down Mahameru server...");
109
+ try {
110
+ this.dependencies.logger.info("Databases destroyed successfully.");
111
+ } catch (error) {
112
+ this.dependencies.logger.error("Error destroying databases", error);
113
+ }
114
+ if (this.dependencies.httpServer.listening) {
115
+ try {
116
+ await this.dependencies.httpServer.close();
117
+ this.dependencies.logger.info("HTTP server closed successfully.");
118
+ } catch (error) {
119
+ this.dependencies.logger.error("Error closing HTTP server", error);
120
+ }
121
+ }
122
+ this.#initialized = false;
123
+ this.dependencies.logger.info("Mahameru server shut down.");
124
+ }
125
+ }
126
+ // Annotate the CommonJS export names for ESM import in node:
127
+ 0 && (module.exports = {
128
+ diatremaDefaultConfig
129
+ });
130
+ //# sourceMappingURL=diatrema.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/diatrema.ts"],"sourcesContent":["import { join } from 'node:path';\n\nimport { HttpServer } from './http-server';\nimport { EventEmitter } from \"./event-emitter\";\n\nimport type { Container } from './container';\nimport type { Route } from './route';\nimport type { Logger } from './logger';\n\nexport type DiatremaEvents = {\n ready: [data: { mode: \"development\" | \"production\"; port: number; host: string; }];\n};\n\nexport type DiatremaOptions = {\n dev: boolean;\n isStandalone: boolean;\n rootPath: string;\n appPath: string;\n routesDir: string;\n productionDir: string;\n developmentDir: string;\n}\n\nexport type DiatremaDependencies = {\n container: Container;\n route: Route;\n httpServer: HttpServer;\n logger: Logger;\n};\n\nexport const diatremaDefaultConfig: DiatremaOptions = {\n dev: false,\n isStandalone: false,\n rootPath: process.cwd(),\n get appPath(): string {\n if (this.isStandalone)\n return this.rootPath;\n\n return join(this.rootPath, this.dev ? this.developmentDir : this.productionDir);\n },\n productionDir: '.mahameru',\n developmentDir: '.mahameru',\n routesDir: 'routes'\n}\n\n/**\n * Main Diatrema class that orchestrates the application lifecycle.\n */\nexport default class Diatrema extends EventEmitter<DiatremaEvents> {\n #initialized = false;\n #isShuttingDown = false;\n public readonly options: DiatremaOptions = diatremaDefaultConfig;\n protected readonly dependencies: DiatremaDependencies;\n\n constructor(dependencies: DiatremaDependencies)\n constructor(\n initialOptions: Partial<DiatremaOptions>,\n dependencies: DiatremaDependencies\n )\n constructor(\n arg1: Partial<DiatremaOptions> | DiatremaDependencies,\n arg2?: DiatremaDependencies\n ) {\n super();\n\n if (typeof arg2 !== 'undefined')\n this.options = { ...this.options, ...arg1 as Partial<DiatremaOptions> };\n\n if (typeof arg2 !== 'undefined') {\n this.dependencies = arg2;\n } else {\n this.dependencies = arg1 as DiatremaDependencies;\n }\n }\n\n /**\n * Indicates whether the Mahameru server has been initialized or not.\n * @returns {boolean}\n */\n get initialized() {\n return this.#initialized;\n }\n\n /**\n * Indicates whether the Mahameru server is shutting down or not.\n * @returns {boolean}\n */\n get isShuttingDown() {\n return this.#isShuttingDown;\n }\n\n /**\n * Initialize the Mahameru server.\n */\n async initialize(): Promise<void> {\n try {\n if (this.#initialized)\n return;\n\n await this.dependencies.container.discover();\n } catch (error) {\n throw error;\n }\n\n const { port, host } = await this.dependencies.httpServer.listen();\n this.#initialized = true;\n\n this.emit('ready', { mode: this.options.dev ? 'development' : 'production', port: port, host: host });\n }\n\n /**\n * Hot reload the middleware and routes when a file changes in development mode.\n */\n async devHRM(changedFile?: string) {\n if (!this.#initialized)\n return\n\n if (changedFile) {\n if (await this.dependencies.container.onFileChanged(changedFile))\n this.dependencies.logger.debug(`File changed: ${changedFile}`);\n }\n }\n\n /**\n * Shut down the Mahameru server gracefully.\n * @returns {Promise<void>}\n */\n async shutdown(): Promise<void> {\n if (this.#isShuttingDown)\n return\n\n this.#isShuttingDown = true;\n\n this.dependencies.logger.info('Shutting down Mahameru server...');\n\n try {\n this.dependencies.logger.info('Databases destroyed successfully.');\n } catch (error) {\n this.dependencies.logger.error('Error destroying databases', error);\n }\n\n if (this.dependencies.httpServer.listening) {\n try {\n await this.dependencies.httpServer.close();\n this.dependencies.logger.info('HTTP server closed successfully.');\n } catch (error) {\n this.dependencies.logger.error('Error closing HTTP server', error);\n }\n }\n\n this.#initialized = false;\n this.dependencies.logger.info('Mahameru server shut down.');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAqB;AAErB,yBAA2B;AAC3B,2BAA6B;AA2BtB,MAAM,wBAAyC;AAAA,EAClD,KAAK;AAAA,EACL,cAAc;AAAA,EACd,UAAU,QAAQ,IAAI;AAAA,EACtB,IAAI,UAAkB;AAClB,QAAI,KAAK;AACL,aAAO,KAAK;AAEhB,eAAO,uBAAK,KAAK,UAAU,KAAK,MAAM,KAAK,iBAAiB,KAAK,aAAa;AAAA,EAClF;AAAA,EACA,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,WAAW;AACf;AAKA,MAAO,iBAA+B,kCAA6B;AAAA,EAhDnE,OAgDmE;AAAA;AAAA;AAAA,EAC/D,eAAe;AAAA,EACf,kBAAkB;AAAA,EACF,UAA2B;AAAA,EACxB;AAAA,EAOnB,YACI,MACA,MACF;AACE,UAAM;AAEN,QAAI,OAAO,SAAS;AAChB,WAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,KAAiC;AAE1E,QAAI,OAAO,SAAS,aAAa;AAC7B,WAAK,eAAe;AAAA,IACxB,OAAO;AACH,WAAK,eAAe;AAAA,IACxB;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,cAAc;AACd,WAAO,KAAK;AAAA,EAChB;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ED
@@ -0,0 +1,73 @@
1
+ import { HttpServer } from './http-server.cjs';
2
+ import { EventEmitter } from './event-emitter.cjs';
3
+ import { Container } from './container.cjs';
4
+ import { Route } from './route.cjs';
5
+ import { Logger } from './logger.cjs';
6
+ import 'node:http';
7
+ import './mahameru-response.cjs';
8
+ import './types-CipcRmc9.cjs';
9
+ import './http-server-error.cjs';
10
+ import './mahameru-server-error.cjs';
11
+ import './container-error.cjs';
12
+ import './module-error.cjs';
13
+
14
+ type DiatremaEvents = {
15
+ ready: [data: {
16
+ mode: "development" | "production";
17
+ port: number;
18
+ host: string;
19
+ }];
20
+ };
21
+ type DiatremaOptions = {
22
+ dev: boolean;
23
+ isStandalone: boolean;
24
+ rootPath: string;
25
+ appPath: string;
26
+ routesDir: string;
27
+ productionDir: string;
28
+ developmentDir: string;
29
+ };
30
+ type DiatremaDependencies = {
31
+ container: Container;
32
+ route: Route;
33
+ httpServer: HttpServer;
34
+ logger: Logger;
35
+ };
36
+ declare const diatremaDefaultConfig: DiatremaOptions;
37
+ /**
38
+ * Main Diatrema class that orchestrates the application lifecycle.
39
+ */
40
+ declare class Diatrema extends EventEmitter<DiatremaEvents> {
41
+ #private;
42
+ readonly options: DiatremaOptions;
43
+ protected readonly dependencies: DiatremaDependencies;
44
+ constructor(dependencies: DiatremaDependencies);
45
+ constructor(initialOptions: Partial<DiatremaOptions>, dependencies: DiatremaDependencies);
46
+ /**
47
+ * Indicates whether the Mahameru server has been initialized or not.
48
+ * @returns {boolean}
49
+ */
50
+ get initialized(): boolean;
51
+ /**
52
+ * Indicates whether the Mahameru server is shutting down or not.
53
+ * @returns {boolean}
54
+ */
55
+ get isShuttingDown(): boolean;
56
+ /**
57
+ * Initialize the Mahameru server.
58
+ */
59
+ initialize(): Promise<void>;
60
+ /**
61
+ * Hot reload the middleware and routes when a file changes in development mode.
62
+ */
63
+ devHRM(changedFile?: string): Promise<void>;
64
+ /**
65
+ * Shut down the Mahameru server gracefully.
66
+ * @returns {Promise<void>}
67
+ */
68
+ shutdown(): Promise<void>;
69
+ }
70
+
71
+ // @ts-ignore
72
+ export = Diatrema;
73
+ export { type DiatremaDependencies, type DiatremaEvents, type DiatremaOptions, diatremaDefaultConfig };
package/diatrema.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ import { HttpServer } from './http-server.js';
2
+ import { EventEmitter } from './event-emitter.js';
3
+ import { Container } from './container.js';
4
+ import { Route } from './route.js';
5
+ import { Logger } from './logger.js';
6
+ import 'node:http';
7
+ import './mahameru-response.js';
8
+ import './types-BRwWYiUN.js';
9
+ import './http-server-error.js';
10
+ import './mahameru-server-error.js';
11
+ import './container-error.js';
12
+ import './module-error.js';
13
+
14
+ type DiatremaEvents = {
15
+ ready: [data: {
16
+ mode: "development" | "production";
17
+ port: number;
18
+ host: string;
19
+ }];
20
+ };
21
+ type DiatremaOptions = {
22
+ dev: boolean;
23
+ isStandalone: boolean;
24
+ rootPath: string;
25
+ appPath: string;
26
+ routesDir: string;
27
+ productionDir: string;
28
+ developmentDir: string;
29
+ };
30
+ type DiatremaDependencies = {
31
+ container: Container;
32
+ route: Route;
33
+ httpServer: HttpServer;
34
+ logger: Logger;
35
+ };
36
+ declare const diatremaDefaultConfig: DiatremaOptions;
37
+ /**
38
+ * Main Diatrema class that orchestrates the application lifecycle.
39
+ */
40
+ declare class Diatrema extends EventEmitter<DiatremaEvents> {
41
+ #private;
42
+ readonly options: DiatremaOptions;
43
+ protected readonly dependencies: DiatremaDependencies;
44
+ constructor(dependencies: DiatremaDependencies);
45
+ constructor(initialOptions: Partial<DiatremaOptions>, dependencies: DiatremaDependencies);
46
+ /**
47
+ * Indicates whether the Mahameru server has been initialized or not.
48
+ * @returns {boolean}
49
+ */
50
+ get initialized(): boolean;
51
+ /**
52
+ * Indicates whether the Mahameru server is shutting down or not.
53
+ * @returns {boolean}
54
+ */
55
+ get isShuttingDown(): boolean;
56
+ /**
57
+ * Initialize the Mahameru server.
58
+ */
59
+ initialize(): Promise<void>;
60
+ /**
61
+ * Hot reload the middleware and routes when a file changes in development mode.
62
+ */
63
+ devHRM(changedFile?: string): Promise<void>;
64
+ /**
65
+ * Shut down the Mahameru server gracefully.
66
+ * @returns {Promise<void>}
67
+ */
68
+ shutdown(): Promise<void>;
69
+ }
70
+
71
+ export { type DiatremaDependencies, type DiatremaEvents, type DiatremaOptions, Diatrema as default, diatremaDefaultConfig };