miqro 7.0.1 → 7.0.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 (145) hide show
  1. package/build/esm/editor/auth.d.ts +6 -0
  2. package/build/esm/editor/auth.js +41 -0
  3. package/build/esm/editor/common/admin-interface.d.ts +36 -0
  4. package/build/esm/editor/common/admin-interface.js +44 -0
  5. package/build/esm/editor/common/constants.d.ts +4 -0
  6. package/build/esm/editor/common/constants.js +20 -0
  7. package/build/esm/editor/common/constants.server.d.ts +2 -0
  8. package/build/esm/editor/common/constants.server.js +4 -0
  9. package/build/esm/editor/common/editor-index.d.ts +2 -0
  10. package/build/esm/editor/common/editor-index.js +14 -0
  11. package/build/esm/editor/common/html-encode.d.ts +1 -0
  12. package/build/esm/editor/common/html-encode.js +14 -0
  13. package/build/esm/editor/common/log-socket.d.ts +15 -0
  14. package/build/esm/editor/common/log-socket.js +71 -0
  15. package/build/esm/editor/common/templates.d.ts +11 -0
  16. package/build/esm/editor/common/templates.js +477 -0
  17. package/build/esm/editor/components/api-preview.d.ts +11 -0
  18. package/build/esm/editor/components/api-preview.js +92 -0
  19. package/build/esm/editor/components/editor.d.ts +16 -0
  20. package/build/esm/editor/components/editor.js +367 -0
  21. package/build/esm/editor/components/file-browser.d.ts +37 -0
  22. package/build/esm/editor/components/file-browser.js +127 -0
  23. package/build/esm/editor/components/file-editor-toolbar.d.ts +22 -0
  24. package/build/esm/editor/components/file-editor-toolbar.js +95 -0
  25. package/build/esm/editor/components/file-editor.d.ts +32 -0
  26. package/build/esm/editor/components/file-editor.js +61 -0
  27. package/build/esm/editor/components/filter-query.d.ts +1 -0
  28. package/build/esm/editor/components/filter-query.js +23 -0
  29. package/build/esm/editor/components/highlight-text-area.d.ts +11 -0
  30. package/build/esm/editor/components/highlight-text-area.js +127 -0
  31. package/build/esm/editor/components/log-viewer.d.ts +6 -0
  32. package/build/esm/editor/components/log-viewer.js +71 -0
  33. package/build/esm/editor/components/new-file.d.ts +10 -0
  34. package/build/esm/editor/components/new-file.js +119 -0
  35. package/build/esm/editor/components/scroll-query.d.ts +7 -0
  36. package/build/esm/editor/components/scroll-query.js +22 -0
  37. package/build/esm/editor/components/start-page.d.ts +13 -0
  38. package/build/esm/editor/components/start-page.js +32 -0
  39. package/build/esm/editor/http/admin/editor/api/fs/delete.api.d.ts +3 -0
  40. package/build/esm/editor/http/admin/editor/api/fs/delete.api.js +30 -0
  41. package/build/esm/editor/http/admin/editor/api/fs/read.api.d.ts +5 -0
  42. package/build/esm/editor/http/admin/editor/api/fs/read.api.js +50 -0
  43. package/build/esm/editor/http/admin/editor/api/fs/rename.api.d.ts +4 -0
  44. package/build/esm/editor/http/admin/editor/api/fs/rename.api.js +40 -0
  45. package/build/esm/editor/http/admin/editor/api/fs/scan.api.d.ts +26 -0
  46. package/build/esm/editor/http/admin/editor/api/fs/scan.api.js +150 -0
  47. package/build/esm/editor/http/admin/editor/api/fs/write.api.d.ts +3 -0
  48. package/build/esm/editor/http/admin/editor/api/fs/write.api.js +39 -0
  49. package/build/esm/editor/http/admin/editor/api/server/reload.api.d.ts +10 -0
  50. package/build/esm/editor/http/admin/editor/api/server/reload.api.js +46 -0
  51. package/build/esm/editor/http/admin/editor/api/server/restart.api.d.ts +10 -0
  52. package/build/esm/editor/http/admin/editor/api/server/restart.api.js +46 -0
  53. package/build/esm/editor/http/admin/editor/editor.d.ts +1 -0
  54. package/build/esm/editor/http/admin/editor/editor.js +8 -0
  55. package/build/esm/editor/http/admin/editor/index.api.d.ts +3 -0
  56. package/build/esm/editor/http/admin/editor/index.api.js +22 -0
  57. package/build/esm/editor/server.d.ts +3 -0
  58. package/build/esm/editor/server.js +49 -0
  59. package/build/esm/editor/ws.d.ts +3 -0
  60. package/build/esm/editor/ws.js +11 -0
  61. package/editor/auth.ts +51 -0
  62. package/editor/common/admin-interface.ts +84 -0
  63. package/editor/common/constants.server.ts +5 -0
  64. package/editor/common/constants.ts +21 -0
  65. package/editor/common/editor-index.tsx +17 -0
  66. package/editor/common/html-encode.ts +14 -0
  67. package/editor/common/log-socket.tsx +87 -0
  68. package/editor/common/templates.ts +481 -0
  69. package/editor/components/api-preview.tsx +118 -0
  70. package/editor/components/editor.tsx +496 -0
  71. package/editor/components/file-browser.tsx +311 -0
  72. package/editor/components/file-editor-toolbar.tsx +194 -0
  73. package/editor/components/file-editor.tsx +125 -0
  74. package/editor/components/filter-query.tsx +26 -0
  75. package/editor/components/highlight-text-area.tsx +148 -0
  76. package/editor/components/log-viewer.tsx +113 -0
  77. package/editor/components/new-file.tsx +172 -0
  78. package/editor/components/scroll-query.tsx +25 -0
  79. package/editor/components/start-page.tsx +52 -0
  80. package/editor/http/admin/editor/api/fs/delete.api.tsx +32 -0
  81. package/editor/http/admin/editor/api/fs/read.api.tsx +55 -0
  82. package/editor/http/admin/editor/api/fs/rename.api.tsx +41 -0
  83. package/editor/http/admin/editor/api/fs/scan.api.tsx +181 -0
  84. package/editor/http/admin/editor/api/fs/write.api.tsx +41 -0
  85. package/editor/http/admin/editor/api/server/reload.api.ts +53 -0
  86. package/editor/http/admin/editor/api/server/restart.api.tsx +52 -0
  87. package/editor/http/admin/editor/editor.tsx +10 -0
  88. package/editor/http/admin/editor/index.api.tsx +42 -0
  89. package/editor/server.ts +57 -0
  90. package/editor/ws.ts +15 -0
  91. package/package.json +1 -1
  92. package/src/bin/compile.ts +35 -0
  93. package/src/bin/doc-md.ts +210 -0
  94. package/src/bin/generate-doc.ts +64 -0
  95. package/src/bin/test.ts +92 -0
  96. package/src/bin/types.ts +34 -0
  97. package/src/cluster.ts +27 -0
  98. package/src/common/arguments.ts +762 -0
  99. package/src/common/assets.ts +148 -0
  100. package/src/common/checksum.ts +58 -0
  101. package/src/common/constants.ts +18 -0
  102. package/src/common/content-type.ts +84 -0
  103. package/src/common/esbuild.ts +102 -0
  104. package/src/common/exit.ts +91 -0
  105. package/src/common/fs.ts +82 -0
  106. package/src/common/help.ts +60 -0
  107. package/src/common/jsx.ts +562 -0
  108. package/src/common/jwt.ts +85 -0
  109. package/src/common/paths.ts +107 -0
  110. package/src/common/watch.ts +88 -0
  111. package/src/inflate/inflate-sea.ts +237 -0
  112. package/src/inflate/inflate.ts +101 -0
  113. package/src/inflate/md.ts +25 -0
  114. package/src/inflate/setup-auth.ts +41 -0
  115. package/src/inflate/setup-cors.ts +41 -0
  116. package/src/inflate/setup-db.ts +117 -0
  117. package/src/inflate/setup-error.ts +44 -0
  118. package/src/inflate/setup-http.ts +704 -0
  119. package/src/inflate/setup-log.ts +45 -0
  120. package/src/inflate/setup-middleware.ts +47 -0
  121. package/src/inflate/setup-server-config.ts +48 -0
  122. package/src/inflate/setup-test.ts +23 -0
  123. package/src/inflate/setup-ws.ts +50 -0
  124. package/src/inflate/setup.doc.ts +92 -0
  125. package/src/inflate/utils/sea-utils.ts +14 -0
  126. package/src/lib.ts +34 -0
  127. package/src/main.ts +101 -0
  128. package/src/services/app.ts +699 -0
  129. package/src/services/editor.tsx +101 -0
  130. package/src/services/globals.ts.ignore +186 -0
  131. package/src/services/hot-reload.ts +51 -0
  132. package/src/services/migrations.ts +68 -0
  133. package/src/services/utils/admin-interface.ts +37 -0
  134. package/src/services/utils/cache.ts +88 -0
  135. package/src/services/utils/cluster-cache.ts +230 -0
  136. package/src/services/utils/cluster-ws.ts +202 -0
  137. package/src/services/utils/db-manager.ts +92 -0
  138. package/src/services/utils/get-route.ts +70 -0
  139. package/src/services/utils/jwt.ts +25 -0
  140. package/src/services/utils/log-transport.ts +81 -0
  141. package/src/services/utils/log.ts +92 -0
  142. package/src/services/utils/middleware.ts +10 -0
  143. package/src/services/utils/server-interface.ts +122 -0
  144. package/src/services/utils/websocketmanager.ts +157 -0
  145. package/src/types.ts +307 -0
