titanpl 4.0.2 → 7.0.0-beta

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 (70) hide show
  1. package/package.json +11 -5
  2. package/packages/cli/index.js +25 -11
  3. package/packages/cli/package.json +5 -5
  4. package/packages/cli/src/commands/build-ext.js +157 -0
  5. package/packages/cli/src/commands/build.js +12 -0
  6. package/packages/cli/src/commands/create.js +160 -0
  7. package/packages/cli/src/commands/init.js +5 -11
  8. package/packages/cli/src/commands/run-ext.js +104 -0
  9. package/packages/engine-darwin-arm64/README.md +0 -2
  10. package/packages/engine-darwin-arm64/package.json +1 -1
  11. package/packages/engine-linux-x64/README.md +0 -2
  12. package/packages/engine-linux-x64/package.json +1 -1
  13. package/packages/engine-win32-x64/README.md +0 -1
  14. package/packages/engine-win32-x64/bin/titan-server.exe +0 -0
  15. package/packages/engine-win32-x64/package.json +1 -1
  16. package/packages/native/README.md +0 -1
  17. package/packages/native/index.d.ts +10 -0
  18. package/packages/native/index.js +4 -0
  19. package/packages/native/package.json +1 -1
  20. package/packages/native/t.native.d.ts +175 -44
  21. package/packages/packet/README.md +0 -1
  22. package/packages/packet/index.js +19 -2
  23. package/packages/packet/package.json +1 -1
  24. package/packages/route/README.md +21 -0
  25. package/packages/route/index.d.ts +1 -0
  26. package/packages/route/index.js +22 -0
  27. package/packages/route/package.json +1 -1
  28. package/packages/sdk/index.js +2 -0
  29. package/packages/sdk/package.json +18 -0
  30. package/packages/sdk/test/index.js +120 -0
  31. package/templates/common/Dockerfile +9 -45
  32. package/templates/common/_tanfig.json +17 -13
  33. package/templates/extension/index.d.ts +26 -22
  34. package/templates/extension/index.js +15 -15
  35. package/templates/extension/native/Cargo.toml +5 -3
  36. package/templates/extension/native/src/lib.rs +2 -3
  37. package/templates/extension/package.json +10 -20
  38. package/templates/extension/titan.json +5 -16
  39. package/templates/extension/utils/registerExtension.js +44 -0
  40. package/templates/js/package.json +8 -8
  41. package/templates/rust-js/package.json +4 -4
  42. package/templates/rust-ts/package.json +4 -4
  43. package/templates/ts/package.json +8 -8
  44. package/templates/common/app/t.native.d.ts +0 -2043
  45. package/templates/common/app/t.native.js +0 -39
  46. package/titanpl-sdk/LICENSE +0 -15
  47. package/titanpl-sdk/README.md +0 -111
  48. package/titanpl-sdk/assets/titanpl-sdk.png +0 -0
  49. package/titanpl-sdk/bin/run.js +0 -274
  50. package/titanpl-sdk/index.js +0 -5
  51. package/titanpl-sdk/package-lock.json +0 -28
  52. package/titanpl-sdk/package.json +0 -40
  53. package/titanpl-sdk/templates/app/actions/hello.js +0 -5
  54. package/titanpl-sdk/templates/app/app.js +0 -7
  55. package/titanpl-sdk/templates/jsconfig.json +0 -19
  56. package/titanpl-sdk/templates/server/Cargo.toml +0 -52
  57. package/titanpl-sdk/templates/server/src/action_management.rs +0 -175
  58. package/titanpl-sdk/templates/server/src/errors.rs +0 -12
  59. package/titanpl-sdk/templates/server/src/extensions/builtin.rs +0 -1055
  60. package/titanpl-sdk/templates/server/src/extensions/external.rs +0 -338
  61. package/titanpl-sdk/templates/server/src/extensions/mod.rs +0 -580
  62. package/titanpl-sdk/templates/server/src/extensions/titan_core.js +0 -249
  63. package/titanpl-sdk/templates/server/src/fast_path.rs +0 -719
  64. package/titanpl-sdk/templates/server/src/main.rs +0 -607
  65. package/titanpl-sdk/templates/server/src/runtime.rs +0 -284
  66. package/titanpl-sdk/templates/server/src/utils.rs +0 -33
  67. package/titanpl-sdk/templates/titan/bundle.js +0 -259
  68. package/titanpl-sdk/templates/titan/dev.js +0 -390
  69. package/titanpl-sdk/templates/titan/error-box.js +0 -277
  70. package/titanpl-sdk/templates/titan/titan.js +0 -129
