@titanpl/packet 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +63 -0
- package/js/titan/builder.js +73 -0
- package/js/titan/bundle.js +261 -0
- package/js/titan/dev.js +85 -0
- package/js/titan/error-box.js +277 -0
- package/js/titan/titan.js +129 -0
- package/package.json +18 -0
- package/ts/titan/builder.js +121 -0
- package/ts/titan/bundle.js +123 -0
- package/ts/titan/dev.js +454 -0
- package/ts/titan/titan.d.ts +17 -0
- package/ts/titan/titan.js +124 -0
package/ts/titan/dev.js
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
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 esbuild from "esbuild";
|
|
7
|
+
import { createRequire } from "module";
|
|
8
|
+
|
|
9
|
+
// Required for __dirname in ES modules
|
|
10
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
11
|
+
const __dirname = path.dirname(__filename);
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
// Colors
|
|
15
|
+
const cyan = (t) => `\x1b[36m${t}\x1b[0m`;
|
|
16
|
+
const green = (t) => `\x1b[32m${t}\x1b[0m`;
|
|
17
|
+
const yellow = (t) => `\x1b[33m${t}\x1b[0m`;
|
|
18
|
+
const red = (t) => `\x1b[31m${t}\x1b[0m`;
|
|
19
|
+
const gray = (t) => `\x1b[90m${t}\x1b[0m`;
|
|
20
|
+
const bold = (t) => `\x1b[1m${t}\x1b[0m`;
|
|
21
|
+
|
|
22
|
+
function getTitanVersion() {
|
|
23
|
+
try {
|
|
24
|
+
const require = createRequire(import.meta.url);
|
|
25
|
+
const pkgPath = require.resolve("@ezetgalaxy/titan/package.json");
|
|
26
|
+
return JSON.parse(fs.readFileSync(pkgPath, "utf-8")).version;
|
|
27
|
+
} catch (e) {
|
|
28
|
+
try {
|
|
29
|
+
// Check levels up to find the framework root
|
|
30
|
+
let cur = __dirname;
|
|
31
|
+
for (let i = 0; i < 5; i++) {
|
|
32
|
+
const pkgPath = path.join(cur, "package.json");
|
|
33
|
+
if (fs.existsSync(pkgPath)) {
|
|
34
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
35
|
+
if (pkg.name === "@ezetgalaxy/titan") return pkg.version;
|
|
36
|
+
}
|
|
37
|
+
cur = path.join(cur, "..");
|
|
38
|
+
}
|
|
39
|
+
} catch (e2) { }
|
|
40
|
+
|
|
41
|
+
try {
|
|
42
|
+
// Fallback to calling tit --version
|
|
43
|
+
const output = execSync("tit --version", { encoding: "utf-8" }).trim();
|
|
44
|
+
const match = output.match(/v(\d+\.\d+\.\d+)/);
|
|
45
|
+
if (match) return match[1];
|
|
46
|
+
} catch (e3) { }
|
|
47
|
+
}
|
|
48
|
+
return "0.1.0";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
let serverProcess = null;
|
|
52
|
+
let isKilling = false;
|
|
53
|
+
let isFirstBoot = true;
|
|
54
|
+
|
|
55
|
+
async function killServer() {
|
|
56
|
+
if (!serverProcess) return;
|
|
57
|
+
|
|
58
|
+
isKilling = true;
|
|
59
|
+
const pid = serverProcess.pid;
|
|
60
|
+
const killPromise = new Promise((resolve) => {
|
|
61
|
+
if (serverProcess.exitCode !== null) return resolve();
|
|
62
|
+
serverProcess.once("close", resolve);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
if (process.platform === "win32") {
|
|
66
|
+
try {
|
|
67
|
+
execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
|
|
68
|
+
} catch (e) {
|
|
69
|
+
// Ignore errors if process is already dead
|
|
70
|
+
}
|
|
71
|
+
} else {
|
|
72
|
+
serverProcess.kill();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
try {
|
|
76
|
+
await killPromise;
|
|
77
|
+
} catch (e) { }
|
|
78
|
+
serverProcess = null;
|
|
79
|
+
isKilling = false;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const delay = (ms) => new Promise(res => setTimeout(res, ms));
|
|
83
|
+
|
|
84
|
+
let spinnerTimer = null;
|
|
85
|
+
const frames = ["⏣", "⟐", "⟡", "⟠", "⟡", "⟐"];
|
|
86
|
+
let frameIdx = 0;
|
|
87
|
+
|
|
88
|
+
function startSpinner(text) {
|
|
89
|
+
if (spinnerTimer) clearInterval(spinnerTimer);
|
|
90
|
+
process.stdout.write("\x1B[?25l"); // Hide cursor
|
|
91
|
+
spinnerTimer = setInterval(() => {
|
|
92
|
+
process.stdout.write(`\r ${cyan(frames[frameIdx])} ${gray(text)}`);
|
|
93
|
+
frameIdx = (frameIdx + 1) % frames.length;
|
|
94
|
+
}, 80);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function stopSpinner(success = true, text = "") {
|
|
98
|
+
if (spinnerTimer) {
|
|
99
|
+
clearInterval(spinnerTimer);
|
|
100
|
+
spinnerTimer = null;
|
|
101
|
+
}
|
|
102
|
+
process.stdout.write("\r\x1B[K"); // Clear line
|
|
103
|
+
process.stdout.write("\x1B[?25h"); // Show cursor
|
|
104
|
+
if (text) {
|
|
105
|
+
if (success) {
|
|
106
|
+
console.log(` ${green("✔")} ${green(text)}`);
|
|
107
|
+
} else {
|
|
108
|
+
console.log(` ${red("✖")} ${red(text)}`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function startRustServer(retryCount = 0) {
|
|
114
|
+
// If TS is broken, don't start
|
|
115
|
+
if (isTs && !isTsHealthy) {
|
|
116
|
+
stopSpinner(false, "Waiting for TypeScript errors to be fixed...");
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const waitTime = retryCount > 0 ? 1000 : 500;
|
|
121
|
+
|
|
122
|
+
await killServer();
|
|
123
|
+
await delay(waitTime);
|
|
124
|
+
|
|
125
|
+
const serverPath = path.join(process.cwd(), "server");
|
|
126
|
+
const startTime = Date.now();
|
|
127
|
+
|
|
128
|
+
startSpinner("Stabilizing your app on its orbit...");
|
|
129
|
+
|
|
130
|
+
let isReady = false;
|
|
131
|
+
let stdoutBuffer = "";
|
|
132
|
+
let buildLogs = "";
|
|
133
|
+
let stderrBuffer = "";
|
|
134
|
+
|
|
135
|
+
// If it takes more than 30s, update the message
|
|
136
|
+
const slowTimer = setTimeout(() => {
|
|
137
|
+
if (!isReady && !isKilling) {
|
|
138
|
+
startSpinner("Still stabilizing... (the first orbit takes longer)");
|
|
139
|
+
}
|
|
140
|
+
}, 30000);
|
|
141
|
+
|
|
142
|
+
serverProcess = spawn("cargo", ["run", "--quiet"], {
|
|
143
|
+
cwd: serverPath,
|
|
144
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
145
|
+
env: { ...process.env, CARGO_INCREMENTAL: "1" }
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
serverProcess.on("error", (err) => {
|
|
149
|
+
stopSpinner(false, "Failed to start orbit");
|
|
150
|
+
console.error(red(`[Titan] Error: ${err.message}`));
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
serverProcess.stderr.on("data", (data) => {
|
|
154
|
+
const str = data.toString();
|
|
155
|
+
if (isReady) {
|
|
156
|
+
process.stderr.write(data);
|
|
157
|
+
} else {
|
|
158
|
+
buildLogs += str;
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
serverProcess.stdout.on("data", (data) => {
|
|
163
|
+
const out = data.toString();
|
|
164
|
+
|
|
165
|
+
if (!isReady) {
|
|
166
|
+
stdoutBuffer += out;
|
|
167
|
+
if (stdoutBuffer.includes("Titan server running") || stdoutBuffer.includes("████████╗")) {
|
|
168
|
+
isReady = true;
|
|
169
|
+
clearTimeout(slowTimer);
|
|
170
|
+
stopSpinner(true, "Your app is now orbiting Titan Planet");
|
|
171
|
+
|
|
172
|
+
if (isFirstBoot) {
|
|
173
|
+
process.stdout.write(stdoutBuffer);
|
|
174
|
+
isFirstBoot = false;
|
|
175
|
+
} else {
|
|
176
|
+
// On subsequent reloads, only print non-banner lines from the buffer
|
|
177
|
+
const lines = stdoutBuffer.split("\n");
|
|
178
|
+
for (const line of lines) {
|
|
179
|
+
const isBanner = line.includes("Titan server running") ||
|
|
180
|
+
line.includes("████████╗") ||
|
|
181
|
+
line.includes("╚══") ||
|
|
182
|
+
line.includes(" ██║") ||
|
|
183
|
+
line.includes(" ╚═╝");
|
|
184
|
+
if (!isBanner && line.trim()) {
|
|
185
|
+
process.stdout.write(line + "\n");
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
stdoutBuffer = "";
|
|
190
|
+
}
|
|
191
|
+
} else {
|
|
192
|
+
process.stdout.write(data);
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
// Monitor stderr for port binding errors
|
|
197
|
+
serverProcess.stderr.on("data", (data) => {
|
|
198
|
+
stderrBuffer += data.toString();
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
serverProcess.on("close", async (code) => {
|
|
202
|
+
clearTimeout(slowTimer);
|
|
203
|
+
if (isKilling) return;
|
|
204
|
+
const runTime = Date.now() - startTime;
|
|
205
|
+
|
|
206
|
+
if (code !== 0 && code !== null) {
|
|
207
|
+
// Check for port binding errors
|
|
208
|
+
const isPortError = stderrBuffer.includes("Address already in use") ||
|
|
209
|
+
stderrBuffer.includes("address in use") ||
|
|
210
|
+
stderrBuffer.includes("os error 10048") || // Windows
|
|
211
|
+
stderrBuffer.includes("EADDRINUSE") ||
|
|
212
|
+
stderrBuffer.includes("AddrInUse");
|
|
213
|
+
|
|
214
|
+
if (isPortError) {
|
|
215
|
+
if (retryCount < 3) {
|
|
216
|
+
// It's likely the previous process hasn't fully released the port
|
|
217
|
+
await delay(1000);
|
|
218
|
+
await startRustServer(retryCount + 1);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
stopSpinner(false, "Orbit stabilization failed");
|
|
223
|
+
|
|
224
|
+
// Try to read intended port
|
|
225
|
+
let port = 3000;
|
|
226
|
+
try {
|
|
227
|
+
const routesConfig = JSON.parse(fs.readFileSync(path.join(process.cwd(), "server", "routes.json"), "utf8"));
|
|
228
|
+
if (routesConfig && routesConfig.__config && routesConfig.__config.port) {
|
|
229
|
+
port = routesConfig.__config.port;
|
|
230
|
+
}
|
|
231
|
+
} catch (e) { }
|
|
232
|
+
|
|
233
|
+
console.log("");
|
|
234
|
+
|
|
235
|
+
console.log(red("⏣ Your application cannot enter this orbit"));
|
|
236
|
+
console.log(red(`↳ Another application is already bound to port ${port}.`));
|
|
237
|
+
console.log("");
|
|
238
|
+
|
|
239
|
+
console.log(yellow("Recommended Actions:"));
|
|
240
|
+
console.log(yellow(" 1.") + " Release the occupied orbit (stop the other service).");
|
|
241
|
+
console.log(yellow(" 2.") + " Assign your application to a new orbit in " + cyan("app/app.js"));
|
|
242
|
+
console.log(yellow(" Example: ") + cyan(`t.start(${port + 1}, "Titan Running!")`));
|
|
243
|
+
console.log("");
|
|
244
|
+
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
stopSpinner(false, "Orbit stabilization failed");
|
|
250
|
+
|
|
251
|
+
// Debug: Show stderr if it's not empty and not a port error
|
|
252
|
+
if (stderrBuffer && stderrBuffer.trim()) {
|
|
253
|
+
console.log(gray("\n[Debug] Cargo stderr:"));
|
|
254
|
+
console.log(gray(stderrBuffer.substring(0, 500))); // Show first 500 chars
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (runTime < 15000 && retryCount < maxRetries) {
|
|
258
|
+
await delay(2000);
|
|
259
|
+
await startRustServer(retryCount + 1);
|
|
260
|
+
} else if (retryCount >= maxRetries) {
|
|
261
|
+
console.log(gray("\n[Titan] Waiting for changes to retry..."));
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async function rebuild() {
|
|
269
|
+
if (isTs && !isTsHealthy) return; // Don't rebuild if TS is broken
|
|
270
|
+
|
|
271
|
+
try {
|
|
272
|
+
const root = process.cwd();
|
|
273
|
+
const appTs = path.join(root, "app", "app.ts");
|
|
274
|
+
const dotTitan = path.join(root, ".titan");
|
|
275
|
+
const compiledApp = path.join(dotTitan, "app.js");
|
|
276
|
+
|
|
277
|
+
if (fs.existsSync(appTs)) {
|
|
278
|
+
if (!fs.existsSync(dotTitan)) fs.mkdirSync(dotTitan, { recursive: true });
|
|
279
|
+
|
|
280
|
+
await esbuild.build({
|
|
281
|
+
entryPoints: [appTs],
|
|
282
|
+
outfile: compiledApp,
|
|
283
|
+
bundle: true,
|
|
284
|
+
platform: "node",
|
|
285
|
+
format: "esm",
|
|
286
|
+
external: ["fs", "path", "esbuild", "chokidar", "typescript"],
|
|
287
|
+
logLevel: "silent"
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
execSync(`node "${compiledApp}"`, { stdio: "inherit" });
|
|
291
|
+
} else {
|
|
292
|
+
execSync("node app/app.js", { stdio: "ignore" });
|
|
293
|
+
}
|
|
294
|
+
} catch (e) {
|
|
295
|
+
stopSpinner(false, "Failed to prepare runtime");
|
|
296
|
+
console.log(red(`[Titan] Error: ${e.message}`));
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
let tsProcess = null;
|
|
301
|
+
let isTsHealthy = false; // STRICT: Assume unhealthy until checked
|
|
302
|
+
|
|
303
|
+
function startTypeChecker() {
|
|
304
|
+
const root = process.cwd();
|
|
305
|
+
if (!fs.existsSync(path.join(root, "tsconfig.json"))) return;
|
|
306
|
+
|
|
307
|
+
let tscPath;
|
|
308
|
+
try {
|
|
309
|
+
const require = createRequire(import.meta.url);
|
|
310
|
+
tscPath = require.resolve("typescript/bin/tsc");
|
|
311
|
+
} catch (e) {
|
|
312
|
+
tscPath = path.join(root, "node_modules", "typescript", "bin", "tsc");
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if (!fs.existsSync(tscPath)) {
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const args = [tscPath, "--noEmit", "--watch", "--preserveWatchOutput", "--pretty"];
|
|
320
|
+
|
|
321
|
+
tsProcess = spawn(process.execPath, args, {
|
|
322
|
+
cwd: root,
|
|
323
|
+
stdio: "pipe",
|
|
324
|
+
shell: false
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
tsProcess.stdout.on("data", (data) => {
|
|
328
|
+
const lines = data.toString().split("\n");
|
|
329
|
+
for (const line of lines) {
|
|
330
|
+
if (line.trim().includes("File change detected") || line.trim().includes("Starting compilation")) {
|
|
331
|
+
isTsHealthy = false;
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (line.includes("Found 0 errors")) {
|
|
335
|
+
isTsHealthy = true;
|
|
336
|
+
// TS is happy, so we rebuild and restart (or start) the server
|
|
337
|
+
rebuild().then(startRustServer);
|
|
338
|
+
|
|
339
|
+
} else if (line.includes("error TS")) {
|
|
340
|
+
isTsHealthy = false;
|
|
341
|
+
if (serverProcess) {
|
|
342
|
+
console.log(red(`[Titan] TypeScript error detected. Stopping server...`));
|
|
343
|
+
killServer();
|
|
344
|
+
}
|
|
345
|
+
process.stdout.write(line + "\n");
|
|
346
|
+
} else if (line.match(/Found [1-9]\d* error/)) {
|
|
347
|
+
isTsHealthy = false;
|
|
348
|
+
if (serverProcess) {
|
|
349
|
+
console.log(red(`[Titan] TypeScript compilation failed. Stopping server...`));
|
|
350
|
+
killServer();
|
|
351
|
+
}
|
|
352
|
+
process.stdout.write(line + "\n");
|
|
353
|
+
} else if (line.trim()) {
|
|
354
|
+
process.stdout.write(gray(`[TS] ${line}\n`));
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
tsProcess.stderr.on("data", (data) => {
|
|
360
|
+
process.stdout.write(data);
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
let isTs = false;
|
|
365
|
+
|
|
366
|
+
async function startDev() {
|
|
367
|
+
const root = process.cwd();
|
|
368
|
+
const actionsDir = path.join(root, "app", "actions");
|
|
369
|
+
let hasRust = false;
|
|
370
|
+
if (fs.existsSync(actionsDir)) {
|
|
371
|
+
hasRust = fs.readdirSync(actionsDir).some(f => f.endsWith(".rs"));
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
isTs = fs.existsSync(path.join(root, "tsconfig.json")) ||
|
|
375
|
+
fs.existsSync(path.join(root, "app", "app.ts"));
|
|
376
|
+
|
|
377
|
+
let mode = "";
|
|
378
|
+
if (hasRust) {
|
|
379
|
+
mode = isTs ? "Rust + TS Actions" : "Rust + JS Actions";
|
|
380
|
+
} else {
|
|
381
|
+
mode = isTs ? "TS Actions" : "JS Actions";
|
|
382
|
+
}
|
|
383
|
+
const version = getTitanVersion();
|
|
384
|
+
|
|
385
|
+
console.clear();
|
|
386
|
+
console.log("");
|
|
387
|
+
console.log(` ${bold(cyan("⏣ Titan Planet"))} ${gray("v" + version)} ${yellow("[ Dev Mode ]")}`);
|
|
388
|
+
console.log("");
|
|
389
|
+
console.log(` ${gray("Type: ")} ${mode}`);
|
|
390
|
+
console.log(` ${gray("Hot Reload: ")} ${green("Enabled")}`);
|
|
391
|
+
|
|
392
|
+
if (fs.existsSync(path.join(root, ".env"))) {
|
|
393
|
+
console.log(` ${gray("Env: ")} ${yellow("Loaded")}`);
|
|
394
|
+
}
|
|
395
|
+
console.log("");
|
|
396
|
+
|
|
397
|
+
if (isTs) {
|
|
398
|
+
startTypeChecker();
|
|
399
|
+
} else {
|
|
400
|
+
// If no TS, start immediately
|
|
401
|
+
try {
|
|
402
|
+
await rebuild();
|
|
403
|
+
await startRustServer();
|
|
404
|
+
} catch (e) {
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const watcher = chokidar.watch(["app", ".env"], {
|
|
409
|
+
ignoreInitial: true,
|
|
410
|
+
awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 }
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
let timer = null;
|
|
414
|
+
watcher.on("all", async (event, file) => {
|
|
415
|
+
if (timer) clearTimeout(timer);
|
|
416
|
+
timer = setTimeout(async () => {
|
|
417
|
+
// If TS, we rely on TCS to trigger the rebuild (via Found 0 errors)
|
|
418
|
+
// We verify path safety using absolute/relative calculations
|
|
419
|
+
const relPath = path.relative(root, file);
|
|
420
|
+
if (isTs && (relPath.startsWith("app") || relPath.startsWith("app" + path.sep))) return;
|
|
421
|
+
|
|
422
|
+
// If TS is broken, rebuild() checks will prevent update, keeping server dead
|
|
423
|
+
// If TS is healthy, we proceed
|
|
424
|
+
if (isTs && !isTsHealthy) return;
|
|
425
|
+
|
|
426
|
+
try {
|
|
427
|
+
await killServer();
|
|
428
|
+
await rebuild();
|
|
429
|
+
await startRustServer();
|
|
430
|
+
} catch (e) {
|
|
431
|
+
// console.log(red("[Titan] Build failed -- waiting for changes..."));
|
|
432
|
+
}
|
|
433
|
+
}, 300);
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
async function handleExit() {
|
|
438
|
+
stopSpinner();
|
|
439
|
+
console.log(gray("\n[Titan] Stopping server..."));
|
|
440
|
+
await killServer();
|
|
441
|
+
if (tsProcess) {
|
|
442
|
+
if (process.platform === "win32") {
|
|
443
|
+
try { execSync(`taskkill /pid ${tsProcess.pid} /f /t`, { stdio: 'ignore' }); } catch (e) { }
|
|
444
|
+
} else {
|
|
445
|
+
tsProcess.kill();
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
process.exit(0);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
process.on("SIGINT", handleExit);
|
|
452
|
+
process.on("SIGTERM", handleExit);
|
|
453
|
+
|
|
454
|
+
startDev();
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// -- Module Definitions (for imports from "titan") --
|
|
2
|
+
|
|
3
|
+
export interface RouteHandler {
|
|
4
|
+
reply(value: any): void;
|
|
5
|
+
action(name: string): void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface TitanBuilder {
|
|
9
|
+
get(route: string): RouteHandler;
|
|
10
|
+
post(route: string): RouteHandler;
|
|
11
|
+
log(module: string, msg: string): void;
|
|
12
|
+
start(port?: number, msg?: string, threads?: number): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
declare const builder: TitanBuilder;
|
|
16
|
+
export const Titan: TitanBuilder;
|
|
17
|
+
export default builder;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { bundle } from "./bundle.js";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
const cyan = (t) => `\x1b[36m${t}\x1b[0m`;
|
|
7
|
+
const green = (t) => `\x1b[32m${t}\x1b[0m`;
|
|
8
|
+
|
|
9
|
+
const routes = {};
|
|
10
|
+
const dynamicRoutes = {};
|
|
11
|
+
const actionMap = {};
|
|
12
|
+
|
|
13
|
+
function addRoute(method, route) {
|
|
14
|
+
const key = `${method.toUpperCase()}:${route}`;
|
|
15
|
+
|
|
16
|
+
return {
|
|
17
|
+
reply(value) {
|
|
18
|
+
routes[key] = {
|
|
19
|
+
type: typeof value === "object" ? "json" : "text",
|
|
20
|
+
value
|
|
21
|
+
};
|
|
22
|
+
},
|
|
23
|
+
|
|
24
|
+
action(name) {
|
|
25
|
+
if (route.includes(":")) {
|
|
26
|
+
if (!dynamicRoutes[method]) dynamicRoutes[method] = [];
|
|
27
|
+
dynamicRoutes[method].push({
|
|
28
|
+
method: method.toUpperCase(),
|
|
29
|
+
pattern: route,
|
|
30
|
+
action: name
|
|
31
|
+
});
|
|
32
|
+
} else {
|
|
33
|
+
routes[key] = {
|
|
34
|
+
type: "action",
|
|
35
|
+
value: name
|
|
36
|
+
};
|
|
37
|
+
actionMap[key] = name;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @typedef {Object} RouteHandler
|
|
45
|
+
* @property {(value: any) => void} reply - Send a direct response
|
|
46
|
+
* @property {(name: string) => void} action - Bind to a server-side action
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Titan App Builder
|
|
51
|
+
*/
|
|
52
|
+
const t = {
|
|
53
|
+
/**
|
|
54
|
+
* Define a GET route
|
|
55
|
+
* @param {string} route
|
|
56
|
+
* @returns {RouteHandler}
|
|
57
|
+
*/
|
|
58
|
+
get(route) {
|
|
59
|
+
return addRoute("GET", route);
|
|
60
|
+
},
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Define a POST route
|
|
64
|
+
* @param {string} route
|
|
65
|
+
* @returns {RouteHandler}
|
|
66
|
+
*/
|
|
67
|
+
post(route) {
|
|
68
|
+
return addRoute("POST", route);
|
|
69
|
+
},
|
|
70
|
+
|
|
71
|
+
log(module, msg) {
|
|
72
|
+
console.log(`[\x1b[35m${module}\x1b[0m] ${msg}`);
|
|
73
|
+
},
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Start the Titan Server
|
|
77
|
+
* @param {number} [port=3000]
|
|
78
|
+
* @param {string} [msg=""]
|
|
79
|
+
* @param {number} [threads]
|
|
80
|
+
* @param {number} [stack_mb]
|
|
81
|
+
*/
|
|
82
|
+
async start(port = 3000, msg = "", threads, stack_mb) {
|
|
83
|
+
try {
|
|
84
|
+
console.log(cyan("[Titan] Preparing runtime..."));
|
|
85
|
+
await bundle();
|
|
86
|
+
|
|
87
|
+
const base = path.join(process.cwd(), "server");
|
|
88
|
+
if (!fs.existsSync(base)) {
|
|
89
|
+
fs.mkdirSync(base, { recursive: true });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const routesPath = path.join(base, "routes.json");
|
|
93
|
+
const actionMapPath = path.join(base, "action_map.json");
|
|
94
|
+
|
|
95
|
+
fs.writeFileSync(
|
|
96
|
+
routesPath,
|
|
97
|
+
JSON.stringify(
|
|
98
|
+
{
|
|
99
|
+
__config: { port, threads, stack_mb },
|
|
100
|
+
routes,
|
|
101
|
+
__dynamic_routes: Object.values(dynamicRoutes).flat()
|
|
102
|
+
},
|
|
103
|
+
null,
|
|
104
|
+
2
|
|
105
|
+
)
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
fs.writeFileSync(
|
|
109
|
+
actionMapPath,
|
|
110
|
+
JSON.stringify(actionMap, null, 2)
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
console.log(green("✔ Titan metadata written successfully"));
|
|
114
|
+
if (msg) console.log(cyan(msg));
|
|
115
|
+
|
|
116
|
+
} catch (e) {
|
|
117
|
+
console.error(`\x1b[31m[Titan] Build Error: ${e.message}\x1b[0m`);
|
|
118
|
+
process.exit(1);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
export const Titan = t;
|
|
124
|
+
export default t;
|