@nexint/lumina 0.0.0-stage → 0.7.7

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.
@@ -0,0 +1,229 @@
1
+ const fs = require("node:fs");
2
+ const path = require('path');
3
+ const { log } = require("./log.mjs");
4
+ const { getConfig } = require("#functions/core/getConfig");
5
+ const { verbose, errorPolicy } = getConfig("core/core");
6
+ const { forceShutdown } = require("./fatalShutdown.mjs");
7
+
8
+ /**
9
+ * helper lol
10
+ * @param {String} dir
11
+ * @param {Function} func
12
+ * @param {Object} [options]
13
+ * @param {String} [options.root=process.cwd()]
14
+ * @param {Boolean} [options.cachedOnly=false]
15
+ * @param {Boolean} [options.fatal=true]
16
+ * @param {String} [options.errorMessage]
17
+ */
18
+ const loadDirHelper = async function (dir, func, { root = process.cwd(), cachedOnly = false, fatal = true, errorMessage = "Failed to load files." } = {}) {
19
+
20
+ let success = true;
21
+
22
+ const dirPath = path.join(root, dir);
23
+
24
+ const files = fs.readdirSync(dirPath, { recursive: true });
25
+ for (const file of files) {
26
+
27
+ // Only load JS files (trust)
28
+ if ([".js", ".cjs", ".mjs"].includes(path.extname(file).toLowerCase())) {
29
+ const filePath = path.join(dirPath, file);
30
+
31
+ // Execute the plugin?
32
+ try {
33
+ let plugin;
34
+
35
+ // Load only pre-existing cached files.
36
+ if (cachedOnly) {
37
+ const filename = require.resolve(filePath);
38
+ const cached = require.cache[filename];
39
+
40
+ if (!cached || !cached.loaded) continue;
41
+
42
+ plugin = cached.exports;
43
+ } else {
44
+ plugin = require(filePath);
45
+ }
46
+
47
+ // good question
48
+ if (await func(plugin, file) === true) {
49
+ return { success, stopped: true };
50
+ }
51
+ } catch (error) {
52
+ success = false;
53
+
54
+ if (errorPolicy.uncaughtException === "continue") {
55
+ continue;
56
+ }
57
+
58
+ log.error(errorMessage);
59
+ log.error(`Problematic file: ${filePath}`, error);
60
+
61
+ if (fatal && errorPolicy.uncaughtException !== "warn") {
62
+ await forceShutdown(errorMessage);
63
+ }
64
+ }
65
+ }
66
+ }
67
+
68
+ return { success, stopped: false };
69
+ }
70
+
71
+ /**
72
+ * Find files
73
+ * This runs the execute function.
74
+ * @param {String} dir
75
+ * @param {String} [root] - Defaults to the working directory.
76
+ * @returns
77
+ */
78
+ const queryFiles = async function (dir, root) {
79
+
80
+ let count = 0;
81
+
82
+ const queryHelper = (plugin) => {
83
+ if ('execute' in plugin || 'command' in plugin) {
84
+ count++;
85
+ }
86
+ }
87
+
88
+ await loadDirHelper(dir, queryHelper, { root });
89
+
90
+ return count;
91
+ }
92
+
93
+ /**
94
+ * Load files in a specific directory.
95
+ * This runs the execute function.
96
+ * @param {String} dir
97
+ * @param {String} [root] - Defaults to the working directory.
98
+ */
99
+ const load = async function (dir, root) {
100
+ let count = 0;
101
+
102
+ const loadHelper = async (plugin, file) => {
103
+ if ('execute' in plugin && !('data' in plugin)) {
104
+ await plugin.execute();
105
+ count++;
106
+
107
+ if (verbose) {
108
+ log.info(`Loaded file: ${path.join(dir, file)}`);
109
+ }
110
+ }
111
+ }
112
+
113
+ await loadDirHelper(dir, loadHelper, { root });
114
+
115
+ return count;
116
+ }
117
+
118
+ /**
119
+ * Load console files
120
+ * This runs the console function.
121
+ * @param {String} dir
122
+ * @param {String} command
123
+ * @param {String} [root] - Defaults to the working directory.
124
+ */
125
+ const loadConsole = async function (dir, command, root) {
126
+
127
+ const loadConsoleHelper = async (plugin, file) => {
128
+ if ('command' in plugin) {
129
+ const validCommand = await plugin.command(command);
130
+
131
+ if (verbose) {
132
+ log.info(`Loaded file: ${path.join(dir, file)}`);
133
+ }
134
+
135
+ return Boolean(validCommand);
136
+ }
137
+ }
138
+
139
+ const { stopped } = await loadDirHelper(dir, loadConsoleHelper, {
140
+ root,
141
+ errorMessage: "Failed to load console files."
142
+ });
143
+
144
+ return stopped;
145
+ }
146
+
147
+ /**
148
+ * Load help menu.
149
+ * This is meant to run dynamically.
150
+ * @param {String} dir
151
+ * @param {String} [root] - Defaults to the working directory.
152
+ */
153
+ const loadHelp = async function (dir, root) {
154
+ let helpArray = [];
155
+
156
+ const loadHelpHelper = async (plugin) => {
157
+ if ('help' in plugin) {
158
+ helpArray = helpArray.concat(await plugin.help());
159
+ }
160
+ }
161
+
162
+ await loadDirHelper(dir, loadHelpHelper, {
163
+ root,
164
+ errorMessage: "Failed to load help menu."
165
+ });
166
+
167
+ return helpArray;
168
+ }
169
+
170
+ /**
171
+ * Close everything (shut it all down) safely.
172
+ * @param {String} dir
173
+ * @param {String} [root] - Defaults to the working directory.
174
+ */
175
+ const close = async function (dir, root) {
176
+
177
+ const closeHelper = async (plugin, file) => {
178
+ if ('close' in plugin) {
179
+ await plugin.close();
180
+
181
+ if (verbose) {
182
+ log.info(`Closed file: ${path.join(dir, file)}`);
183
+ }
184
+ }
185
+ }
186
+
187
+ const { success } = await loadDirHelper(dir, closeHelper, {
188
+ root,
189
+ cachedOnly: true,
190
+ fatal: false,
191
+ errorMessage: "Failed to close app."
192
+ });
193
+
194
+ return success;
195
+ }
196
+
197
+ /**
198
+ * Refresh everything
199
+ * @param {String} dir
200
+ * @param {String} [root] - Defaults to the working directory.
201
+ */
202
+ const refresh = async function (dir, root) {
203
+
204
+ const refreshHelper = async (plugin, file) => {
205
+ if ('reload' in plugin) {
206
+ await plugin.reload();
207
+
208
+ if (verbose) {
209
+ log.info(`Refreshed file: ${path.join(dir, file)}`);
210
+ }
211
+ }
212
+ }
213
+
214
+ const { success } = await loadDirHelper(dir, refreshHelper, {
215
+ root,
216
+ errorMessage: "Failed to refresh app."
217
+ });
218
+
219
+ return success;
220
+ }
221
+
222
+ module.exports = {
223
+ load,
224
+ loadConsole,
225
+ loadHelp,
226
+ close,
227
+ refresh,
228
+ queryFiles
229
+ }
@@ -0,0 +1,174 @@
1
+ import config from "#functions/core/getConfig";
2
+ const { getConfig } = config;
3
+ const { dateOptions } = getConfig("core/core");
4
+ import { styleText, inspect } from "node:util";
5
+ import { forceShutdown } from "./fatalShutdown.mjs";
6
+ import { writeLogFile } from "#preload/core/fileLog";
7
+ const DateFormatter = new Intl.DateTimeFormat(undefined, dateOptions)
8
+ let infoCount = 0;
9
+ let successCount = 0;
10
+ let warnCount = 0;
11
+ let errorCount = 0;
12
+ let eventCount = 0;
13
+ let fatalCount = 0;
14
+ let fatal = false;
15
+ const log = {
16
+
17
+ /**
18
+ * Info event
19
+ * @param {String} text
20
+ */
21
+ info: function (text) {
22
+ console.log(`[INFO] [${DateFormatter.format(Date.now())}] ${text}`);
23
+ infoCount += 1;
24
+ },
25
+
26
+ /**
27
+ * Successful event!
28
+ * @param {String} text
29
+ */
30
+ success: function (text) {
31
+
32
+ const messages = [
33
+ `[SUCCESS] [${DateFormatter.format(Date.now())}] ${text}`,
34
+ ]
35
+
36
+ for (const message of messages) {
37
+ console.log(styleText("greenBright", message))
38
+ writeLogFile(message)
39
+ }
40
+ successCount += 1;
41
+ },
42
+
43
+ /**
44
+ * Log a given event lol
45
+ * @param {String} text
46
+ */
47
+ event: function (text) {
48
+
49
+ const messages = [
50
+ `[EVENT] [${DateFormatter.format(Date.now())}] ${text}`,
51
+ ]
52
+
53
+ for (const message of messages) {
54
+ console.log(styleText("blueBright", message))
55
+ writeLogFile(message)
56
+ }
57
+ eventCount += 1;
58
+ },
59
+
60
+ /**
61
+ * Warning event
62
+ * @param {String} text
63
+ */
64
+ warn: function (text) {
65
+
66
+ const messages = [
67
+ `[WARN] [${DateFormatter.format(Date.now())}] ${text}`,
68
+ ]
69
+
70
+ for (const message of messages) {
71
+ console.log(styleText("yellowBright", message))
72
+ writeLogFile(message)
73
+ }
74
+ warnCount += 1;
75
+ },
76
+
77
+ /**
78
+ * Error event
79
+ * @param {String} text
80
+ * @param {Error} error
81
+ */
82
+ error: function (text, error) {
83
+
84
+ const messages = [
85
+ `[ERROR] [${DateFormatter.format(Date.now())}] ${text}`,
86
+ ]
87
+
88
+ for (const message of messages) {
89
+ console.error(styleText("redBright", message))
90
+ writeLogFile(message)
91
+ }
92
+
93
+ if (error) {
94
+ console.error(error)
95
+
96
+ const formatted = inspect(error, {
97
+ depth: null,
98
+ colors: false,
99
+ showHidden: true
100
+ });
101
+ writeLogFile(formatted)
102
+ }
103
+ errorCount += 1;
104
+ },
105
+
106
+ /**
107
+ * Fatal event
108
+ * @param {String} text
109
+ * @param {Error} error
110
+ * @param {Number} code
111
+ * @param {Boolean} shutdown
112
+ */
113
+ fatal: async function (text, error, code = 0x0000, shutdown = false) {
114
+
115
+ fatalCount += 1;
116
+ const hexCode = `0x${code.toString(16).toUpperCase().padStart(4, "0")}`;
117
+
118
+ const messages = [
119
+ `[FATAL] [${DateFormatter.format(Date.now())}] ${text}`,
120
+ `[FATAL] [${DateFormatter.format(Date.now())}] Code: ${hexCode}`,
121
+ `[FATAL] [${DateFormatter.format(Date.now())}] Info Events: ${infoCount}`,
122
+ `[FATAL] [${DateFormatter.format(Date.now())}] Success Events: ${successCount}`,
123
+ `[FATAL] [${DateFormatter.format(Date.now())}] Warn Events: ${warnCount}`,
124
+ `[FATAL] [${DateFormatter.format(Date.now())}] Error Events: ${errorCount}`,
125
+ `[FATAL] [${DateFormatter.format(Date.now())}] Fatal Events: ${fatalCount}`,
126
+ `[FATAL] [${DateFormatter.format(Date.now())}] General Events: ${eventCount}`,
127
+ ]
128
+
129
+ for (const message of messages) {
130
+ console.error(styleText("red", message))
131
+ writeLogFile(message)
132
+ }
133
+
134
+ if (error) {
135
+ console.error(error)
136
+
137
+ const formatted = inspect(error, {
138
+ depth: null,
139
+ colors: false,
140
+ showHidden: true
141
+ });
142
+ writeLogFile(formatted)
143
+ }
144
+
145
+
146
+
147
+ if (shutdown && !fatal) {
148
+ fatal = true
149
+ await forceShutdown(text);
150
+ process.exit(1) // This should never run
151
+ }
152
+ },
153
+ }
154
+
155
+ const getInfo = function () {
156
+ return infoCount
157
+ }
158
+ const getSuccess = function () {
159
+ return successCount
160
+ }
161
+ const getWarn = function () {
162
+ return warnCount
163
+ }
164
+ const getError = function () {
165
+ return errorCount
166
+ }
167
+ const getEvent = function () {
168
+ return eventCount
169
+ }
170
+ const getFatal = function () {
171
+ return fatalCount
172
+ }
173
+
174
+ export { log, getInfo, getSuccess, getWarn, getError, getEvent, getFatal };
@@ -0,0 +1,212 @@
1
+ const { clearDirectory } = require("./clearCache");
2
+ const { date } = require("./date");
3
+ const { close, refresh, load } = require("./load");
4
+ const { log } = require("./log.mjs");
5
+ const { root, frameworkDir, standalone } = require("#functions/core/dirs")
6
+
7
+ let shutDownState = null;
8
+ let otherState = null;
9
+
10
+ /**
11
+ * Graceful Shutdown of bot
12
+ * Exit: Determines if the process exits immediately or not.
13
+ * @param {String} cause
14
+ * @param {Boolean} exit
15
+ */
16
+ const gracefulShutdown = async function (cause, exit) {
17
+ if (shutDownState) {
18
+ await log.fatal(`Additional shutdown requested during active shutdown. Escalating to forced shutdown. Cause: ${cause}`, null, 0x0004, true);
19
+ process.exit(1) // again, this shouldnt happen in any circumstance, but just a failsafe :)
20
+ }
21
+ if (otherState) {
22
+ log.error(`This app is in an undefined state. Shutting down to avoid conflicts.`)
23
+ await log.fatal(`Shutdown triggered while another power operation was happening. Cause: ${cause}`, null, 0x0004, true);
24
+ process.exit(1) // again, this shouldnt happen in any circumstance, but just a failsafe :)
25
+ }
26
+ shutDownState = true;
27
+
28
+ try {
29
+ log.info(`\x1b[36m--------------------- Nex ${date.getFullYear()} ---------------------\x1b[0m`)
30
+ log.event(`Shutdown triggered by: ${cause}`)
31
+ log.event("Closing all apps...")
32
+ let success = true;
33
+ let dirs = ["apps", "plugins", "preload"];
34
+
35
+ // Close Apps
36
+ for (const dir of dirs) {
37
+ if (!await close(dir, root)) {
38
+ success = false
39
+ }
40
+ }
41
+
42
+ // Close Framework
43
+ if (!standalone) {
44
+ dirs = ["plugins", "preload"];
45
+ for (const dir of dirs) {
46
+ if (!await close(dir, frameworkDir)) {
47
+ success = false
48
+ }
49
+ }
50
+ }
51
+
52
+ if (!success) {
53
+ log.error("One or more components failed to close.");
54
+ } else {
55
+ log.event("All components closed successfully.");
56
+ }
57
+ log.event("Shutting down.")
58
+ log.info(`\x1b[36m----------------------------------------------------\x1b[0m`)
59
+ shutDownState = false;
60
+ if (exit) {
61
+ if (success) {
62
+ process.exit(0);
63
+ } else {
64
+ process.exit(1);
65
+ }
66
+ }
67
+ return success;
68
+ } catch (error) {
69
+ await log.fatal("An unexpected error happened while trying to shut down.", error, 0x0005, true)
70
+ process.exit(1);
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Reloads files
76
+ * @param {String} cause
77
+ * @returns
78
+ */
79
+ const reload = async function (cause) {
80
+
81
+ // State machine
82
+ if (otherState || shutDownState) {
83
+ return false;
84
+ }
85
+ otherState = true;
86
+ try {
87
+ log.info(`\x1b[36m---------------------- Reload ----------------------\x1b[0m`)
88
+ const startReload = Date.now()
89
+ log.event(`Reload triggered by: ${cause}`)
90
+
91
+ // Closes apps and plugins
92
+ let success = true;
93
+ let dirs = ["apps", "plugins"];
94
+
95
+ // Reload App Dirs
96
+ for (const dir of dirs) {
97
+ if (!await close(dir, root)) {
98
+ success = false
99
+ }
100
+ }
101
+
102
+ // Reload Framework
103
+ if (!standalone) {
104
+ dirs = ["plugins"];
105
+ for (const dir of dirs) {
106
+ if (!await close(dir, frameworkDir)) {
107
+ success = false
108
+ }
109
+ }
110
+ }
111
+
112
+ // Determine if successful
113
+ if (!success) {
114
+ await log.fatal("One or more components failed to close.", null, 0x0003, true);
115
+ process.exit(1) // again, this shouldnt happen in any circumstance, but just a failsafe :)
116
+ } else {
117
+ log.success("Apps have been taken temporarily offline.");
118
+ }
119
+
120
+ let cleared = 0;
121
+ let clearedDirs = ["apps", "plugins", "functions", "test", "config", "console"]
122
+
123
+ // Clear non framework dirs
124
+ // Sidenote: This shouldn't technically need an order lol
125
+ for (const dir of clearedDirs) {
126
+ cleared += clearDirectory(dir, root)
127
+ }
128
+
129
+ // Clear framework dirs
130
+ if (!standalone) {
131
+ clearedDirs = ["plugins", "functions", "test", "config", "console"]
132
+ for (const dir of clearedDirs) {
133
+ cleared += clearDirectory(dir, frameworkDir)
134
+ }
135
+ }
136
+
137
+ log.success(`Cleared ${cleared} files!`)
138
+
139
+ // Load Framework
140
+ await load("plugins", frameworkDir);
141
+
142
+ // Load Apps
143
+ if (!standalone) {
144
+ await load("plugins", root);
145
+ }
146
+
147
+ await load("apps", root);
148
+ log.success(`Reload complete in ${(Date.now() - startReload) / 1000}s!`)
149
+ log.warn("Note: Reloading is unstable and not explicitly supported. If things don't work, restart.")
150
+ log.info(`\x1b[36m--------------------- Nex ${date.getFullYear()} ---------------------\x1b[0m`)
151
+ otherState = false;
152
+ return true;
153
+ } catch (error) {
154
+ await log.fatal("An unexpected error has happened while reloading.", error, 0x0005, true)
155
+ process.exit(1);
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Refreshes the Discord part lol
161
+ * @returns
162
+ */
163
+ const refreshCycle = async function (cause) {
164
+
165
+ // State machine
166
+ if (otherState || shutDownState) {
167
+ return false;
168
+ }
169
+ otherState = true;
170
+ try {
171
+ log.info(`\x1b[36m------------------- Refresh real --------------------\x1b[0m`)
172
+ const startRefresh = Date.now()
173
+ log.event(`Refresh triggered by: ${cause}`)
174
+
175
+ // Start refreshing
176
+
177
+ let cleared = 0;
178
+ const clearedDirs = ["functions", "config", "console"]
179
+
180
+ // Clear non framework dirs
181
+ for (const dir of clearedDirs) {
182
+ cleared += clearDirectory(dir, root)
183
+ cleared += clearDirectory(dir, frameworkDir)
184
+ }
185
+
186
+ log.success(`Cleared ${cleared} files!`)
187
+ const success = await refresh("apps", root);
188
+
189
+ // Determine success or not
190
+ if (!success) {
191
+ await log.fatal("One or more components failed to refresh.", null, 0x0004, true);
192
+ process.exit(1) // again, this shouldnt happen in any circumstance, but just a failsafe :)
193
+ } else {
194
+ log.success(`Refresh complete in ${(Date.now() - startRefresh) / 1000}s!`)
195
+ }
196
+
197
+ // Cleanup
198
+ log.warn("Note: Refreshing is unstable and not explicitly supported. If things don't work, restart or reload.")
199
+ log.info(`\x1b[36m--------------------- Nex ${date.getFullYear()} ---------------------\x1b[0m`)
200
+ otherState = false;
201
+ return true;
202
+ } catch (error) {
203
+ await log.fatal("An unexpected error has happened while reloading.", error, 0x0005, true)
204
+ process.exit(1);
205
+ }
206
+ }
207
+
208
+ module.exports = {
209
+ gracefulShutdown,
210
+ reload,
211
+ refreshCycle
212
+ }
@@ -0,0 +1,78 @@
1
+ const { log } = require("./log.mjs");
2
+
3
+ const { frameName, frameVer, frameID, updateSource, updateURL } = require('#config/core/framework');
4
+
5
+ /**
6
+ * Gets the latest version of this bot!
7
+ * @returns
8
+ */
9
+ const getUpdateVersion = async function () {
10
+ try {
11
+ // Update Versions
12
+ const update = await fetch(updateSource + "/ver.txt");
13
+ if (!update.ok) {
14
+ throw new Error(`HTTP ${update.status}: ${update.statusText}`);
15
+ }
16
+
17
+ // Update Version
18
+ const updateName = await fetch(updateSource + "/verName.txt");
19
+ if (!updateName.ok) {
20
+ throw new Error(`HTTP ${updateName.status}: ${updateName.statusText}`);
21
+ }
22
+
23
+ // Get the actual versions lol
24
+ const tmp = await update.text();
25
+ const version = Number(tmp)
26
+ const result = await updateName.text();
27
+ const versionName = result
28
+
29
+ // isNan?
30
+ if (!Number.isNaN(version)) {
31
+ return [versionName, version]
32
+ } else {
33
+ throw new Error("Not a Number.")
34
+ }
35
+ } catch (error) {
36
+ log.error("An error happened while trying to check for updates!")
37
+ log.error("Likely caused by the bot being unable to access Github. Full stack trace:", error)
38
+ return 0;
39
+ }
40
+ };
41
+
42
+
43
+ /**
44
+ * Update Checker
45
+ * If it's the initial check, it notifies even if it's the latest version.
46
+ * If not, it does not notify.
47
+ * @param {Boolean} initial
48
+ */
49
+ const updateCheck = async function (initial) {
50
+ const check = await getUpdateVersion();
51
+ if (!check) {
52
+ log.error(`Something went wrong updating ${frameName}!`)
53
+ return;
54
+ }
55
+ const [versionName, latestVersion] = check
56
+
57
+ if (frameID < latestVersion) {
58
+ log.warn(`You're running an outdated version of ${frameName}! (You are ${latestVersion - frameID} commits behind)`)
59
+ log.warn(`Update now at ${updateURL} to make sure that ${frameName} has the latest security fixes!`)
60
+ if ((latestVersion - frameID) >= 5) {
61
+ log.warn(`You are over 5 commits behind. Update to the latest version as soon as possible.`)
62
+ }
63
+ log.warn(`Current version: v${frameVer} / Latest Version: ${versionName}`)
64
+ } else if (latestVersion <= 0) {
65
+ log.warn(`This instance of ${frameName} is fetching an invalid version.`)
66
+ } else if (frameID > latestVersion) {
67
+ log.warn(`You're running an experimental version of ${frameName}! (You are ${frameID - latestVersion} commits ahead)`)
68
+ log.warn(`Here be dragons!~`)
69
+ log.warn(`Current version: v${frameVer} / Latest Version: ${versionName}`)
70
+ } else if (initial) {
71
+ log.info(`You're running the latest version of ${frameName}!`)
72
+ }
73
+ }
74
+
75
+ module.exports = {
76
+ getUpdateVersion,
77
+ updateCheck
78
+ }