@@ -1,390 +0,0 @@
1
- /**
2
- * Dev.js
3
- * Titan development server with hot reload
4
- * RULE: This file shows ONLY clean error messages - no raw logs, no stack traces
5
- */
6
-
7
- import chokidar from "chokidar";
8
- import { spawn, execSync } from "child_process";
9
- import path from "path";
10
- import { fileURLToPath } from "url";
11
- import fs from "fs";
12
- import { createRequire } from "module";
13
-
14
- const __filename = fileURLToPath(import.meta.url);
15
- const __dirname = path.dirname(__filename);
16
-
17
- // Premium colors
18
- const cyan = (t) => `\x1b[36m${t}\x1b[0m`;
19
- const green = (t) => `\x1b[32m${t}\x1b[0m`;
20
- const yellow = (t) => `\x1b[33m${t}\x1b[0m`;
21
- const red = (t) => `\x1b[31m${t}\x1b[0m`;
22
- const gray = (t) => `\x1b[90m${t}\x1b[0m`;
23
- const bold = (t) => `\x1b[1m${t}\x1b[0m`;
24
-
25
- function getTitanVersion() {
26
- try {
27
- const require = createRequire(import.meta.url);
28
- const pkgPath = require.resolve("titanpl/package.json");
29
- return JSON.parse(fs.readFileSync(pkgPath, "utf-8")).version;
30
- } catch (e) {
31
- try {
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 === "titanpl") return pkg.version;
38
- }
39
- cur = path.join(cur, "..");
40
- }
41
- } catch (e2) { }
42
-
43
- try {
44
- const output = execSync("tit --version", { encoding: "utf-8" }).trim();
45
- const match = output.match(/v(\d+\.\d+\.\d+)/);
46
- if (match) return match[1];
47
- } catch (e3) { }
48
- }
49
- return "0.1.0";
50
- }
51
-
52
- let serverProcess = null;
53
- let isKilling = false;
54
- let isFirstBoot = true;
55
-
56
- async function killServer() {
57
- if (!serverProcess) return;
58
-
59
- isKilling = true;
60
- const pid = serverProcess.pid;
61
- const killPromise = new Promise((resolve) => {
62
- if (serverProcess.exitCode !== null) return resolve();
63
- serverProcess.once("close", resolve);
64
- });
65
-
66
- if (process.platform === "win32") {
67
- try {
68
- execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
69
- } catch (e) {
70
- // Ignore errors if process is already dead
71
- }
72
- } else {
73
- serverProcess.kill();
74
- }
75
-
76
- try {
77
- await killPromise;
78
- } catch (e) { }
79
- serverProcess = null;
80
- isKilling = false;
81
- }
82
-
83
- const delay = (ms) => new Promise(res => setTimeout(res, ms));
84
-
85
- let spinnerTimer = null;
86
- const frames = ["⏣", "⟐", "⟡", "⟠", "⟡", "⟐"];
87
- let frameIdx = 0;
88
-
89
- function startSpinner(text) {
90
- if (spinnerTimer) clearInterval(spinnerTimer);
91
- process.stdout.write("\x1B[?25l"); // Hide cursor
92
- spinnerTimer = setInterval(() => {
93
- process.stdout.write(`\r ${cyan(frames[frameIdx])} ${gray(text)}`);
94
- frameIdx = (frameIdx + 1) % frames.length;
95
- }, 80);
96
- }
97
-
98
- function stopSpinner(success = true, text = "") {
99
- if (spinnerTimer) {
100
- clearInterval(spinnerTimer);
101
- spinnerTimer = null;
102
- }
103
- process.stdout.write("\r\x1B[K"); // Clear line
104
- process.stdout.write("\x1B[?25h"); // Show cursor
105
- if (text) {
106
- if (success) {
107
- console.log(` ${green("✔")} ${green(text)}`);
108
- } else {
109
- console.log(` ${red("✖")} ${red(text)}`);
110
- }
111
- }
112
- }
113
-
114
- async function startRustServer(retryCount = 0) {
115
- const maxRetries = 3;
116
- const waitTime = retryCount > 0 ? 500 : 200;
117
-
118
- await killServer();
119
- await delay(waitTime);
120
-
121
- const serverPath = path.join(process.cwd(), "server");
122
- const startTime = Date.now();
123
-
124
- startSpinner("Stabilizing your app on its orbit...");
125
-
126
- let isReady = false;
127
- let stdoutBuffer = "";
128
- let stderrBuffer = "";
129
-
130
- const slowTimer = setTimeout(() => {
131
- if (!isReady && !isKilling) {
132
- startSpinner("Still stabilizing... (the first orbit takes longer)");
133
- }
134
- }, 15000);
135
-
136
- serverProcess = spawn("cargo", ["run", "--quiet"], {
137
- cwd: serverPath,
138
- stdio: ["ignore", "pipe", "pipe"],
139
- env: { ...process.env, CARGO_INCREMENTAL: "1", TITAN_DEV: "1" }
140
- });
141
-
142
- serverProcess.on("error", (err) => {
143
- stopSpinner(false, "Orbit stabilization failed");
144
- });
145
-
146
- serverProcess.stdout.on("data", (data) => {
147
- const out = data.toString();
148
-
149
- if (!isReady) {
150
- stdoutBuffer += out;
151
- if (stdoutBuffer.includes("Titan server running") || stdoutBuffer.includes("████████╗")) {
152
- isReady = true;
153
- clearTimeout(slowTimer);
154
- stopSpinner(true, "Your app is now orbiting Titan Planet");
155
-
156
- if (isFirstBoot) {
157
- process.stdout.write(stdoutBuffer);
158
- isFirstBoot = false;
159
- } else {
160
- const lines = stdoutBuffer.split("\n");
161
- for (const line of lines) {
162
- const isBanner = line.includes("Titan server running") ||
163
- line.includes("████████╗") ||
164
- line.includes("╚══") ||
165
- line.includes(" ██║") ||
166
- line.includes(" ╚═╝");
167
- if (!isBanner && line.trim()) {
168
- process.stdout.write(line + "\n");
169
- }
170
- }
171
- }
172
- stdoutBuffer = "";
173
- }
174
- } else {
175
- process.stdout.write(data);
176
- }
177
- });
178
-
179
- // Monitor stderr for port binding errors
180
- serverProcess.stderr.on("data", (data) => {
181
- stderrBuffer += data.toString();
182
- });
183
-
184
- serverProcess.on("close", async (code) => {
185
- clearTimeout(slowTimer);
186
- if (isKilling) return;
187
- const runTime = Date.now() - startTime;
188
-
189
- if (code !== 0 && code !== null) {
190
- // Check for port binding errors
191
- const isPortError = stderrBuffer.includes("Address already in use") ||
192
- stderrBuffer.includes("address in use") ||
193
- stderrBuffer.includes("os error 10048") || // Windows
194
- stderrBuffer.includes("EADDRINUSE") ||
195
- stderrBuffer.includes("AddrInUse");
196
-
197
- if (isPortError) {
198
- if (retryCount < 3) {
199
- // It's likely the previous process hasn't fully released the port
200
- await delay(1000);
201
- await startRustServer(retryCount + 1);
202
- return;
203
- }
204
-
205
- stopSpinner(false, "Orbit stabilization failed");
206
-
207
- // Try to read intended port
208
- let port = 3000;
209
- try {
210
- const routesConfig = JSON.parse(fs.readFileSync(path.join(process.cwd(), "server", "routes.json"), "utf8"));
211
- if (routesConfig && routesConfig.__config && routesConfig.__config.port) {
212
- port = routesConfig.__config.port;
213
- }
214
- } catch (e) { }
215
-
216
- console.log("");
217
-
218
- console.log(red("⏣ Your application cannot enter this orbit"));
219
- console.log(red(`↳ Another application is already bound to port ${port}.`));
220
- console.log("");
221
-
222
- console.log(yellow("Recommended Actions:"));
223
- console.log(yellow(" 1.") + " Release the occupied orbit (stop the other service).");
224
- console.log(yellow(" 2.") + " Assign your application to a new orbit in " + cyan("app/app.js"));
225
- console.log(yellow(" Example: ") + cyan(`t.start(${port + 1}, "Titan Running!")`));
226
- console.log("");
227
-
228
- return;
229
- }
230
-
231
-
232
- stopSpinner(false, "Orbit stabilization failed");
233
-
234
- // // Debug: Show stderr if it's not empty and not a port error
235
- // if (stderrBuffer && stderrBuffer.trim()) {
236
- // console.log(gray("\n[Debug] Cargo stderr:"));
237
- // console.log(gray(stderrBuffer.substring(0, 500))); // Show first 500 chars
238
- // }
239
-
240
- if (runTime < 15000 && retryCount < maxRetries) {
241
- await delay(2000);
242
- await startRustServer(retryCount + 1);
243
- } else if (retryCount >= maxRetries) {
244
- console.log(gray("\n[Titan] Waiting for changes to retry..."));
245
- }
246
- }
247
- });
248
- }
249
-
250
- function prepareRuntime() {
251
- try {
252
- const nm = path.join(process.cwd(), "node_modules");
253
- const titanPkg = path.join(nm, "@titanpl");
254
- const routePkg = path.join(titanPkg, "route");
255
-
256
- if (!fs.existsSync(nm)) fs.mkdirSync(nm, { recursive: true });
257
- if (!fs.existsSync(titanPkg)) fs.mkdirSync(titanPkg, { recursive: true });
258
-
259
- if (!fs.existsSync(routePkg)) {
260
- fs.mkdirSync(routePkg, { recursive: true });
261
- fs.writeFileSync(path.join(routePkg, "package.json"), JSON.stringify({
262
- name: "@titanpl/route",
263
- main: "../../../titan/titan.js",
264
- type: "module"
265
- }, null, 2));
266
- }
267
- } catch (e) {
268
- // Ignore errors
269
- }
270
- }
271
-
272
- /**
273
- * Rebuild JS runtime
274
- * RULE: Only show "✖ Runtime preparation failed" on error
275
- * RULE: No raw logs, no stack traces, no console.error output
276
- */
277
- async function rebuild() {
278
- try {
279
- // Execute app.js - pipe both stdout and stderr to capture and filter
280
- const result = execSync("node app/app.js", {
281
- encoding: "utf-8",
282
- stdio: ["ignore", "pipe", "pipe"]
283
- });
284
-
285
- // If succeeded, just print stdout (usually empty unless successful logs)
286
- if (result) process.stdout.write(result);
287
- } catch (e) {
288
- stopSpinner(false, "Runtime preparation failed");
289
-
290
- // RULE: Search for the error box in the output and print ONLY that
291
- // This removes Node.js version, stack traces, etc.
292
- const output = (e.stdout || "") + (e.stderr || "");
293
-
294
- // Find the box content - look for the start border (accounting for ANSI color)
295
- // Match from the first ┌ up to the last ┘
296
- const startIdx = output.indexOf('┌');
297
- const endIdx = output.lastIndexOf('┘');
298
-
299
- if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
300
- // Include potential ANSI codes before/after borders
301
- let box = output.substring(startIdx - 5, endIdx + 1 + 5);
302
- // Clean up to ensure we start/end at ANSI boundaries or borders
303
- const realStart = box.indexOf('\x1b[31m┌');
304
- const realEnd = box.lastIndexOf('┘\x1b[0m');
305
-
306
- if (realStart !== -1 && realEnd !== -1) {
307
- console.error("\n" + box.substring(realStart, realEnd + 5) + "\n");
308
- } else {
309
- // Fallback to simpler match
310
- const simpleBox = output.substring(startIdx, endIdx + 1);
311
- console.error("\n" + red(simpleBox) + "\n");
312
- }
313
- } else if (e.stderr && !e.stderr.includes("Node.js v")) {
314
- console.error(red(e.stderr.trim()));
315
- }
316
-
317
- throw e;
318
- }
319
- }
320
-
321
- async function startDev() {
322
- prepareRuntime();
323
- const root = process.cwd();
324
- const actionsDir = path.join(root, "app", "actions");
325
- let hasRust = false;
326
- if (fs.existsSync(actionsDir)) {
327
- hasRust = fs.readdirSync(actionsDir).some(f => f.endsWith(".rs"));
328
- }
329
-
330
- const isTs = fs.existsSync(path.join(root, "tsconfig.json")) ||
331
- fs.existsSync(path.join(root, "app", "app.ts"));
332
-
333
- let mode = "";
334
- if (hasRust) {
335
- mode = isTs ? "Rust + TS Actions" : "Rust + JS Actions";
336
- } else {
337
- mode = isTs ? "TS Actions" : "JS Actions";
338
- }
339
- const version = getTitanVersion();
340
-
341
- console.clear();
342
- console.log("");
343
- console.log(` ${bold(cyan("⏣ Titan Planet"))} ${gray("v" + version)} ${yellow("[ Dev Mode ]")}`);
344
- console.log("");
345
- console.log(` ${gray("Type: ")} ${mode}`);
346
- console.log(` ${gray("Hot Reload: ")} ${green("Enabled")}`);
347
-
348
- if (fs.existsSync(path.join(root, ".env"))) {
349
- console.log(` ${gray("Env: ")} ${yellow("Loaded")}`);
350
- }
351
- console.log("");
352
-
353
- try {
354
- await rebuild();
355
- await startRustServer();
356
- } catch (e) {
357
- console.log(gray("\n[Titan] Waiting for changes to retry..."));
358
- }
359
-
360
- const watcher = chokidar.watch(["app", ".env"], {
361
- ignoreInitial: true,
362
- awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 }
363
- });
364
-
365
- let timer = null;
366
- watcher.on("all", async (event, file) => {
367
- if (timer) clearTimeout(timer);
368
- timer = setTimeout(async () => {
369
- try {
370
- await killServer();
371
- await rebuild();
372
- await startRustServer();
373
- } catch (e) {
374
- console.log(gray("\n[Titan] Waiting for changes to retry..."));
375
- }
376
- }, 300);
377
- });
378
- }
379
-
380
- async function handleExit() {
381
- stopSpinner();
382
- console.log(gray("\n[Titan] Stopping server..."));
383
- await killServer();
384
- process.exit(0);
385
- }
386
-
387
- process.on("SIGINT", handleExit);
388
- process.on("SIGTERM", handleExit);
389
-
390
- startDev();
@@ -1,277 +0,0 @@
1
- /**
2
- * Error Box Renderer
3
- * Renders errors in a Next.js-style red terminal box
4
- */
5
-
6
- import fs from 'fs';
7
- import path from 'path';
8
- import { createRequire } from 'module';
9
- import { execSync } from 'child_process';
10
- import { fileURLToPath } from 'url';
11
-
12
- const __filename = fileURLToPath(import.meta.url);
13
- const __dirname = path.dirname(__filename);
14
-
15
- // Simple color function using ANSI escape codes
16
- const red = (text) => `\x1b[31m${text}\x1b[0m`;
17
-
18
- /**
19
- * Wraps text to fit within a specified width
20
- * @param {string} text - Text to wrap
21
- * @param {number} maxWidth - Maximum width per line
22
- * @returns {string[]} Array of wrapped lines
23
- */
24
-
25
- function getTitanVersion() {
26
- try {
27
- const require = createRequire(import.meta.url);
28
- const pkgPath = require.resolve("titanpl/package.json");
29
- return JSON.parse(fs.readFileSync(pkgPath, "utf-8")).version;
30
- } catch (e) {
31
- try {
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 === "titanpl") return pkg.version;
38
- }
39
- cur = path.join(cur, "..");
40
- }
41
- } catch (e2) { }
42
-
43
- try {
44
- const output = execSync("tit --version", { encoding: "utf-8" }).trim();
45
- const match = output.match(/v(\d+\.\d+\.\d+)/);
46
- if (match) return match[1];
47
- } catch (e3) { }
48
- }
49
- return "0.1.0";
50
- }
51
-
52
- function wrapText(text, maxWidth) {
53
- if (!text) return [''];
54
-
55
- const lines = text.split('\n');
56
- const wrapped = [];
57
-
58
- for (const line of lines) {
59
- if (line.length <= maxWidth) {
60
- wrapped.push(line);
61
- continue;
62
- }
63
-
64
- // Word wrap logic
65
- const words = line.split(' ');
66
- let currentLine = '';
67
-
68
- for (const word of words) {
69
- const testLine = currentLine ? `${currentLine} ${word}` : word;
70
-
71
- if (testLine.length <= maxWidth) {
72
- currentLine = testLine;
73
- } else {
74
- if (currentLine) {
75
- wrapped.push(currentLine);
76
- }
77
- // If single word is too long, force split it
78
- if (word.length > maxWidth) {
79
- let remaining = word;
80
- while (remaining.length > maxWidth) {
81
- wrapped.push(remaining.substring(0, maxWidth));
82
- remaining = remaining.substring(maxWidth);
83
- }
84
- currentLine = remaining;
85
- } else {
86
- currentLine = word;
87
- }
88
- }
89
- }
90
-
91
- if (currentLine) {
92
- wrapped.push(currentLine);
93
- }
94
- }
95
-
96
- return wrapped.length > 0 ? wrapped : [''];
97
- }
98
-
99
- /**
100
- * Pads text to fit within box width
101
- * @param {string} text - Text to pad
102
- * @param {number} width - Target width
103
- * @returns {string} Padded text
104
- */
105
- function padLine(text, width) {
106
- const padding = width - text.length;
107
- return text + ' '.repeat(Math.max(0, padding));
108
- }
109
-
110
- /**
111
- * Renders an error in a Next.js-style red box
112
- * @param {Object} errorInfo - Error information
113
- * @param {string} errorInfo.title - Error title (e.g., "Build Error")
114
- * @param {string} errorInfo.file - File path where error occurred
115
- * @param {string} errorInfo.message - Error message
116
- * @param {string} [errorInfo.location] - Error location (e.g., "at hello.js:3:1")
117
- * @param {number} [errorInfo.line] - Line number
118
- * @param {number} [errorInfo.column] - Column number
119
- * @param {string} [errorInfo.codeFrame] - Code frame showing error context
120
- * @param {string} [errorInfo.suggestion] - Recommended fix
121
- */
122
- /**
123
- * Renders an error in a Next.js-style red box
124
- * @param {Object} errorInfo - Error information
125
- * @param {string} errorInfo.title - Error title (e.g., "Build Error")
126
- * @param {string} errorInfo.file - File path where error occurred
127
- * @param {string} errorInfo.message - Error message
128
- * @param {string} [errorInfo.location] - Error location (e.g., "at hello.js:3:1")
129
- * @param {number} [errorInfo.line] - Line number
130
- * @param {number} [errorInfo.column] - Column number
131
- * @param {string} [errorInfo.codeFrame] - Code frame showing error context
132
- * @param {string} [errorInfo.suggestion] - Recommended fix
133
- */
134
- export function renderErrorBox(errorInfo) {
135
- const boxWidth = 72;
136
- const contentWidth = boxWidth - 4; // Account for "│ " and " │"
137
-
138
- const lines = [];
139
-
140
- // Add title
141
- if (errorInfo.title) {
142
- lines.push(bold(errorInfo.title));
143
- }
144
-
145
- // Add file path
146
- if (errorInfo.file) {
147
- lines.push(errorInfo.file);
148
- }
149
-
150
- // Add message
151
- if (errorInfo.message) {
152
- lines.push('');
153
- lines.push(...wrapText(errorInfo.message, contentWidth));
154
- }
155
-
156
- // Add location
157
- if (errorInfo.location) {
158
- lines.push(gray(errorInfo.location));
159
- } else if (errorInfo.file && errorInfo.line !== undefined) {
160
- const loc = `at ${errorInfo.file}:${errorInfo.line}${errorInfo.column !== undefined ? `:${errorInfo.column}` : ''}`;
161
- lines.push(gray(loc));
162
- }
163
-
164
- // Add code frame if available
165
- if (errorInfo.codeFrame) {
166
- lines.push(''); // Empty line for separation
167
- const frameLines = errorInfo.codeFrame.split('\n');
168
- for (const frameLine of frameLines) {
169
- lines.push(frameLine);
170
- }
171
- }
172
-
173
- // Add suggestion if available
174
- if (errorInfo.suggestion) {
175
- lines.push(''); // Empty line for separation
176
- lines.push(...wrapText('Recommended fix: ' + errorInfo.suggestion, contentWidth));
177
- }
178
-
179
- // Add Footer with Branding
180
- lines.push('');
181
- const version = getTitanVersion()
182
- lines.push(gray(`⏣ Titan Planet ${version}`));
183
-
184
- // Build the box
185
- const topBorder = '┌' + '─'.repeat(boxWidth - 2) + '┐';
186
- const bottomBorder = '└' + '─'.repeat(boxWidth - 2) + '┘';
187
-
188
-
189
- const boxLines = [
190
- red(topBorder),
191
- ...lines.map(line => {
192
- // Strip ANSI codes for padding calculation if any were added
193
- const plainLine = line.replace(/\x1b\[\d+m/g, '');
194
- const padding = ' '.repeat(Math.max(0, contentWidth - plainLine.length));
195
- return red('│ ') + line + padding + red(' │');
196
- }),
197
- red(bottomBorder)
198
- ];
199
-
200
- return boxLines.join('\n');
201
- }
202
-
203
- // Internal formatting helpers
204
- function gray(t) { return `\x1b[90m${t}\x1b[0m`; }
205
- function bold(t) { return `\x1b[1m${t}\x1b[0m`; }
206
-
207
- /**
208
- * Parses esbuild error and extracts relevant information
209
- * @param {Object} error - esbuild error object
210
- * @returns {Object} Parsed error information
211
- */
212
- export function parseEsbuildError(error) {
213
- const errorInfo = {
214
- title: 'Build Error',
215
- file: error.location?.file || 'unknown',
216
- message: error.text || error.message || 'Unknown error',
217
- line: error.location?.line,
218
- column: error.location?.column,
219
- location: null,
220
- codeFrame: null,
221
- suggestion: error.notes?.[0]?.text || null
222
- };
223
-
224
- // Format location
225
- if (error.location) {
226
- const { file, line, column } = error.location;
227
- errorInfo.location = `at ${file}:${line}:${column}`;
228
-
229
- // Format code frame if lineText is available
230
- if (error.location.lineText) {
231
- const lineText = error.location.lineText;
232
- // Ensure column is at least 1 to prevent negative values
233
- const col = Math.max(0, (column || 1) - 1);
234
- const pointer = ' '.repeat(col) + '^';
235
- errorInfo.codeFrame = `${line} | ${lineText}\n${' '.repeat(String(line).length)} | ${pointer}`;
236
- }
237
- }
238
-
239
- return errorInfo;
240
- }
241
-
242
- /**
243
- * Parses Node.js syntax error and extracts relevant information
244
- * @param {Error} error - Node.js error object
245
- * @param {string} [file] - File path (if known)
246
- * @returns {Object} Parsed error information
247
- */
248
- export function parseNodeError(error, file = null) {
249
- const errorInfo = {
250
- title: 'Syntax Error',
251
- file: file || 'unknown',
252
- message: error.message || 'Unknown error',
253
- location: null,
254
- suggestion: null
255
- };
256
-
257
- // Try to extract line and column from error message
258
- const locationMatch = error.message.match(/\((\d+):(\d+)\)/) ||
259
- error.stack?.match(/:(\d+):(\d+)/);
260
-
261
- if (locationMatch) {
262
- const line = parseInt(locationMatch[1]);
263
- const column = parseInt(locationMatch[2]);
264
- errorInfo.line = line;
265
- errorInfo.column = column;
266
- errorInfo.location = `at ${errorInfo.file}:${line}:${column}`;
267
- }
268
-
269
- // Extract suggestion from error message if available
270
- if (error.message.includes('expected')) {
271
- errorInfo.suggestion = 'Check for missing or misplaced syntax elements';
272
- } else if (error.message.includes('Unexpected token')) {
273
- errorInfo.suggestion = 'Remove or fix the unexpected token';
274
- }
275
-
276
- return errorInfo;
277
- }