@@ -0,0 +1,107 @@
1
+ import { checkEnvVariable } from "@miqro/core";
2
+ import { randomUUID } from "node:crypto";
3
+ import { existsSync, statSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { resolve } from "node:path";
6
+ import { cwd, platform } from "node:process";
7
+
8
+ export const JSX_TMP_DIR = checkEnvVariable(`JSX_TMP`, resolve(tmpdir(), "jsx_tmp"));
9
+
10
+ export const TEST_SOCKET = resolve(JSX_TMP_DIR, `test.${randomUUID()}.sock`);
11
+
12
+ export function getServicePath(service: string) {
13
+ return resolve(cwd(), service);
14
+ }
15
+
16
+ const EXTENSIONS = [".ts", ".js", ".cjs"];
17
+
18
+ function getFilePath(dirname: string, name: string, extensions: string[]) {
19
+ for (const ex of extensions) {
20
+ const path = resolve(dirname, name + ex);
21
+ if (existsSync(path) && !statSync(path).isDirectory()) {
22
+ return path;
23
+ }
24
+ }
25
+ return false;
26
+ }
27
+
28
+ export function getLogConfigPath(servicePath: string) {
29
+ return getFilePath(servicePath, "log", EXTENSIONS);
30
+ }
31
+
32
+ export function getCORSConfigPath(servicePath: string) {
33
+ return getFilePath(servicePath, "cors", EXTENSIONS);
34
+ }
35
+
36
+ export function getServerConfigPath(servicePath: string) {
37
+ return getFilePath(servicePath, "server", EXTENSIONS);
38
+ }
39
+
40
+ export function getWSConfigPath(servicePath: string) {
41
+ return getFilePath(servicePath, "ws", EXTENSIONS);
42
+ }
43
+
44
+ export function getDBConfigPath(servicePath: string) {
45
+ return getFilePath(servicePath, "db", EXTENSIONS);
46
+ }
47
+
48
+ export function getStaticFilesPath(servicePath: string) {
49
+ const staticFilesPath = resolve(servicePath, "static");
50
+ if (existsSync(staticFilesPath) && statSync(staticFilesPath).isDirectory()) {
51
+ return staticFilesPath;
52
+ }
53
+ return false;
54
+ }
55
+
56
+ export function getMiddlewareConfigPath(servicePath: string) {
57
+ return getFilePath(servicePath, "middleware", EXTENSIONS);
58
+ }
59
+
60
+ export function getErrorConfigPath(servicePath: string) {
61
+ return getFilePath(servicePath, "catch", EXTENSIONS);
62
+ }
63
+
64
+ export function getDocConfigPath(servicePath: string) {
65
+ return getFilePath(servicePath, "doc", EXTENSIONS);
66
+ }
67
+
68
+ export function getMiqroJSONPath() {
69
+ const miqroRCPath = resolve(cwd(), "miqro.json");
70
+ if (existsSync(miqroRCPath) && !statSync(miqroRCPath).isDirectory()) {
71
+ return miqroRCPath;
72
+ }
73
+ return false;
74
+ }
75
+
76
+ export function getAuthConfigPath(servicePath: string) {
77
+ return getFilePath(servicePath, "auth", EXTENSIONS);
78
+ }
79
+
80
+ export function getHTTPRouterPath(servicePath: string) {
81
+ const apiRouterPath = resolve(servicePath, "http");
82
+ if (existsSync(apiRouterPath) && statSync(apiRouterPath).isDirectory()) {
83
+ return apiRouterPath;
84
+ }
85
+ return false;
86
+ }
87
+
88
+ export function getMigrationsPath(servicePath: string) {
89
+ const migrationsFolderPath = resolve(servicePath, "migration");
90
+ if (existsSync(migrationsFolderPath) && statSync(migrationsFolderPath).isDirectory()) {
91
+ return migrationsFolderPath;
92
+ }
93
+ return false;
94
+ }
95
+
96
+ export function getESBuildBinaryPath() {
97
+ if (platform === "win32") {
98
+ return resolve(JSX_TMP_DIR, String(process.pid), "esbuild.exe");
99
+ } else {
100
+ return resolve(JSX_TMP_DIR, String(process.pid), "esbuild");
101
+ }
102
+ }
103
+
104
+ /*export function getJSXJSPath() {
105
+ return resolve(JSX_TMP_DIR, String(process.pid), "jsx.js");
106
+ }*/
107
+
@@ -0,0 +1,88 @@
1
+ //import "../services/globals.js";
2
+ import { FSWatcher, existsSync, readdirSync, statSync, watch } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { Miqro } from "../services/app.js";
5
+
6
+ export async function watchAndServer(app: Miqro) {
7
+ let timeout: any;
8
+ const watchLogger = app.logger;
9
+ const watchers: FSWatcher[] = [];
10
+
11
+ /*await start({
12
+ logger,
13
+ webSocketManager,
14
+ dbManager,
15
+ services,
16
+ editor,
17
+ inflateTests: false,
18
+ inflateDir: false,
19
+ inflateSea: false,
20
+ runOnTestPort: false
21
+ });*/
22
+
23
+ //await app.start();
24
+
25
+ function watchHandler(eventType: any, filename: any) {
26
+ stopWatch();
27
+ watchLogger?.debug(`event type is: ${eventType}`);
28
+ if (filename) {
29
+ watchLogger?.debug(`filename provided: ${filename}`);
30
+ } else {
31
+ watchLogger?.debug('filename not provided');
32
+ }
33
+ watchLogger?.info(`${eventType} on ${filename}`);
34
+ clearTimeout(timeout);
35
+ timeout = setTimeout(async () => {
36
+ try {
37
+ stopWatch();
38
+ setTimeout(async () => {
39
+ watchLogger?.debug("closed");
40
+ await app.reload();
41
+ reWatch();
42
+ }, 500);
43
+ } catch (e) {
44
+ watchLogger?.error(e);
45
+ }
46
+ }, 2000);
47
+ }
48
+
49
+ function watchDir(toWatch: string) {
50
+ clearTimeout(timeout);
51
+ const files = existsSync(toWatch) ? readdirSync(toWatch) : [];
52
+ for (const file of files) {
53
+ const filePath = resolve(toWatch, file);
54
+ if (statSync(filePath).isDirectory()) {
55
+ watchDir(filePath);
56
+ } else {
57
+ //console.log("toWatch=" + filePath);
58
+ watchers.push(watch(filePath, watchHandler));
59
+ }
60
+ }
61
+ }
62
+
63
+ function stopWatch() {
64
+ clearTimeout(timeout);
65
+ const toClose = watchers.splice(0, watchers.length);
66
+ for (const watcher of toClose) {
67
+ watcher.close();
68
+ }
69
+ }
70
+
71
+
72
+ function reWatch() {
73
+ stopWatch();
74
+ clearTimeout(timeout);
75
+ for (const service of app.options.services) {
76
+ const toWatch = resolve(process.cwd(), service);
77
+ watchDir(toWatch);
78
+ }
79
+ }
80
+
81
+ watchLogger?.info("watching for changes on [%s]", app.options.services.join(","));
82
+ reWatch();
83
+ return {
84
+ stopWatch: () => {
85
+ stopWatch();
86
+ }
87
+ };
88
+ }
@@ -0,0 +1,237 @@
1
+ import { Logger } from "@miqro/core";
2
+ import { chmodSync, constants, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, extname, join, relative, resolve } from "node:path";
4
+ import { cwd, platform } from "node:process";
5
+
6
+ import { RouteFileMap, StaticFileMap } from "./setup-http.js";
7
+ import { getAuthConfigPath, getCORSConfigPath, getDBConfigPath, getErrorConfigPath, getMiddlewareConfigPath, getMigrationsPath, getMiqroJSONPath, getServerConfigPath, getServicePath, getWSConfigPath } from "../common/paths.js";
8
+ import { getAsset } from "../common/assets.js";
9
+ import { migration } from "@miqro/query";
10
+ import { esBuild } from "../common/esbuild.js";
11
+
12
+ //export const libCJSBuffer = Buffer.from(getAsset("lib.cjs"));
13
+ /*export const COMPILESH = Buffer.from(Buffer.from(getAsset("compile.base64.sh")).toString(), "base64");
14
+ export const SIGN_REMOVESH = Buffer.from(getAsset("sign-remove.sh"));
15
+ export const SIGN_ADDSH = Buffer.from(getAsset("sign-add.sh"));
16
+ export const INSTALLNODEJSSH = Buffer.from(getAsset("install-nodejs.sh"));
17
+ export const APPSH = Buffer.from(getAsset("app.sh"));
18
+ export const NODESH = Buffer.from(getAsset("node.sh"));
19
+ export const SEACONFIGJSON = Buffer.from(getAsset("sea.basic.config.json"));
20
+ export const POSTJECTCJS = Buffer.from(Buffer.from(getAsset("postject.base64.cjs")).toString(), "base64");*/
21
+
22
+ export async function inflateSeaAssets(logger: Logger, inflateDir: string) {
23
+ const esbuildBinaryBuffer = Buffer.from(getAsset("esbuild-binary"));
24
+ if (platform === "win32") {
25
+ writeFile(logger, resolve(inflateDir, "sea", "esbuild.exe"), esbuildBinaryBuffer);
26
+ chmodSync(resolve(inflateDir, "sea", "esbuild.exe"), constants.S_IXUSR | constants.S_IRUSR | constants.S_IWUSR);
27
+ } else {
28
+ writeFile(logger, resolve(inflateDir, "sea", "esbuild"), esbuildBinaryBuffer);
29
+ chmodSync(resolve(inflateDir, "sea", "esbuild"), constants.S_IXUSR | constants.S_IRUSR | constants.S_IWUSR);
30
+ }
31
+ // writeFile(logger, resolve(inflateDir, "sea", "postject.cjs"), Buffer.from(Buffer.from(getAsset("postject.base64.cjs")).toString(), "base64"));
32
+ writeFile(logger, resolve(inflateDir, "sea", "config.json"), Buffer.from(getAsset("sea.basic.config.json")));
33
+ writeFile(logger, resolve(inflateDir, "sea", "run.sh"), Buffer.from(getAsset("app.sh")));
34
+ writeFile(logger, resolve(inflateDir, "sea", "node.sh"), Buffer.from(getAsset("node.sh")));
35
+ writeFile(logger, resolve(inflateDir, "compile.sh"), Buffer.from(Buffer.from(getAsset("compile.base64.sh")).toString(), "base64"));
36
+ writeFile(logger, resolve(inflateDir, "sea", "sign-add.sh"), Buffer.from(getAsset("sign-add.sh")));
37
+ writeFile(logger, resolve(inflateDir, "sea", "sign-remove.sh"), Buffer.from(getAsset("sign-remove.sh")));
38
+ writeFile(logger, resolve(inflateDir, "install-nodejs.sh"), Buffer.from(getAsset("install-nodejs.sh")));
39
+ }
40
+
41
+ export async function inflateAppForSea(logger: Logger, inflateDir: string, services: string[], port: string) {
42
+
43
+ const PORT = port;
44
+
45
+ inflateSeaAssets(logger, inflateDir);
46
+
47
+ writeFile(logger, resolve(inflateDir, "sea", "lib.cjs"), Buffer.from(getAsset("lib.cjs")));
48
+
49
+ const WSLIST = services.filter(service => getWSConfigPath(resolve(cwd(), service))).map(service => {
50
+ return `(await require("../${service}/ws.cjs")).default`;
51
+ }).join(",")
52
+
53
+ const SERVERCONFIGLIST = services.filter(service => getServerConfigPath(resolve(cwd(), service))).map(service => {
54
+ return `(await require("../${service}/server.cjs")).default`;
55
+ }).join(",\n");
56
+
57
+ const DBCONFIGLIST = services.filter(service => getDBConfigPath(resolve(cwd(), service))).map(service => {
58
+ return `new Promise(async (resolve, reject) => {
59
+ try {
60
+ const db = await dbManager.setupDB((await require("../${service}/db.cjs")).default);
61
+ await (await require("./${service}/migration-up.cjs")).runMigrations(db);
62
+ resolve();
63
+ } catch(e) {
64
+ reject(e);
65
+ }
66
+
67
+ })`;
68
+ }).join(",");
69
+
70
+ writeFile(logger, join(inflateDir, "sea", "package.json"), `{ "type": "module", "private": true }`);
71
+
72
+ writeFile(logger, join(inflateDir, "sea", "app.cjs"), `const { createServerInterface, ServerRequestHandler, WebSocketManager, DBManager, App, LoggerHandler, LogProvider, LocalCache, ClusterCache } = require("./lib.cjs");
73
+
74
+ async function main() {
75
+ const PORT = "${PORT}";
76
+ const loggerProvider = new LogProvider();
77
+ const localCache = new LocalCache();
78
+ const cache = new ClusterCache();
79
+ const webSocketManager = new WebSocketManager();
80
+ const dbManager = new DBManager();
81
+ const serverInterface = createServerInterface({
82
+ cache,
83
+ localCache,
84
+ loggerProvider,
85
+ wsManager: webSocketManager,
86
+ logger: loggerProvider.getLogger("server"),
87
+ dbManager,
88
+ port: PORT
89
+ });
90
+
91
+ await Promise.all([${DBCONFIGLIST}]);
92
+
93
+ ${!WSLIST ? "" : `\n webSocketManager.replaceALLWS(await Promise.all([${WSLIST}]))`}
94
+ const app = new App({
95
+ onUpgrade: webSocketManager.onUpgrade
96
+ });
97
+ ${SERVERCONFIGLIST ? `\n await Promise.all([${SERVERCONFIGLIST}].filter(config=>config.preload).map(config=>config.preload(serverInterface)));\n` : ""}
98
+ app.use(ServerRequestHandler(serverInterface));
99
+ app.use(LoggerHandler());
100
+ ${services.map(service => `app.use(await (await require("./${join(service, "router.cjs")}")).setupRouter());`).join("\n")}
101
+ ${SERVERCONFIGLIST ? `\n await Promise.all([${SERVERCONFIGLIST}].filter(config=>config.load).map(config=>config.load(serverInterface)));\n` : ""}
102
+
103
+ await app.listen(PORT);
104
+ ${SERVERCONFIGLIST ? `\n await Promise.all([${SERVERCONFIGLIST}].filter(config=>config.start).map(config=>config.start(serverInterface)));` : ""}
105
+ loggerProvider.getLogger("server").info("listening on [%s]", PORT);
106
+ }
107
+ main().catch(e=>console.error(e));
108
+ `
109
+ );
110
+
111
+ logger.log("writing [%s]", relative(cwd(), join(inflateDir, "sea", "app.bundle.cjs")));
112
+ await esBuild({
113
+ entryPoints: [join(inflateDir, "sea", "app.cjs")],
114
+ bundle: true,
115
+ minify: true,
116
+ jsxFactory: "JSX.createElement",
117
+ jsxFragment: "JSX.Fragment",
118
+ platform: "node",
119
+ outfile: join(inflateDir, "sea", "app.bundle.cjs")
120
+ });
121
+ const miqroRCPath = getMiqroJSONPath();
122
+ if (miqroRCPath) {
123
+ writeFile(logger, join(inflateDir, "miqro.json"), readFileSync(miqroRCPath));
124
+ }
125
+ }
126
+
127
+ export async function inflateServiceForSea(logger: Logger, inflateDir: string, service: string, servicePath: string/*, serviceMigrations: string[]*/, serviceRouteFileMap: RouteFileMap, serviceStaticFileMap: StaticFileMap) {
128
+ const migrationsFolderPath = getMigrationsPath(servicePath);
129
+
130
+ const serviceMigrations: string[] = migrationsFolderPath ? migration.getSortedMigrations(migrationsFolderPath) : [];
131
+ writeFile(logger, join(inflateDir, "sea", service, "router.cjs"), `const { appendAPIModule, Router, middleware } = require("./../lib.cjs");\n
132
+ async function setupRouter() {
133
+ const router = new Router();
134
+ ${getErrorConfigPath(servicePath) ? `
135
+ const errorConfig = (await require("../../${service}/catch.cjs")).default;
136
+ if(errorConfig && errorConfig.catch) {
137
+ for(const m of errorConfig.catch) {
138
+ router.catch(m);
139
+ }
140
+ }` : ""}
141
+ ${getCORSConfigPath(servicePath) ? ` router.use(middleware.cors((await require("../../${service}/cors.cjs")).default));` : ""}
142
+ ${getAuthConfigPath(servicePath) ? ` router.use(middleware.session((await require("../../${service}/auth.cjs")).default));` : ""}
143
+ ${getMiddlewareConfigPath(servicePath) ? `
144
+ const middlewareConfig = (await require("../../${service}/middleware.cjs")).default;
145
+ if(middlewareConfig && middlewareConfig.middleware) {
146
+ for(const m of middlewareConfig.middleware) {
147
+ router.use(m);
148
+ }
149
+ }` : ""}
150
+ ${Object.keys(serviceRouteFileMap)
151
+ .map(filePath => serviceRouteFileMap[filePath])
152
+ .filter(data => data.previewMethod === "api")
153
+ .map(data => data.routes.map(r => {
154
+ const rPath = join(relative(cwd(), dirname(data.filePath)), basename(data.filePath));
155
+ if (rPath) {
156
+ const rPathExt = extname(rPath);
157
+ const apiInflatedPath = join("..", "..", rPath.substring(0, rPath.length - rPathExt.length) + ".cjs");
158
+ return ` await appendAPIModule(router, "../../${service}/http", "./${apiInflatedPath}", (await require("./${apiInflatedPath}")).default);`;
159
+ } else {
160
+ return "";
161
+ }
162
+ }).filter(l => l)[0])
163
+ .join("\n")}
164
+ router.use(await (await require("./static-router.cjs")).setupRouter())
165
+
166
+ ${getMiddlewareConfigPath(servicePath) ? `
167
+ if(middlewareConfig && middlewareConfig.post) {
168
+ for(const m of middlewareConfig.post) {
169
+ router.use(m);
170
+ }
171
+ }` : ""}
172
+
173
+ return router;
174
+ }
175
+ module.exports = {
176
+ setupRouter
177
+ }`);
178
+
179
+ writeFile(logger, join(inflateDir, "sea", service, "migration-up.cjs"), `const { migration } = require("./../lib.cjs");\n
180
+ async function runMigrations(db) {
181
+ await migration.init(db);
182
+ ${serviceMigrations.map(file => {
183
+ const name = `${file.substring(0, file.length - extname(file).length)}`;
184
+ return ` await migration.up.module(db, "${file}", (await require("../../${service}/migration/${name}.cjs")).default)`;
185
+ }).join("\n")}
186
+ }
187
+ module.exports = {
188
+ runMigrations
189
+ }`);
190
+
191
+ writeFile(logger, join(inflateDir, "sea", service, "migration-down.cjs"), `const { migration } = require("./../lib.cjs");\n
192
+ async function runMigrations(db) {
193
+ await migration.init(db);
194
+ ${serviceMigrations.reverse().map(file => {
195
+ const name = `${file.substring(0, file.length - extname(file).length)}`;
196
+ return ` await migration.down.module(db, "${file}", (await require("../../${service}/migration/${name}.cjs")).default)`;
197
+ }).join("\n")}
198
+ }
199
+ module.exports = {
200
+ runMigrations
201
+ }`);
202
+
203
+ const staticFiles = Object.keys(serviceStaticFileMap);
204
+ /*if (staticFiles.length !== 0) {
205
+ writeFile(logger, join(inflateDir, "sea", service, "static.base64.json"), JSON.stringify(serviceStaticFileMap));
206
+ }*/
207
+ writeFile(logger, join(inflateDir, "sea", service, "static-router.cjs"), `const { appendAPIModule, Router } = require("./../lib.cjs");\n
208
+ async function setupRouter() {
209
+ const router = new Router();
210
+ ${staticFiles.length === 0 ? "" : `
211
+ ${staticFiles.map((filePath) => {
212
+ return ` router.get("${serviceStaticFileMap[filePath].path}", async (_, res) => {
213
+ return res.asyncEnd({
214
+ status: 200,
215
+ headers: {
216
+ ["Content-Type"]: "${serviceStaticFileMap[filePath].contentType}"
217
+ },
218
+ body: Buffer.from("${serviceStaticFileMap[filePath].body.toString("base64")}", "base64")
219
+ });
220
+ });`;
221
+ }).join("\n")}
222
+ `}
223
+ return router;
224
+ }
225
+ module.exports = {
226
+ setupRouter
227
+ }`);
228
+
229
+ }
230
+
231
+ function writeFile(logger: Logger, path: string, buffer: Buffer | string) {
232
+ logger.log("writing [%s]", relative(cwd(), path));
233
+ mkdirSync(dirname(path), {
234
+ recursive: true
235
+ });
236
+ writeFileSync(path, buffer);
237
+ }
@@ -0,0 +1,101 @@
1
+ import { InflateError } from "../common/jsx.js";
2
+ import { Logger, Router } from "@miqro/core";
3
+ import { RouteFileMap, setupHTTPRouter, StaticFileMap } from "./setup-http.js";
4
+ //import { WSMapConfig } from "./utils/websocketmanager.js";
5
+ //import { ServerConfigMap, setupServerConfig } from "./setup-server-config.js";
6
+ // import { assertGlobalTampered } from "../services/globals.js";
7
+ import { getServicePath } from "../common/paths.js";
8
+ import { inflateWSConfig } from "./setup-ws.js";
9
+ import { inflateAppForSea, inflateServiceForSea } from "./inflate-sea.js";
10
+ import { ServerInterface, WSConfig } from "../types.js";
11
+ import { LogConfigMap, setupLogConfig } from "./setup-log.js";
12
+ import { setupDoc } from "./setup.doc.js";
13
+
14
+ export interface InflateAppOptions {
15
+ logger?: Logger;
16
+ services: string[];
17
+ //dbManager: DBManager;
18
+ inflateDir: string | undefined | false;
19
+ inflateSea: boolean;
20
+ //editor: boolean;
21
+ //inflateTests: boolean;
22
+ hotreload?: boolean;
23
+ port: string;
24
+ serverInterface: ServerInterface;
25
+ inflateParallel?: number;
26
+ }
27
+
28
+ export async function inflateApp({ inflateParallel, serverInterface, logger, hotreload, services/*, dbManager*/, inflateDir, inflateSea/*, editor, inflateTests*/, port }: InflateAppOptions): Promise<[Router, InflateError[] | null, RouteFileMap, WSConfig[]/*, ServerConfigMap*/, LogConfigMap]> {
29
+ logger.trace("inflateApp");
30
+ const errors: InflateError[] = [];
31
+ //const migrations: string[] = [];
32
+ let routeFileMap: RouteFileMap = {};
33
+ const wsConfigList: WSConfig[] = [];
34
+ const router = new Router();
35
+ const logConfigMap: LogConfigMap = {};
36
+ //const serverConfigMap: ServerConfigMap = {};
37
+
38
+ // router.use(assertGlobalTampered);
39
+
40
+ /*if (editor) {
41
+ logger.info("setting up editor on %s", BASEEDITOR_PATH);
42
+ const editorRouter = await createEditorRouter();
43
+ router.use(editorRouter);
44
+ logger.info("setting up ws on [%s]", LOG_SOCKET_PATH);
45
+ wsConfigList.push(editorWSConfig);
46
+ serverConfigMap[EDITOR_CONFIG_KEY] = editorServerConfig;
47
+ }*/
48
+
49
+
50
+
51
+ for (const service of services) {
52
+ const serviceRouteFileMap: RouteFileMap = {};
53
+ const serviceStaticFileMap: StaticFileMap | null = inflateSea ? {} : null;
54
+ const servicePath = getServicePath(service);
55
+
56
+ /*const migrationsFolderPath = getMigrationsPath(servicePath);
57
+
58
+ const serviceMigrations: string[] = migrationsFolderPath ? migration.getSortedMigrations(migrationsFolderPath) : [];*/
59
+
60
+ /*const db = dbManager.getDB(service) ? dbManager.getDB(service) : await setupDB(logger, service, dbManager, inflateDir);;
61
+
62
+ if (db && (cluster.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === "0")) {
63
+ await runMigrations(logger, db, servicePath, service, inflateDir, serviceMigrations);
64
+ }
65
+ if (db) {
66
+ migrations.push(...serviceMigrations);
67
+ }*/
68
+
69
+ //await setupDB(logger, service, dbConfigList, inflateDir);
70
+
71
+ await setupLogConfig(logger, servicePath, service, logConfigMap, inflateSea ? inflateDir : false, errors);
72
+
73
+ router.use(await setupHTTPRouter(serverInterface, logger, hotreload ? hotreload : false, servicePath, service, serviceRouteFileMap, serviceStaticFileMap, inflateDir, inflateSea, errors, inflateParallel));
74
+ routeFileMap = {
75
+ ...routeFileMap,
76
+ ...serviceRouteFileMap
77
+ };
78
+
79
+ await setupDoc(logger, servicePath, service, router, routeFileMap, serviceStaticFileMap, inflateDir, errors);
80
+
81
+ await inflateWSConfig(logger, servicePath, service, wsConfigList, inflateSea ? inflateDir : undefined, errors);
82
+
83
+ //await setupServerConfig(logger, servicePath, service, serverConfigMap, inflateSea ? inflateDir : undefined, errors);
84
+
85
+ if (inflateDir && inflateSea) {
86
+ await inflateServiceForSea(logger, inflateDir, service, servicePath /*, serviceMigrations*/, serviceRouteFileMap, serviceStaticFileMap);
87
+ }
88
+
89
+ /*if (inflateTests) {
90
+ await setupTests(logger, servicePath);
91
+ }*/
92
+ }
93
+
94
+ if (inflateDir && inflateSea) {
95
+ await inflateAppForSea(logger, inflateDir, services, port);
96
+ }
97
+
98
+ // router.use(assertGlobalTampered);
99
+
100
+ return errors.length === 0 ? [router, null, routeFileMap/*, migrations*/, wsConfigList/*, serverConfigMap*/, logConfigMap] : [router, errors, routeFileMap/*, migrations*/, wsConfigList/*, serverConfigMap*/, logConfigMap];
101
+ }
@@ -0,0 +1,25 @@
1
+
2
+ import * as showdown from "showdown";
3
+ import { readFileSync } from "node:fs";
4
+ import { Logger } from "@miqro/core";
5
+
6
+ export function inflateMD2HTML(inFile: string, logger?: Logger): string {
7
+ try {
8
+ const text = readFileSync(inFile).toString();
9
+ const html = inflateMDString2HTML(text);
10
+ return html;
11
+ } catch (e) {
12
+ logger?.error("error with: " + inFile);
13
+ logger?.error(e);
14
+ throw e;
15
+ }
16
+ }
17
+
18
+ export function inflateMDString2HTML(text: string, logger?: Logger): string {
19
+ const converter = new (showdown as any).default.Converter();
20
+ converter.setFlavor('github');
21
+ /*converter.setOption("tables", true);
22
+ converter.setOption("rawHeaderId", true);*/
23
+ const html = converter.makeHtml(text);
24
+ return html;
25
+ }
@@ -0,0 +1,41 @@
1
+ import { Logger, Router, SessionHandler } from "@miqro/core";
2
+ import { importAuthModule, InflateError, inflateJSX } from "../common/jsx.js";
3
+ import { getAuthConfigPath } from "../common/paths.js";
4
+ import { basename, dirname, join, relative, resolve } from "node:path";
5
+ import { mkdirSync, writeFileSync } from "node:fs";
6
+ import { cwd } from "node:process";
7
+
8
+ export async function setupAUTH(logger: Logger, servicePath: string, service: string, mainRouter: Router, inflateDir: string | undefined | false, inflateSea: boolean, errors: InflateError[]) {
9
+ const authPath = getAuthConfigPath(servicePath); //resolve(process.cwd(), service, "auth.ts");
10
+
11
+ if (authPath) {
12
+ try {
13
+ const authModule = await importAuthModule(authPath, logger);
14
+ logger.debug("setting up authentication from [%s]", join(service, basename(authPath)));
15
+ mainRouter.use(SessionHandler(authModule));
16
+
17
+ if (inflateDir && inflateSea) {
18
+ const inflatePath = resolve(inflateDir, service, "auth.cjs");
19
+ mkdirSync(dirname(inflatePath), {
20
+ recursive: true
21
+ });
22
+ logger.log("writing [%s]", relative(cwd(), inflatePath));
23
+ writeFileSync(inflatePath, await inflateJSX(authPath, {
24
+ // embemedJSX: false,
25
+ minify: false,
26
+ useExport: true,
27
+ platform: "node",
28
+ logger
29
+ }));
30
+ }
31
+
32
+ } catch (e) {
33
+ errors.push({
34
+ filePath: authPath,
35
+ error: e
36
+ });
37
+ logger.error("error with " + authPath);
38
+ logger.error(e);
39
+ }
40
+ }
41
+ }
@@ -0,0 +1,41 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { importCORSModule, InflateError, inflateJSX } from "../common/jsx.js";
3
+ import { getCORSConfigPath } from "../common/paths.js";
4
+ import { CORS, Logger, Router } from "@miqro/core";
5
+ import { basename, dirname, join, relative, resolve } from "node:path";
6
+ import { cwd } from "node:process";
7
+
8
+ export async function setupCORS(logger: Logger, servicePath: string, service: string, mainRouter: Router, inflateDir: string | undefined | false, inflateSea: boolean, errors: InflateError[]) {
9
+ const corsPath = getCORSConfigPath(servicePath);
10
+
11
+ if (corsPath) {
12
+ try {
13
+ const corsOptions = await importCORSModule(corsPath, logger);
14
+ logger.debug("setting up cors from [%s]", join(service, basename(corsPath)));
15
+ mainRouter.use(CORS(corsOptions));
16
+
17
+ if (inflateDir && inflateSea) {
18
+ const inflatePath = resolve(inflateDir, service, "cors.cjs");
19
+ mkdirSync(dirname(inflatePath), {
20
+ recursive: true
21
+ });
22
+ logger.log("writing [%s]", relative(cwd(), inflatePath));
23
+ writeFileSync(inflatePath, await inflateJSX(corsPath, {
24
+ // embemedJSX: false,
25
+ minify: false,
26
+ useExport: true,
27
+ platform: "node",
28
+ logger
29
+ }));
30
+ }
31
+
32
+ } catch (e) {
33
+ errors.push({
34
+ filePath: corsPath,
35
+ error: e
36
+ });
37
+ logger.error("error with " + corsPath);
38
+ logger.error(e);
39
+ }
40
+ }
41
+ }