@miqro/core 1.6.1 → 1.7.2

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 (175) hide show
  1. package/README.md +101 -41
  2. package/dist/api-router.d.ts +1 -1
  3. package/dist/api-router.js +0 -1
  4. package/dist/app-utils.js +0 -1
  5. package/dist/app.js +2 -3
  6. package/dist/common/api-router-utils.d.ts +1 -1
  7. package/dist/common/api-router-utils.js +6 -22
  8. package/dist/common/api-router.d.ts +3 -16
  9. package/dist/common/api-router.js +0 -1
  10. package/dist/common/config/config.js +0 -1
  11. package/dist/common/config/featuretoggle.js +0 -1
  12. package/dist/common/config/index.js +0 -1
  13. package/dist/common/config/loader.js +0 -1
  14. package/dist/common/context.d.ts +1 -1
  15. package/dist/common/context.js +0 -1
  16. package/dist/common/error/badrequesterror.js +0 -1
  17. package/dist/common/error/configfilenotfound.js +0 -1
  18. package/dist/common/error/forbiddenerror.js +0 -1
  19. package/dist/common/error/index.js +0 -1
  20. package/dist/common/error/notfound.js +0 -1
  21. package/dist/common/error/notimplemented.js +0 -1
  22. package/dist/common/error/unauthorizederror.js +0 -1
  23. package/dist/common/helpers.js +0 -1
  24. package/dist/common/index.js +0 -1
  25. package/dist/common/logger/constants.d.ts +13 -0
  26. package/dist/common/logger/constants.js +25 -0
  27. package/dist/common/logger/factory.d.ts +2 -4
  28. package/dist/common/logger/factory.js +7 -4
  29. package/dist/common/logger/index.d.ts +5 -5
  30. package/dist/common/logger/index.js +5 -5
  31. package/dist/common/logger/{transport.d.ts → interfaces.d.ts} +6 -3
  32. package/dist/common/logger/interfaces.js +2 -0
  33. package/dist/common/logger/logger.d.ts +15 -7
  34. package/dist/common/logger/logger.js +35 -28
  35. package/dist/common/logger/transport/console.d.ts +5 -0
  36. package/dist/common/logger/transport/console.js +38 -0
  37. package/dist/common/logger/transport/file.d.ts +2 -0
  38. package/dist/common/logger/transport/file.js +28 -0
  39. package/dist/common/router-handler.js +0 -1
  40. package/dist/common/router-helpers.d.ts +1 -1
  41. package/dist/common/router-helpers.js +3 -4
  42. package/dist/common/router-utils.js +0 -1
  43. package/dist/common/session/common.js +0 -1
  44. package/dist/common/session/index.js +0 -1
  45. package/dist/common/session/service.js +0 -1
  46. package/dist/common/tokenize-match.js +0 -1
  47. package/dist/index.js +0 -1
  48. package/dist/middleware/buffer.js +0 -1
  49. package/dist/middleware/cookie.js +0 -1
  50. package/dist/middleware/cors.js +0 -1
  51. package/dist/middleware/form.js +0 -1
  52. package/dist/middleware/group.js +0 -1
  53. package/dist/middleware/index.js +0 -1
  54. package/dist/middleware/json.js +0 -1
  55. package/dist/middleware/logger.js +0 -1
  56. package/dist/middleware/parse.js +0 -1
  57. package/dist/middleware/result.js +0 -1
  58. package/dist/middleware/session.js +0 -1
  59. package/dist/middleware/tag.js +0 -1
  60. package/dist/middleware/text.js +0 -1
  61. package/dist/proxy.js +0 -1
  62. package/dist/router.d.ts +1 -1
  63. package/dist/router.js +2 -3
  64. package/dist/static.js +0 -1
  65. package/package.json +8 -10
  66. package/dist/api-router.js.map +0 -1
  67. package/dist/app-utils.js.map +0 -1
  68. package/dist/app.js.map +0 -1
  69. package/dist/common/api-router-utils.js.map +0 -1
  70. package/dist/common/api-router.js.map +0 -1
  71. package/dist/common/config/config.js.map +0 -1
  72. package/dist/common/config/featuretoggle.js.map +0 -1
  73. package/dist/common/config/index.js.map +0 -1
  74. package/dist/common/config/loader.js.map +0 -1
  75. package/dist/common/context.js.map +0 -1
  76. package/dist/common/error/badrequesterror.js.map +0 -1
  77. package/dist/common/error/configfilenotfound.js.map +0 -1
  78. package/dist/common/error/forbiddenerror.js.map +0 -1
  79. package/dist/common/error/index.js.map +0 -1
  80. package/dist/common/error/notfound.js.map +0 -1
  81. package/dist/common/error/notimplemented.js.map +0 -1
  82. package/dist/common/error/unauthorizederror.js.map +0 -1
  83. package/dist/common/helpers.js.map +0 -1
  84. package/dist/common/index.js.map +0 -1
  85. package/dist/common/logger/common.d.ts +0 -4
  86. package/dist/common/logger/common.js +0 -7
  87. package/dist/common/logger/common.js.map +0 -1
  88. package/dist/common/logger/factory.js.map +0 -1
  89. package/dist/common/logger/formatter.d.ts +0 -7
  90. package/dist/common/logger/formatter.js +0 -9
  91. package/dist/common/logger/formatter.js.map +0 -1
  92. package/dist/common/logger/index.js.map +0 -1
  93. package/dist/common/logger/logger.js.map +0 -1
  94. package/dist/common/logger/transport.js +0 -59
  95. package/dist/common/logger/transport.js.map +0 -1
  96. package/dist/common/router-handler.js.map +0 -1
  97. package/dist/common/router-helpers.js.map +0 -1
  98. package/dist/common/router-utils.js.map +0 -1
  99. package/dist/common/session/common.js.map +0 -1
  100. package/dist/common/session/index.js.map +0 -1
  101. package/dist/common/session/service.js.map +0 -1
  102. package/dist/common/tokenize-match.js.map +0 -1
  103. package/dist/index.js.map +0 -1
  104. package/dist/middleware/buffer.js.map +0 -1
  105. package/dist/middleware/cookie.js.map +0 -1
  106. package/dist/middleware/cors.js.map +0 -1
  107. package/dist/middleware/form.js.map +0 -1
  108. package/dist/middleware/group.js.map +0 -1
  109. package/dist/middleware/index.js.map +0 -1
  110. package/dist/middleware/json.js.map +0 -1
  111. package/dist/middleware/logger.js.map +0 -1
  112. package/dist/middleware/parse.js.map +0 -1
  113. package/dist/middleware/result.js.map +0 -1
  114. package/dist/middleware/session.js.map +0 -1
  115. package/dist/middleware/tag.js.map +0 -1
  116. package/dist/middleware/text.js.map +0 -1
  117. package/dist/proxy.js.map +0 -1
  118. package/dist/router.js.map +0 -1
  119. package/dist/static.js.map +0 -1
  120. package/src/api-router.ts +0 -60
  121. package/src/api-router.unit.test.js +0 -273
  122. package/src/app-utils.ts +0 -82
  123. package/src/app-utils.unit.test.js +0 -100
  124. package/src/app.ts +0 -51
  125. package/src/app.unit.test.js +0 -334
  126. package/src/common/api-router-utils.ts +0 -209
  127. package/src/common/api-router.ts +0 -32
  128. package/src/common/config/config.ts +0 -111
  129. package/src/common/config/featuretoggle.ts +0 -6
  130. package/src/common/config/index.ts +0 -3
  131. package/src/common/config/loader.ts +0 -80
  132. package/src/common/context.ts +0 -167
  133. package/src/common/context.unit.test.js +0 -288
  134. package/src/common/error/badrequesterror.ts +0 -6
  135. package/src/common/error/configfilenotfound.ts +0 -6
  136. package/src/common/error/forbiddenerror.ts +0 -6
  137. package/src/common/error/index.ts +0 -6
  138. package/src/common/error/notfound.ts +0 -6
  139. package/src/common/error/notimplemented.ts +0 -6
  140. package/src/common/error/unauthorizederror.ts +0 -6
  141. package/src/common/helpers.ts +0 -11
  142. package/src/common/index.ts +0 -7
  143. package/src/common/logger/common.ts +0 -6
  144. package/src/common/logger/factory.ts +0 -51
  145. package/src/common/logger/formatter.ts +0 -9
  146. package/src/common/logger/index.ts +0 -6
  147. package/src/common/logger/logger.ts +0 -114
  148. package/src/common/logger/transport.ts +0 -71
  149. package/src/common/router-handler.ts +0 -159
  150. package/src/common/router-helpers.ts +0 -20
  151. package/src/common/router-utils.ts +0 -95
  152. package/src/common/session/common.ts +0 -40
  153. package/src/common/session/index.ts +0 -2
  154. package/src/common/session/service.ts +0 -160
  155. package/src/common/tokenize-match.ts +0 -130
  156. package/src/index.ts +0 -7
  157. package/src/middleware/buffer.ts +0 -80
  158. package/src/middleware/cookie.ts +0 -20
  159. package/src/middleware/cors.ts +0 -96
  160. package/src/middleware/form.ts +0 -59
  161. package/src/middleware/group.ts +0 -70
  162. package/src/middleware/index.ts +0 -48
  163. package/src/middleware/json.ts +0 -55
  164. package/src/middleware/logger.ts +0 -18
  165. package/src/middleware/parse.ts +0 -93
  166. package/src/middleware/result.ts +0 -43
  167. package/src/middleware/session.ts +0 -136
  168. package/src/middleware/tag.ts +0 -15
  169. package/src/middleware/text.ts +0 -45
  170. package/src/proxy.ts +0 -77
  171. package/src/proxy.unit.test.js +0 -159
  172. package/src/router.ts +0 -112
  173. package/src/router.unit.test.js +0 -397
  174. package/src/setup-test.js +0 -5
  175. package/src/static.ts +0 -238
