@ezetgalaxy/titan 26.8.0 → 26.8.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.
@@ -1,194 +1,266 @@
1
- import chokidar from "chokidar";
2
- import { spawn, execSync } from "child_process";
3
- import path from "path";
4
- import { fileURLToPath } from "url";
5
- import fs from "fs";
6
- import { bundle } from "./bundle.js";
7
-
8
- // Required for __dirname in ES modules
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = path.dirname(__filename);
11
-
12
-
13
- // Colors
14
- import { createRequire } from "module";
15
-
16
- // Colors
17
- const cyan = (t) => `\x1b[36m${t}\x1b[0m`;
18
- const green = (t) => `\x1b[32m${t}\x1b[0m`;
19
- const yellow = (t) => `\x1b[33m${t}\x1b[0m`;
20
- const red = (t) => `\x1b[31m${t}\x1b[0m`;
21
- const gray = (t) => `\x1b[90m${t}\x1b[0m`;
22
- const bold = (t) => `\x1b[1m${t}\x1b[0m`;
23
-
24
- function getTitanVersion() {
25
- try {
26
- // 1. Try resolving from node_modules (standard user case)
27
- const require = createRequire(import.meta.url);
28
- // We look for @ezetgalaxy/titan/package.json
29
- const pkgPath = require.resolve("@ezetgalaxy/titan/package.json");
30
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
31
- return pkg.version;
32
- } catch (e) {
33
- try {
34
- // 2. Fallback for local dev (path to repo root)
35
- const localPath = path.join(__dirname, "..", "..", "..", "package.json");
36
- if (fs.existsSync(localPath)) {
37
- const pkg = JSON.parse(fs.readFileSync(localPath, "utf-8"));
38
- if (pkg.name === "@ezetgalaxy/titan") {
39
- return pkg.version;
40
- }
41
- }
42
- } catch (e2) { }
43
- }
44
- return "0.1.0"; // Fallback
45
- }
46
-
47
- let serverProcess = null;
48
- let isKilling = false;
49
-
50
- // ... (killServer same as before)
51
- async function killServer() {
52
- if (!serverProcess) return;
53
-
54
- isKilling = true;
55
- const pid = serverProcess.pid;
56
- const killPromise = new Promise((resolve) => {
57
- if (serverProcess.exitCode !== null) return resolve();
58
- serverProcess.once("close", resolve);
59
- });
60
-
61
- if (process.platform === "win32") {
62
- try {
63
- execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
64
- } catch (e) {
65
- // Ignore errors if process is already dead
66
- }
67
- } else {
68
- serverProcess.kill();
69
- }
70
-
71
- try {
72
- await killPromise;
73
- } catch (e) { }
74
- serverProcess = null;
75
- isKilling = false;
76
- }
77
-
78
- async function startRustServer(retryCount = 0) {
79
- const waitTime = retryCount > 0 ? 2000 : 1000;
80
-
81
- await killServer();
82
- await new Promise(r => setTimeout(r, waitTime));
83
-
84
- const serverPath = path.join(process.cwd(), "server");
85
- const startTime = Date.now();
86
-
87
- if (retryCount > 0) {
88
- console.log(yellow(`[Titan] Retrying Rust server (Attempt ${retryCount})...`));
89
- }
90
-
91
- serverProcess = spawn("cargo", ["run", "--jobs", "1"], {
92
- cwd: serverPath,
93
- stdio: "inherit",
94
- shell: true,
95
- env: { ...process.env, CARGO_INCREMENTAL: "0" }
96
- });
97
-
98
- serverProcess.on("close", async (code) => {
99
- if (isKilling) return;
100
- const runTime = Date.now() - startTime;
101
- if (code !== 0 && code !== null && runTime < 15000 && retryCount < 5) {
102
- await startRustServer(retryCount + 1);
103
- } else if (code !== 0 && code !== null && retryCount >= 5) {
104
- console.log(red(`[Titan] Server failed to start after multiple attempts.`));
105
- }
106
- });
107
- }
108
-
109
- async function rebuild() {
110
- // process.stdout.write(gray("[Titan] Preparing runtime... "));
111
- const start = Date.now();
112
- try {
113
- execSync("node app/app.js", { stdio: "ignore" });
114
- await bundle();
115
- // console.log(green("Done"));
116
- const elapsed = ((Date.now() - start) / 1000).toFixed(1);
117
- console.log(gray(` A new orbit is ready for your app in ${elapsed}s`));
118
- console.log(green(` Your app is now orbiting Titan Planet`));
119
- } catch (e) {
120
- console.log(red("Failed"));
121
- console.log(red("[Titan] Failed to prepare runtime. Check your app/app.js"));
122
- }
123
- }
124
-
125
- async function startDev() {
126
- const root = process.cwd();
127
- // Check if Rust actions exist by looking for .rs files in app/actions
128
- const actionsDir = path.join(root, "app", "actions");
129
- let hasRust = false;
130
- if (fs.existsSync(actionsDir)) {
131
- hasRust = fs.readdirSync(actionsDir).some(f => f.endsWith(".rs"));
132
- }
133
-
134
- const mode = hasRust ? "Rust + JS Actions" : "JS Actions";
135
- const version = getTitanVersion();
136
-
137
- console.clear();
138
- console.log("");
139
- console.log(` ${bold(cyan("Titan Planet"))} ${gray("v" + version)} ${yellow("[ Dev Mode ]")}`);
140
- console.log("");
141
- console.log(` ${gray("Type: ")} ${mode}`);
142
- console.log(` ${gray("Hot Reload: ")} ${green("Enabled")}`);
143
-
144
- if (fs.existsSync(path.join(root, ".env"))) {
145
- console.log(` ${gray("Env: ")} ${yellow("Loaded")}`);
146
- }
147
- console.log(""); // Spacer
148
-
149
- // FIRST BUILD
150
- try {
151
- await rebuild();
152
- await startRustServer();
153
- } catch (e) {
154
- console.log(red("[Titan] Initial build failed. Waiting for changes..."));
155
- }
156
-
157
- // ... watcher logic same as before but using color vars ...
158
- const watcher = chokidar.watch(["app", ".env"], {
159
- ignoreInitial: true,
160
- awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 }
161
- });
162
-
163
- let timer = null;
164
- watcher.on("all", async (event, file) => {
165
- if (timer) clearTimeout(timer);
166
- timer = setTimeout(async () => {
167
- console.log(""); // Spacer before reload logs
168
- if (file.includes(".env")) {
169
- console.log(yellow("[Titan] Env Refreshed"));
170
- } else {
171
- console.log(cyan(`[Titan] Change: ${path.basename(file)}`));
172
- }
173
- try {
174
- await killServer();
175
- await rebuild();
176
- await startRustServer();
177
- } catch (e) {
178
- console.log(red("[Titan] Build failed -- waiting for changes..."));
179
- }
180
- }, 1000);
181
- });
182
- }
183
-
184
- // Handle graceful exit to release file locks
185
- async function handleExit() {
186
- console.log("\n[Titan] Stopping server...");
187
- await killServer();
188
- process.exit(0);
189
- }
190
-
191
- process.on("SIGINT", handleExit);
192
- process.on("SIGTERM", handleExit);
193
-
194
- startDev();
1
+ import chokidar from "chokidar";
2
+ import { spawn, execSync } from "child_process";
3
+ import path from "path";
4
+ import { fileURLToPath } from "url";
5
+ import fs from "fs";
6
+ import { bundle } from "./bundle.js";
7
+
8
+ // Required for __dirname in ES modules
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = path.dirname(__filename);
11
+
12
+
13
+ // Colors
14
+ import { createRequire } from "module";
15
+
16
+ // Colors
17
+ const cyan = (t) => `\x1b[36m${t}\x1b[0m`;
18
+ const green = (t) => `\x1b[32m${t}\x1b[0m`;
19
+ const yellow = (t) => `\x1b[33m${t}\x1b[0m`;
20
+ const red = (t) => `\x1b[31m${t}\x1b[0m`;
21
+ const gray = (t) => `\x1b[90m${t}\x1b[0m`;
22
+ const bold = (t) => `\x1b[1m${t}\x1b[0m`;
23
+
24
+ function getTitanVersion() {
25
+ try {
26
+ const require = createRequire(import.meta.url);
27
+ const pkgPath = require.resolve("@ezetgalaxy/titan/package.json");
28
+ return JSON.parse(fs.readFileSync(pkgPath, "utf-8")).version;
29
+ } catch (e) {
30
+ try {
31
+ // Check levels up to find the framework root
32
+ let cur = __dirname;
33
+ for (let i = 0; i < 5; i++) {
34
+ const pkgPath = path.join(cur, "package.json");
35
+ if (fs.existsSync(pkgPath)) {
36
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
37
+ if (pkg.name === "@ezetgalaxy/titan") return pkg.version;
38
+ }
39
+ cur = path.join(cur, "..");
40
+ }
41
+ } catch (e2) { }
42
+ }
43
+ return "0.1.0";
44
+ }
45
+
46
+ let serverProcess = null;
47
+ let isKilling = false;
48
+
49
+ // ... (killServer same as before)
50
+ async function killServer() {
51
+ if (!serverProcess) return;
52
+
53
+ isKilling = true;
54
+ const pid = serverProcess.pid;
55
+ const killPromise = new Promise((resolve) => {
56
+ if (serverProcess.exitCode !== null) return resolve();
57
+ serverProcess.once("close", resolve);
58
+ });
59
+
60
+ if (process.platform === "win32") {
61
+ try {
62
+ execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
63
+ } catch (e) {
64
+ // Ignore errors if process is already dead
65
+ }
66
+ } else {
67
+ serverProcess.kill();
68
+ }
69
+
70
+ try {
71
+ await killPromise;
72
+ } catch (e) { }
73
+ serverProcess = null;
74
+ isKilling = false;
75
+ }
76
+
77
+ const delay = (ms) => new Promise(res => setTimeout(res, ms));
78
+
79
+ let spinnerTimer = null;
80
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
81
+ let frameIdx = 0;
82
+
83
+ function startSpinner(text) {
84
+ if (spinnerTimer) clearInterval(spinnerTimer);
85
+ process.stdout.write("\x1B[?25l"); // Hide cursor
86
+ spinnerTimer = setInterval(() => {
87
+ process.stdout.write(`\r ${cyan(frames[frameIdx])} ${gray(text)}`);
88
+ frameIdx = (frameIdx + 1) % frames.length;
89
+ }, 80);
90
+ }
91
+
92
+ function stopSpinner(success = true, text = "") {
93
+ if (spinnerTimer) {
94
+ clearInterval(spinnerTimer);
95
+ spinnerTimer = null;
96
+ }
97
+ process.stdout.write("\r\x1B[K"); // Clear line
98
+ process.stdout.write("\x1B[?25h"); // Show cursor
99
+ if (text) {
100
+ if (success) {
101
+ console.log(` ${green("✔")} ${green(text)}`);
102
+ } else {
103
+ console.log(` ${red("✖")} ${red(text)}`);
104
+ }
105
+ }
106
+ }
107
+
108
+ async function startRustServer(retryCount = 0) {
109
+ const waitTime = retryCount > 0 ? 500 : 200;
110
+
111
+ await killServer();
112
+ await delay(waitTime);
113
+
114
+ const serverPath = path.join(process.cwd(), "server");
115
+ const startTime = Date.now();
116
+
117
+ startSpinner("Stabilizing your app on its orbit...");
118
+
119
+ let isReady = false;
120
+ let stdoutBuffer = "";
121
+ let buildLogs = "";
122
+
123
+ // If it takes more than 15s, update the message
124
+ const slowTimer = setTimeout(() => {
125
+ if (!isReady && !isKilling) {
126
+ startSpinner("Still stabilizing... (the first orbit takes longer)");
127
+ }
128
+ }, 15000);
129
+
130
+ serverProcess = spawn("cargo", ["run", "--quiet"], {
131
+ cwd: serverPath,
132
+ stdio: ["ignore", "pipe", "pipe"],
133
+ env: { ...process.env, CARGO_INCREMENTAL: "1" }
134
+ });
135
+
136
+ serverProcess.on("error", (err) => {
137
+ stopSpinner(false, "Failed to start orbit");
138
+ console.error(red(`[Titan] Error: ${err.message}`));
139
+ });
140
+
141
+ serverProcess.stderr.on("data", (data) => {
142
+ const str = data.toString();
143
+ if (isReady) {
144
+ process.stderr.write(data);
145
+ } else {
146
+ buildLogs += str;
147
+ }
148
+ });
149
+
150
+ serverProcess.stdout.on("data", (data) => {
151
+ const out = data.toString();
152
+
153
+ if (!isReady) {
154
+ stdoutBuffer += out;
155
+ if (stdoutBuffer.includes("Titan server running") || stdoutBuffer.includes("████████╗")) {
156
+ isReady = true;
157
+ clearTimeout(slowTimer);
158
+ stopSpinner(true, "Your app is now orbiting Titan Planet");
159
+ process.stdout.write(stdoutBuffer);
160
+ stdoutBuffer = "";
161
+ }
162
+ } else {
163
+ process.stdout.write(data);
164
+ }
165
+ });
166
+
167
+ serverProcess.on("close", async (code) => {
168
+ clearTimeout(slowTimer);
169
+ if (isKilling) return;
170
+ const runTime = Date.now() - startTime;
171
+
172
+ if (code !== 0 && code !== null) {
173
+ stopSpinner(false, "Orbit stabilization failed");
174
+ if (!isReady) {
175
+ console.log(gray("\n--- Build Logs ---"));
176
+ console.log(buildLogs);
177
+ console.log(gray("------------------\n"));
178
+ }
179
+
180
+ if (runTime < 15000 && retryCount < 5) {
181
+ await delay(2000);
182
+ await startRustServer(retryCount + 1);
183
+ }
184
+ }
185
+ });
186
+ }
187
+
188
+ async function rebuild() {
189
+ try {
190
+ execSync("node app/app.js", { stdio: "ignore" });
191
+ await bundle();
192
+ } catch (e) {
193
+ stopSpinner(false, "Failed to prepare runtime");
194
+ console.log(red(`[Titan] Error: ${e.message}`));
195
+ }
196
+ }
197
+
198
+ async function startDev() {
199
+ const root = process.cwd();
200
+ const actionsDir = path.join(root, "app", "actions");
201
+ let hasRust = false;
202
+ if (fs.existsSync(actionsDir)) {
203
+ hasRust = fs.readdirSync(actionsDir).some(f => f.endsWith(".rs"));
204
+ }
205
+
206
+ const mode = hasRust ? "Rust + JS Actions" : "JS Actions";
207
+ const version = getTitanVersion();
208
+
209
+ console.clear();
210
+ console.log("");
211
+ console.log(` ${bold(cyan("Titan Planet"))} ${gray("v" + version)} ${yellow("[ Dev Mode ]")}`);
212
+ console.log("");
213
+ console.log(` ${gray("Type: ")} ${mode}`);
214
+ console.log(` ${gray("Hot Reload: ")} ${green("Enabled")}`);
215
+
216
+ if (fs.existsSync(path.join(root, ".env"))) {
217
+ console.log(` ${gray("Env: ")} ${yellow("Loaded")}`);
218
+ }
219
+ console.log("");
220
+
221
+ try {
222
+ await rebuild();
223
+ await startRustServer();
224
+ } catch (e) {
225
+ // console.log(red("[Titan] Initial build failed. Waiting for changes..."));
226
+ }
227
+
228
+ const watcher = chokidar.watch(["app", ".env"], {
229
+ ignoreInitial: true,
230
+ awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 }
231
+ });
232
+
233
+ let timer = null;
234
+ watcher.on("all", async (event, file) => {
235
+ if (timer) clearTimeout(timer);
236
+ timer = setTimeout(async () => {
237
+ // console.log("");
238
+ /*
239
+ if (file.includes(".env")) {
240
+ console.log(yellow("[Titan] Env Refreshed"));
241
+ } else {
242
+ console.log(cyan(`[Titan] Change: ${path.basename(file)}`));
243
+ }
244
+ */
245
+ try {
246
+ await killServer();
247
+ await rebuild();
248
+ await startRustServer();
249
+ } catch (e) {
250
+ // console.log(red("[Titan] Build failed -- waiting for changes..."));
251
+ }
252
+ }, 300);
253
+ });
254
+ }
255
+
256
+ async function handleExit() {
257
+ stopSpinner();
258
+ console.log(gray("\n[Titan] Stopping server..."));
259
+ await killServer();
260
+ process.exit(0);
261
+ }
262
+
263
+ process.on("SIGINT", handleExit);
264
+ process.on("SIGTERM", handleExit);
265
+
266
+ startDev();