@@ -1,209 +0,0 @@
1
- import {lstatSync, readdirSync} from "fs";
2
- import {join, parse as pathParse, resolve} from "path";
3
- import {Logger} from "./logger";
4
- import {APIRoute} from "./api-router";
5
- import {normalizePath} from "./tokenize-match";
6
- import {isFeatureEnabled} from "./config";
7
- import {Router} from "../router";
8
- import {Handler, Method} from "./context";
9
- import {RouterHandlerOptions} from "./router-utils";
10
- import {parse, ParseOptionMap} from "@miqro/parser";
11
-
12
- export const APIRouteValidator: ParseOptionMap = {
13
- name: "string?",
14
- description: "string?",
15
- method: "string[]!?",
16
- path: "string[]!?",
17
- parser: "ParserInterface?",
18
- headers: "ParseOptions[]!?",
19
- query: "boolean?|ParseOptions[]!?|string?",
20
- params: "boolean?|ParseOptions[]!?|string?",
21
- body: "boolean?|ParseOptions[]!?|string?",
22
- response: "ParseOptions[]!?|string?",
23
- handler: "function[]!",
24
- middleware: "function[]!?",
25
- session: "function?|SessionHandlerOptions?",
26
- policy: "GroupPolicy?"
27
- };
28
-
29
- export function traverseAPIRouteDir(
30
- featureName: string,
31
- dirname: string,
32
- basePath = "/",
33
- features: FeatureRouterOptions = {}, logger?: Logger): FeatureRouterOptions {
34
- if (logger) {
35
- logger.trace("loading routes from [%s]", dirname);
36
- }
37
- const files = readdirSync(dirname);
38
- const dirs = files.filter(f => lstatSync(join(dirname, f)).isDirectory());
39
- const methods = files.filter(f => !lstatSync(join(dirname, f)).isDirectory());
40
- for (const f of dirs) {
41
- const {name} = pathParse(f);
42
- features = traverseAPIRouteDir(`${featureName}_${name}`.toUpperCase(), join(dirname, f), `${basePath}/${name}`, features, logger);
43
- }
44
- for (const f of methods) {
45
- const {name, ext} = pathParse(f);
46
- if (name !== "index" && ((ext === ".ts" || ext === ".js") && name.slice(-2) !== ".d")) {
47
- const filePath = join(dirname, name);
48
- // eslint-disable-next-line @typescript-eslint/no-var-requires
49
- let route: APIRoute = require(filePath);
50
- if ((route as any).default && (route as any).__esModule === true) {
51
- route = (route as any).default;
52
- }
53
- const ___filePath = filePath + ext;
54
- let routeMethods: Method[] = [name] as Method[];
55
- if (typeof route === "function") {
56
- route = {
57
- handler: route
58
- } as any;
59
- } else {
60
- if (typeof route.method !== "undefined" && (!(route.method instanceof Array) && (typeof route.method !== "string"))) {
61
- throw new Error(`${resolve(dirname, name)} doesnt export method as a string or string array`);
62
- } else if (typeof route.method !== "undefined") {
63
- routeMethods = route.method instanceof Array ? route.method : [route.method];
64
- }
65
- if (typeof route.path !== "string" && typeof route.path !== "undefined" && !(route.path instanceof Array)) {
66
- throw new Error(`${resolve(dirname, name)} doesnt export path as a string or a string array`);
67
- }
68
- if ((!(route.handler instanceof Array) && typeof route.handler !== "function") || typeof route.handler === "undefined") {
69
- throw new Error(`${resolve(dirname, name)} doesnt export handler as a function or an array`);
70
- }
71
- if (typeof route.name !== "string" && typeof route.name !== "undefined") {
72
- throw new Error(`${resolve(dirname, name)} doesnt export name as a string`);
73
- }
74
- }
75
- route = parse(route, APIRouteValidator, "no_extra", ___filePath) as APIRoute;
76
- const paths = route.path instanceof Array ? route.path : route.path === undefined ? [route.method && route.method.indexOf(name as Method) === -1 ? `/${name}` : "/"] : [route.path];
77
- for (let i = 0; i < paths.length; i++) {
78
- const p = paths[i];
79
- if (typeof p !== "string" || !p) {
80
- throw new Error(`${resolve(dirname, name)} doesnt export path as a string or a string array`);
81
- }
82
- const path = normalizePath(`${basePath}${p && p !== "/" ? `${p}` : ""}`)
83
-
84
- const subName = (p.charAt(0) === "/" ? p.substring(1) : p).replace(/[^a-z0-9+]+/gi, '_');
85
- const routeName = route.name ? route.name : name;
86
-
87
- let newFeatureSubPath = `${featureName}_${route.name ? route.name : name}${routeName !== subName ? `_${subName}` : ""}`.toUpperCase();
88
-
89
- newFeatureSubPath = newFeatureSubPath.length > 1 && newFeatureSubPath.charAt(newFeatureSubPath.length - 1) === "_" ? newFeatureSubPath.substring(0, newFeatureSubPath.length - 1) : newFeatureSubPath;
90
- if (features[newFeatureSubPath]) {
91
- throw new Error(`${___filePath} feature name collides with ${(features[newFeatureSubPath] as any).___filePath}`)
92
- }
93
- if (newFeatureSubPath === "__prototype__" || newFeatureSubPath === "__proto__") {
94
- throw new Error(`invalid feature name ${newFeatureSubPath}`);
95
- }
96
- features[newFeatureSubPath] = {
97
- options: {
98
- name: route.name,
99
- description: route.description,
100
- parser: route.parser,
101
- middleware: route.middleware,
102
- session: route.session,
103
- policy: route.policy,
104
- request: {
105
- headers: route.headers,
106
- query: route.query,
107
- body: route.body,
108
- params: route.params,
109
- },
110
- response: {
111
- body: route.response ? route.response : true
112
- }
113
- },
114
- path,
115
- method: routeMethods,
116
- handler: route.handler
117
- };
118
- (features[newFeatureSubPath] as any).___filePath = ___filePath;
119
- }
120
- }
121
- }
122
- return features;
123
- };
124
-
125
- export interface FeatureRouterPathOptions {
126
- path: string | string[];
127
- method: Method | Method[];
128
- handler: Array<Handler> | Handler;
129
- options?: RouterHandlerOptions;
130
- }
131
-
132
- export type FeatureRouterOptions = { [name: string]: FeatureRouterPathOptions };
133
-
134
- const FEATURE_ROUTER_METHODS: Method[] = ["get", "post", "put", "delete", "patch", "options"];
135
-
136
- export const FeatureRouter = (options: FeatureRouterOptions, logger?: Logger): Router => {
137
- const router: Router = new Router();
138
- const toSetup = Object.keys(options);
139
- const enabled: string[] = [];
140
- const disabled: string[] = [];
141
- const enabledPaths: { [name: string]: string } = {};
142
- for (const featureName of toSetup) {
143
- const handlerOptions = options[featureName];
144
- if (!handlerOptions) {
145
- throw new Error(`no handler options for feature [${featureName}]`);
146
- } else {
147
- const {path, handler: implementation, method} = handlerOptions;
148
- if (!method) {
149
- throw new Error(`no methods for feature [${featureName}]`);
150
- } else if (!implementation) {
151
- throw new Error(`no implementation for feature [${featureName}]`);
152
- } else if (!path) {
153
- throw new Error(`no path for feature [${featureName}]`);
154
- } else {
155
- if (method instanceof Array) {
156
- for (const m of method) {
157
- if (FEATURE_ROUTER_METHODS.indexOf(m.toLowerCase() as Method) === -1) {
158
- throw new Error(`feature [${featureName}] method [${m.toUpperCase()}] not defined! use only [${FEATURE_ROUTER_METHODS.join(",")}]`);
159
- }
160
- }
161
- } else if (FEATURE_ROUTER_METHODS.indexOf(method.toLowerCase() as Method) === -1) {
162
- throw new Error(`feature [${featureName}] method [${method.toUpperCase()}] not defined! use only [${FEATURE_ROUTER_METHODS.join(",")}]`);
163
- }
164
- const methods = method instanceof Array ? method : [method];
165
- if (isFeatureEnabled(featureName)) {
166
- if (logger) {
167
- logger.trace(`feature [${featureName}] enabled`);
168
- }
169
- enabled.push(featureName);
170
- const paths = path instanceof Array ? path : [path];
171
- for (const nnP of paths) {
172
- const p = normalizePath(nnP);
173
- for (const m of methods) {
174
- if (logger) {
175
- logger.info("%s", featureName);
176
- logger.info("\t%s:%s", m.toUpperCase(), p);
177
- if ((handlerOptions as any).___filePath) {
178
- logger.info("\t%s", (handlerOptions as any).___filePath);
179
- }
180
- }
181
- if (enabledPaths[`${p}${m}`] !== undefined) {
182
- throw new Error(`${featureName} collides with feature ${enabledPaths[`${p}${m}`]} on path ${p} method ${m}`)
183
- }
184
- enabledPaths[`${p}${m}`] = featureName;
185
- router.use(implementation, p, m.toLocaleLowerCase() as Method, handlerOptions.options);
186
- }
187
- }
188
- } else {
189
- if (logger) {
190
- logger.debug("feature [%s] disabled", featureName);
191
- }
192
- disabled.push(featureName);
193
- }
194
- }
195
- }
196
- }
197
- if (logger && enabled.length > 0) {
198
- logger.debug("enabled features [%s]", enabled.join(","));
199
- }
200
- if (logger) {
201
- if (disabled.length > 0) {
202
- logger.warn("disabled features [%s]", disabled.join(","));
203
- logger.warn(`to enable them just add the env var <feature>=true`);
204
- } else {
205
- logger.debug(`no features disabled`);
206
- }
207
- }
208
- return router;
209
- }
@@ -1,32 +0,0 @@
1
- import {ParseOptions, ParserInterface} from "@miqro/parser";
2
- import {GroupPolicy, SessionHandlerOptions} from "./session";
3
- import {Handler, Method} from "./context";
4
-
5
- /**
6
- * # APIRoute
7
- *
8
- * src/api/comment/get.js
9
- * ```typescript
10
- *import { APIRouter } from "@miqro/core";
11
- *const route: APIRoute = {
12
- * ...
13
- *};
14
- *export default route;
15
- * ```
16
- */
17
- export interface APIRoute {
18
- name?: string;
19
- description?: string;
20
- method?: Method | Method[];
21
- path?: string | string[];
22
- parser?: ParserInterface;
23
- headers?: ParseOptions | ParseOptions[];
24
- query?: ParseOptions | boolean | ParseOptions[] | string;
25
- params?: ParseOptions | boolean | ParseOptions[] | string;
26
- body?: ParseOptions | boolean | ParseOptions[] | string;
27
- response?: ParseOptions | ParseOptions[] | string;
28
- handler: Array<Handler> | Handler;
29
- middleware?: Handler[];
30
- session?: SessionHandlerOptions | Handler;
31
- policy?: GroupPolicy;
32
- }
@@ -1,111 +0,0 @@
1
- import {resolve} from "path";
2
-
3
- export type ConfigOutput = { [name: string]: string };
4
-
5
- export abstract class ConfigPathResolver {
6
-
7
- public static getSequelizeRCFilePath(): string {
8
- return resolve(ConfigPathResolver.getBaseDirname(), `.sequelizerc`);
9
- }
10
-
11
- public static getConfigDirname(): string {
12
- return resolve(ConfigPathResolver.getBaseDirname(), `config`, `${ConfigStore.getConfig("NODE_ENV", "development")}`);
13
- }
14
-
15
- public static getBaseDirname(): string {
16
- const envVar = ConfigStore.getConfig("APP_BASE_DIRNAME");
17
- if (envVar) {
18
- return envVar;
19
- } else if (typeof process !== "undefined") {
20
- return process.cwd();
21
- } else {
22
- return "";
23
- }
24
- }
25
- }
26
-
27
- export interface LoadConfigOut {
28
- combined: ConfigOutput;
29
- outputs: ConfigOutput[]
30
- }
31
-
32
- const processEnvDefined = (typeof process !== "undefined" && typeof process.env !== "undefined");
33
-
34
- export abstract class ConfigStore {
35
-
36
- public static putConfig(key: string, value: string): ConfigStore {
37
- if (key === "__proto__" || key === "__prototype__") {
38
- throw new Error("invalid key " + key);
39
- }
40
- if (processEnvDefined) {
41
- Object.defineProperty(process.env, key, {
42
- writable: true,
43
- enumerable: true,
44
- configurable: true,
45
- value
46
- }); // this is for webpack
47
- } else {
48
- /* eslint-disable @typescript-eslint/ban-ts-comment */
49
- // @ts-ignore
50
- localStorage.setItem(key, value);
51
- }
52
- return this;
53
- }
54
-
55
- public static clear(key: string): ConfigStore {
56
- if (key === "__proto__" || key === "__prototype__") {
57
- throw new Error("invalid key " + key);
58
- }
59
- if (processEnvDefined) {
60
- delete process.env[key];
61
- } else {
62
- /* eslint-disable @typescript-eslint/ban-ts-comment */
63
- // @ts-ignore
64
- localStorage.removeItem(key);
65
- }
66
- return this;
67
- }
68
-
69
- public static keys(): string[] {
70
- if (processEnvDefined) {
71
- return Object.keys(process.env);
72
- } else {
73
- const keys: string[] = [];
74
- /* eslint-disable @typescript-eslint/ban-ts-comment */
75
- // @ts-ignore
76
- for (let i = 0; i < localStorage.length; i++) {
77
- /* eslint-disable @typescript-eslint/ban-ts-comment */
78
- // @ts-ignore
79
- const key = localStorage.key(i) as string;
80
- keys.push(key);
81
- }
82
- return keys;
83
- }
84
- }
85
-
86
- public static getConfig(key: string, defaultValue?: string): string | null {
87
- if (key === "__proto__" || key === "__prototype__") {
88
- throw new Error("invalid key " + key);
89
- }
90
- if (processEnvDefined) {
91
- return process.env[key] !== undefined ? process.env[key] as string : (defaultValue !== undefined ? defaultValue : null);
92
- } else {
93
- /* eslint-disable @typescript-eslint/ban-ts-comment */
94
- // @ts-ignore
95
- return localStorage.getItem(key) ? localStorage.getItem(key) : (defaultValue !== undefined ? defaultValue : null);
96
- }
97
- }
98
- }
99
-
100
- export const checkEnvVariables = (requiredEnvVariables: string[], defaults?: string[]): string[] => {
101
- if (defaults && defaults.length !== requiredEnvVariables.length) {
102
- throw new Error(`defaults cannot be a different length of requiredEnvVariables`);
103
- }
104
- return requiredEnvVariables.map((envName, index) => {
105
- const value = ConfigStore.getConfig(envName, defaults && defaults[index] ? defaults && defaults[index] as string : undefined);
106
- if (!value) {
107
- throw new Error(`Env variable [${envName}!] not defined.`);
108
- }
109
- return value;
110
- });
111
- };
@@ -1,6 +0,0 @@
1
- import {ConfigStore} from "./config";
2
-
3
- export const isFeatureEnabled = (feature: string, defaults = true): boolean => {
4
- const featureToggleName = `${feature.toUpperCase()}`;
5
- return ConfigStore.getConfig(featureToggleName, String(defaults)) === "true"
6
- };
@@ -1,3 +0,0 @@
1
- export * from "./config";
2
- export * from "./loader";
3
- export * from "./featuretoggle";
@@ -1,80 +0,0 @@
1
- import {extname, resolve} from "path";
2
- import {existsSync, readdirSync, readFileSync} from "fs";
3
- import {ConfigOutput, ConfigPathResolver, ConfigStore, LoadConfigOut} from "./config";
4
-
5
- interface Logger {
6
- log(message?: any, ...optionalParams: any[]): void;
7
-
8
- info(message?: any, ...optionalParams: any[]): void;
9
-
10
- trace(message?: any, ...optionalParams: any[]): void;
11
-
12
- debug(message?: any, ...optionalParams: any[]): void;
13
-
14
- warn(message?: any, ...optionalParams: any[]): void;
15
-
16
- error(message?: any, ...optionalParams: any[]): void;
17
- }
18
-
19
-
20
- class ConfigFileNotFoundError extends Error {
21
- constructor(args: any) {
22
- super(args);
23
- this.name = "ConfigFileNotFoundError";
24
- }
25
- }
26
-
27
- export const loadConfigString = (envFileContent: string, combined?: ConfigOutput): ConfigOutput => {
28
- const ret: ConfigOutput = Object.create(null);
29
- envFileContent.split("\n")
30
- .filter(value => value && value.length > 0 && value.substring(0, 1) !== "#")
31
- .forEach((line) => {
32
- const separator = line.indexOf("=");
33
- if (separator === -1) {
34
- throw new Error(`cannot read ${line}`);
35
- }
36
- ret[line.substring(0, separator)] = line.substring(separator + 1);
37
- });
38
- const keys = Object.keys(ret);
39
- for (const key of keys) {
40
- if (combined) {
41
- combined[key] = ret[key];
42
- }
43
- ConfigStore.putConfig(key, ret[key]);
44
- }
45
- return ret;
46
- }
47
-
48
- export const loadConfigFile = (envFilePath: string, combined?: ConfigOutput, logger?: Logger): ConfigOutput => {
49
- if (!existsSync(envFilePath)) {
50
- throw new ConfigFileNotFoundError(`config file [${envFilePath}] doesnt exists!`);
51
- } else {
52
- if (logger) {
53
- logger.trace(`loading config from [${envFilePath}].`);
54
- }
55
- return loadConfigString(readFileSync(envFilePath).toString(), combined);
56
- }
57
- };
58
-
59
- const MISSED_TO_RUNMIQRO_INIT = (configDirname: string): string => `no config loaded. env files in [${configDirname}] doesnt exist!.`;
60
-
61
- export const loadConfig = (configDirname: string = ConfigPathResolver.getConfigDirname(), logger?: Logger): LoadConfigOut => {
62
- const outputs: ConfigOutput[] = [];
63
- const combined = Object.create(null);
64
- if (existsSync(configDirname)) {
65
- const configFiles = readdirSync(configDirname);
66
- for (const configFile of configFiles) {
67
- const configFilePath = resolve(configDirname, configFile);
68
- const ext = extname(configFilePath);
69
- if (ext === ".env") {
70
- outputs.push(loadConfigFile(configFilePath, combined, logger));
71
- }
72
- }
73
- if (logger && configFiles.length === 0) {
74
- logger.debug(MISSED_TO_RUNMIQRO_INIT(configDirname));
75
- }
76
- } else if (logger) {
77
- logger.debug(MISSED_TO_RUNMIQRO_INIT(configDirname));
78
- }
79
- return {combined, outputs};
80
- };
@@ -1,167 +0,0 @@
1
- import {Logger} from "./logger";
2
- import {Session} from "./session";
3
- import {IncomingHttpHeaders, IncomingMessage, OutgoingHttpHeaders, ServerResponse} from "http";
4
- import {normalizePath, parseSearchParams} from "./tokenize-match";
5
- import {URL} from "url";
6
- import {newURL} from "./helpers";
7
- import {CookieSerializeOptions, serialize} from "cookie";
8
-
9
- export type Method =
10
- "get"
11
- | "post"
12
- | "put"
13
- | "delete"
14
- | "patch"
15
- | "options"
16
- | "GET"
17
- | "POST"
18
- | "PUT"
19
- | "DELETE"
20
- | "PATCH"
21
- | "OPTIONS";
22
-
23
- export const IGNORE_HEADER = ["keep-alive", "connection"];
24
-
25
- export type Handler<T = boolean | void | any> = ((ctx: Context) => Promise<T>) | ((ctx: Context) => T);
26
-
27
- export type ErrorHandler<T = boolean | void | any> =
28
- ((e: unknown, ctx: Context) => Promise<T>)
29
- | ((e: unknown, ctx: Context) => T);
30
-
31
- export class Context {
32
- public readonly url: URL; // new URL(req.url ? req.url : "/", `http://${req.headers.host}`)
33
- public readonly startMS: number; // Date.now()
34
- public session?: Session; // a middleware will fill this
35
- public results: any[]; // handlers will fill this
36
- public readonly path: string; // normalized path
37
- public readonly hash: string; // from this.url.hash
38
- public readonly method: string; // from this.url.method
39
- public headers: IncomingHttpHeaders; // from this.req.headers
40
- public readonly cookies: { [name: string]: string }; // a middleware will fill this
41
- public query: { [name: string]: string | string[] }; // parseSearchParams will fill this with this.url.searchParams
42
- public params: { [name: string]: string | undefined }; // the router will fill this
43
- public buffer?: Buffer; // empty buffer. middleware must read it
44
- public readonly remoteAddress?: string;
45
- public body: any; // a middleware will fill this reading the buffer
46
- constructor(public readonly uuid: string, public readonly req: IncomingMessage, public readonly res: ServerResponse, public readonly logger: Logger) {
47
- this.body = undefined as any;
48
- this.res.removeHeader("Date");
49
- this.url = newURL(req.url ? req.url : "/", `http://${req.headers.host}`) as URL;
50
- this.method = req.method ? req.method.toUpperCase() as string : "GET";
51
- this.path = normalizePath(this.url.pathname); // normalized path
52
- this.hash = this.url.hash;
53
- this.params = Object.create(null);
54
- this.query = parseSearchParams(this.url.searchParams);
55
- //this.buffer = Buffer.from("");
56
- this.remoteAddress = req.socket.remoteAddress;
57
- this.cookies = Object.create(null); // a middleware will fill
58
- this.headers = req.headers;
59
- this.startMS = Date.now();
60
- this.results = []; // handlers will fill this
61
- }
62
-
63
- public async close(): Promise<void> {
64
- return this.end({
65
- status: 400,
66
- headers: {
67
- connection: "close"
68
- }
69
- });
70
- }
71
-
72
- public addVaryHeader(value: number | string | ReadonlyArray<string>): ServerResponse {
73
- const c = this.res.getHeader("Vary");
74
- const current = c ? c instanceof Array ? c.join(", ") : String(c) : "";
75
- const nV = value instanceof Array ? value.join(", ") : String(value);
76
- const newValue = current ? `${current}, ${nV}` : nV;
77
- return this.setHeader("Vary", newValue.indexOf("*") !== -1 ? "*" : newValue);
78
- }
79
-
80
- public setHeader(name: string, value: number | string | ReadonlyArray<string>): ServerResponse {
81
- return this.res.setHeader(name, value);
82
- }
83
-
84
- public setCookie(name: string, value: string, options?: CookieSerializeOptions): ServerResponse {
85
- return this.setHeader('Set-Cookie', serialize(name, String(value), options));
86
- }
87
-
88
- public async end({status, headers, body}: {
89
- body?: any;
90
- status: number;
91
- headers: OutgoingHttpHeaders;
92
- }): Promise<void> {
93
- if (this.res.headersSent) {
94
- return Promise.reject(new Error("already ended"));
95
- }
96
- return new Promise<void>((resolve, reject) => {
97
- try {
98
- if (this.res.headersSent) {
99
- reject(new Error("already ended"));
100
- } else {
101
- this.res.statusCode = status;
102
- const keys = Object.keys(headers);
103
- for (const key of keys) {
104
- if (IGNORE_HEADER.indexOf(key.toLocaleLowerCase()) !== -1) {
105
- this.logger.warn("ignoring " + key);
106
- continue;
107
- }
108
- if (headers[key] !== undefined) {
109
- this.res.setHeader(key, headers[key] as any);
110
- }
111
- }
112
- this.res.setHeader("connection", "close");
113
- this.res.end(body !== undefined ? (body instanceof Buffer ? body : String(body)) : undefined, () => {
114
- resolve();
115
- });
116
- }
117
- } catch (e) {
118
- reject(e);
119
- }
120
- });
121
- }
122
-
123
- /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
124
- public async json(body: any, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
125
- return this.end({
126
- status: status !== undefined ? status : 200,
127
- headers: {
128
- ['Content-Type']: 'application/json; charset=utf-8',
129
- ...headers,
130
- },
131
- body: JSON.stringify(body)
132
- })
133
- }
134
-
135
- public async text(text: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
136
- return this.end({
137
- status: status !== undefined ? status : 200,
138
- headers: {
139
- ['Content-Type']: 'plain/text; charset=utf-8',
140
- ...headers
141
- },
142
- body: text
143
- });
144
- }
145
-
146
- public async html(html: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
147
- return this.end({
148
- status: status !== undefined ? status : 200,
149
- headers: {
150
- ['Content-Type']: 'text/html; charset=utf-8',
151
- ...headers
152
- },
153
- body: html
154
- })
155
- }
156
-
157
- public async redirect(url: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
158
- return this.end({
159
- status: status !== undefined ? status : 302,
160
- headers: {
161
- ['Location']: url,
162
- ...headers
163
- }
164
- })
165
- }
166
- }
167
-