@ezetgalaxy/titan 26.9.1 → 26.9.3
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/README.md +17 -5
- package/index.js +177 -112
- package/package.json +19 -5
- package/templates/common/app/titan.d.ts +87 -0
- package/templates/extension/node_modules/.bin/esbuild +16 -0
- package/templates/extension/node_modules/.bin/esbuild.cmd +17 -0
- package/templates/extension/node_modules/.bin/esbuild.ps1 +28 -0
- package/templates/extension/node_modules/.bin/titanpl-sdk +16 -0
- package/templates/extension/node_modules/.bin/titanpl-sdk.cmd +17 -0
- package/templates/extension/node_modules/.bin/titanpl-sdk.ps1 +28 -0
- package/templates/extension/node_modules/.package-lock.json +111 -0
- package/templates/extension/node_modules/@esbuild/win32-x64/README.md +3 -0
- package/templates/extension/node_modules/@esbuild/win32-x64/esbuild.exe +0 -0
- package/templates/extension/node_modules/@esbuild/win32-x64/package.json +20 -0
- package/templates/extension/node_modules/@titanpl/core/LICENSE +15 -0
- package/templates/extension/node_modules/@titanpl/core/README.md +127 -0
- package/templates/extension/node_modules/@titanpl/core/globals.d.ts +17 -0
- package/templates/extension/node_modules/@titanpl/core/index.js +250 -0
- package/templates/extension/node_modules/@titanpl/core/native/target/release/titan_core.dll +0 -0
- package/templates/extension/node_modules/@titanpl/core/package.json +41 -0
- package/templates/extension/node_modules/@titanpl/core/titan.json +115 -0
- package/templates/extension/node_modules/chokidar/LICENSE +21 -0
- package/templates/extension/node_modules/chokidar/README.md +305 -0
- package/templates/extension/node_modules/chokidar/handler.d.ts +90 -0
- package/templates/extension/node_modules/chokidar/handler.js +632 -0
- package/templates/extension/node_modules/chokidar/index.d.ts +217 -0
- package/templates/extension/node_modules/chokidar/index.js +822 -0
- package/templates/extension/node_modules/chokidar/package.json +63 -0
- package/templates/extension/node_modules/esbuild/LICENSE.md +21 -0
- package/templates/extension/node_modules/esbuild/README.md +3 -0
- package/templates/extension/node_modules/esbuild/bin/esbuild +223 -0
- package/templates/extension/node_modules/esbuild/install.js +289 -0
- package/templates/extension/node_modules/esbuild/lib/main.d.ts +716 -0
- package/templates/extension/node_modules/esbuild/lib/main.js +2242 -0
- package/templates/extension/node_modules/esbuild/package.json +49 -0
- package/templates/extension/node_modules/readdirp/LICENSE +21 -0
- package/templates/extension/node_modules/readdirp/README.md +120 -0
- package/templates/extension/node_modules/readdirp/index.d.ts +108 -0
- package/templates/extension/node_modules/readdirp/index.js +272 -0
- package/templates/extension/node_modules/readdirp/package.json +66 -0
- package/templates/extension/node_modules/titanpl-sdk/LICENSE +15 -0
- package/templates/extension/node_modules/titanpl-sdk/README.md +109 -0
- package/templates/extension/node_modules/titanpl-sdk/assets/titanpl-sdk.png +0 -0
- package/templates/extension/node_modules/titanpl-sdk/bin/run.js +251 -0
- package/templates/extension/node_modules/titanpl-sdk/index.d.ts +46 -0
- package/templates/extension/node_modules/titanpl-sdk/index.js +5 -0
- package/templates/extension/node_modules/titanpl-sdk/package.json +33 -0
- package/templates/{rust-js → extension/node_modules/titanpl-sdk/templates}/Dockerfile +4 -17
- package/templates/extension/node_modules/titanpl-sdk/templates/app/actions/hello.js +5 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/app/app.js +10 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/jsconfig.json +19 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/server/Cargo.lock +2839 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/server/Cargo.toml +27 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/server/src/action_management.rs +131 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/server/src/errors.rs +10 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/server/src/extensions.rs +640 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/server/src/main.rs +345 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/server/src/utils.rs +33 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/titan/bundle.js +65 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/titan/dev.js +113 -0
- package/templates/extension/node_modules/titanpl-sdk/templates/titan/titan.js +98 -0
- package/templates/extension/package-lock.json +522 -0
- package/templates/extension/package.json +4 -3
- package/templates/rust-ts/app/actions/hello.ts +1 -1
- package/templates/rust-ts/titan/runtime.d.ts +1 -0
- package/templates/rust-ts/titan/runtime.js +1 -0
- package/templates/rust-ts/titan/titan.d.ts +117 -117
- package/templates/rust-ts/titan/titan.js +1 -1
- package/templates/ts/app/actions/hello.ts +1 -1
- package/templates/ts/titan/builder.js +121 -121
- package/templates/ts/titan/runtime.d.ts +1 -0
- package/templates/ts/titan/runtime.js +1 -1
- package/templates/ts/titan/titan.d.ts +117 -117
- package/templates/ts/titan/titan.js +1 -1
- package/titanpl-sdk/node_modules/.package-lock.json +17 -0
- package/titanpl-sdk/node_modules/@titanpl/core/LICENSE +15 -0
- package/titanpl-sdk/node_modules/@titanpl/core/README.md +127 -0
- package/titanpl-sdk/node_modules/@titanpl/core/globals.d.ts +17 -0
- package/titanpl-sdk/node_modules/@titanpl/core/index.js +250 -0
- package/titanpl-sdk/node_modules/@titanpl/core/native/target/release/titan_core.dll +0 -0
- package/titanpl-sdk/node_modules/@titanpl/core/package.json +41 -0
- package/titanpl-sdk/node_modules/@titanpl/core/titan.json +115 -0
- package/titanpl-sdk/package-lock.json +28 -0
- package/titanpl-sdk/package.json +6 -3
- package/templates/rust-js/_gitignore +0 -38
- package/templates/rust-js/app/titan.d.ts +0 -101
- package/templates/rust-ts/Dockerfile +0 -66
- package/templates/rust-ts/_dockerignore +0 -3
- package/templates/rust-ts/_gitignore +0 -38
- package/templates/ts/Dockerfile +0 -40
- package/templates/ts/_dockerignore +0 -3
- package/templates/ts/_gitignore +0 -38
- /package/templates/{js → common}/Dockerfile +0 -0
- /package/templates/{js → common}/_dockerignore +0 -0
- /package/templates/{js → common}/_gitignore +0 -0
- /package/templates/{rust-js/_dockerignore → extension/node_modules/titanpl-sdk/templates/.dockerignore} +0 -0
- /package/templates/{js → extension/node_modules/titanpl-sdk/templates}/app/titan.d.ts +0 -0
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
use std::{collections::HashMap, fs, path::PathBuf, sync::Arc};
|
|
2
|
+
use anyhow::Result;
|
|
3
|
+
use axum::{
|
|
4
|
+
body::{to_bytes, Body},
|
|
5
|
+
extract::State,
|
|
6
|
+
http::{Request, StatusCode},
|
|
7
|
+
response::{IntoResponse, Json},
|
|
8
|
+
routing::any,
|
|
9
|
+
Router,
|
|
10
|
+
};
|
|
11
|
+
use serde_json::Value;
|
|
12
|
+
use tokio::net::TcpListener;
|
|
13
|
+
use std::time::Instant;
|
|
14
|
+
|
|
15
|
+
mod utils;
|
|
16
|
+
|
|
17
|
+
mod extensions;
|
|
18
|
+
mod action_management;
|
|
19
|
+
|
|
20
|
+
use utils::{blue, white, yellow, green, gray, red};
|
|
21
|
+
use extensions::{init_v8, inject_extensions};
|
|
22
|
+
use action_management::{
|
|
23
|
+
resolve_actions_dir, find_actions_dir, match_dynamic_route,
|
|
24
|
+
DynamicRoute, RouteVal
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
#[derive(Clone)]
|
|
28
|
+
struct AppState {
|
|
29
|
+
routes: Arc<HashMap<String, RouteVal>>,
|
|
30
|
+
dynamic_routes: Arc<Vec<DynamicRoute>>,
|
|
31
|
+
project_root: PathBuf,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Root/dynamic handlers -----------------------------------------------------
|
|
35
|
+
|
|
36
|
+
async fn root_route(state: State<AppState>, req: Request<Body>) -> impl IntoResponse {
|
|
37
|
+
dynamic_handler_inner(state, req).await
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async fn dynamic_route(state: State<AppState>, req: Request<Body>) -> impl IntoResponse {
|
|
41
|
+
dynamic_handler_inner(state, req).await
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async fn dynamic_handler_inner(
|
|
45
|
+
State(state): State<AppState>,
|
|
46
|
+
req: Request<Body>,
|
|
47
|
+
) -> impl IntoResponse {
|
|
48
|
+
|
|
49
|
+
// ---------------------------
|
|
50
|
+
// BASIC REQUEST INFO
|
|
51
|
+
// ---------------------------
|
|
52
|
+
let method = req.method().as_str().to_uppercase();
|
|
53
|
+
let path = req.uri().path().to_string();
|
|
54
|
+
let key = format!("{}:{}", method, path);
|
|
55
|
+
|
|
56
|
+
// ---------------------------
|
|
57
|
+
// TIMER + LOG META
|
|
58
|
+
// ---------------------------
|
|
59
|
+
let start = Instant::now();
|
|
60
|
+
let mut route_label = String::from("not_found");
|
|
61
|
+
let mut route_kind = "none"; // exact | dynamic | reply
|
|
62
|
+
|
|
63
|
+
// ---------------------------
|
|
64
|
+
// QUERY PARSING
|
|
65
|
+
// ---------------------------
|
|
66
|
+
let query: HashMap<String, String> = req
|
|
67
|
+
.uri()
|
|
68
|
+
.query()
|
|
69
|
+
.map(|q| {
|
|
70
|
+
q.split('&')
|
|
71
|
+
.filter_map(|pair| {
|
|
72
|
+
let mut it = pair.splitn(2, '=');
|
|
73
|
+
Some((
|
|
74
|
+
it.next()?.to_string(),
|
|
75
|
+
it.next().unwrap_or("").to_string(),
|
|
76
|
+
))
|
|
77
|
+
})
|
|
78
|
+
.collect()
|
|
79
|
+
})
|
|
80
|
+
.unwrap_or_default();
|
|
81
|
+
|
|
82
|
+
// ---------------------------
|
|
83
|
+
// HEADERS & BODY
|
|
84
|
+
// ---------------------------
|
|
85
|
+
let (parts, body) = req.into_parts();
|
|
86
|
+
|
|
87
|
+
let headers = parts
|
|
88
|
+
.headers
|
|
89
|
+
.iter()
|
|
90
|
+
.map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
|
|
91
|
+
.collect::<HashMap<String, String>>();
|
|
92
|
+
|
|
93
|
+
let body_bytes = match to_bytes(body, usize::MAX).await {
|
|
94
|
+
Ok(b) => b,
|
|
95
|
+
Err(_) => {
|
|
96
|
+
return (StatusCode::BAD_REQUEST, "Failed to read request body").into_response()
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
let body_str = String::from_utf8_lossy(&body_bytes).to_string();
|
|
101
|
+
let body_json: Value = if body_str.is_empty() {
|
|
102
|
+
Value::Null
|
|
103
|
+
} else {
|
|
104
|
+
serde_json::from_str(&body_str).unwrap_or(Value::String(body_str))
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// ---------------------------
|
|
108
|
+
// ROUTE RESOLUTION
|
|
109
|
+
// ---------------------------
|
|
110
|
+
let mut params: HashMap<String, String> = HashMap::new();
|
|
111
|
+
let mut action_name: Option<String> = None;
|
|
112
|
+
|
|
113
|
+
// Exact route
|
|
114
|
+
if let Some(route) = state.routes.get(&key) {
|
|
115
|
+
route_kind = "exact";
|
|
116
|
+
if route.r#type == "action" {
|
|
117
|
+
let name = route.value.as_str().unwrap_or("unknown").to_string();
|
|
118
|
+
route_label = name.clone();
|
|
119
|
+
action_name = Some(name);
|
|
120
|
+
} else if route.r#type == "json" {
|
|
121
|
+
let elapsed = start.elapsed();
|
|
122
|
+
println!("{} {} {} {}", blue("[Titan]"), white(&format!("{} {}", method, path)), white("→ json"), gray(&format!("in {:.2?}", elapsed)));
|
|
123
|
+
return Json(route.value.clone()).into_response();
|
|
124
|
+
} else if let Some(s) = route.value.as_str() {
|
|
125
|
+
let elapsed = start.elapsed();
|
|
126
|
+
println!("{} {} {} {}", blue("[Titan]"), white(&format!("{} {}", method, path)), white("→ reply"), gray(&format!("in {:.2?}", elapsed)));
|
|
127
|
+
return s.to_string().into_response();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Dynamic route
|
|
132
|
+
if action_name.is_none() {
|
|
133
|
+
if let Some((action, p)) = match_dynamic_route(&method, &path, state.dynamic_routes.as_slice()) {
|
|
134
|
+
route_kind = "dynamic";
|
|
135
|
+
route_label = action.clone();
|
|
136
|
+
action_name = Some(action);
|
|
137
|
+
params = p;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
let action_name = match action_name {
|
|
142
|
+
Some(a) => a,
|
|
143
|
+
None => {
|
|
144
|
+
let elapsed = start.elapsed();
|
|
145
|
+
println!("{} {} {} {}", blue("[Titan]"), white(&format!("{} {}", method, path)), white("→ 404"), gray(&format!("in {:.2?}", elapsed)));
|
|
146
|
+
return (StatusCode::NOT_FOUND, "Not Found").into_response();
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
// ---------------------------
|
|
151
|
+
// LOAD ACTION
|
|
152
|
+
// ---------------------------
|
|
153
|
+
let resolved = resolve_actions_dir();
|
|
154
|
+
let actions_dir = resolved.exists()
|
|
155
|
+
.then(|| resolved)
|
|
156
|
+
.or_else(|| find_actions_dir(&state.project_root))
|
|
157
|
+
.unwrap();
|
|
158
|
+
|
|
159
|
+
let mut action_path = actions_dir.join(format!("{}.jsbundle", action_name));
|
|
160
|
+
if !action_path.exists() {
|
|
161
|
+
let js_path = actions_dir.join(format!("{}.js", action_name));
|
|
162
|
+
if js_path.exists() {
|
|
163
|
+
action_path = js_path;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
let js_code = match fs::read_to_string(&action_path) {
|
|
168
|
+
Ok(c) => c,
|
|
169
|
+
Err(_) => {
|
|
170
|
+
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": "Action bundle not found", "action": action_name}))).into_response()
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
// ---------------------------
|
|
175
|
+
// EXECUTE IN V8
|
|
176
|
+
// ---------------------------
|
|
177
|
+
let env_json = std::env::vars().map(|(k, v)| (k, Value::String(v))).collect::<serde_json::Map<_, _>>();
|
|
178
|
+
|
|
179
|
+
let injected = format!(
|
|
180
|
+
r#"
|
|
181
|
+
globalThis.process = {{ env: {} }};
|
|
182
|
+
const __titan_req = {{
|
|
183
|
+
body: {},
|
|
184
|
+
method: "{}",
|
|
185
|
+
path: "{}",
|
|
186
|
+
headers: {},
|
|
187
|
+
params: {},
|
|
188
|
+
query: {}
|
|
189
|
+
}};
|
|
190
|
+
(function() {{
|
|
191
|
+
{}
|
|
192
|
+
}})(); // Run the bundle
|
|
193
|
+
// Call the action
|
|
194
|
+
if (typeof globalThis["{}"] === 'function') {{
|
|
195
|
+
globalThis["{}"](__titan_req);
|
|
196
|
+
}} else {{
|
|
197
|
+
throw new Error("Action function '{}' not found in bundle");
|
|
198
|
+
}}
|
|
199
|
+
"#,
|
|
200
|
+
Value::Object(env_json).to_string(),
|
|
201
|
+
body_json.to_string(),
|
|
202
|
+
method,
|
|
203
|
+
path,
|
|
204
|
+
serde_json::to_string(&headers).unwrap(),
|
|
205
|
+
serde_json::to_string(¶ms).unwrap(),
|
|
206
|
+
serde_json::to_string(&query).unwrap(),
|
|
207
|
+
js_code,
|
|
208
|
+
action_name,
|
|
209
|
+
action_name,
|
|
210
|
+
action_name
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
// Run V8 in a blocking task safely?
|
|
214
|
+
// Axum handlers are async. V8 operations should be blocking.
|
|
215
|
+
// We can use `task::spawn_blocking`.
|
|
216
|
+
let root = state.project_root.clone();
|
|
217
|
+
let action_name_for_v8 = action_name.clone();
|
|
218
|
+
|
|
219
|
+
let result_json: Value = tokio::task::spawn_blocking(move || {
|
|
220
|
+
let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
|
|
221
|
+
let handle_scope = &mut v8::HandleScope::new(isolate);
|
|
222
|
+
let context = v8::Context::new(handle_scope, v8::ContextOptions::default());
|
|
223
|
+
let scope = &mut v8::ContextScope::new(handle_scope, context);
|
|
224
|
+
|
|
225
|
+
let global = context.global(scope);
|
|
226
|
+
|
|
227
|
+
// Inject extensions (t.read, etc)
|
|
228
|
+
inject_extensions(scope, global);
|
|
229
|
+
|
|
230
|
+
// Set metadata globals
|
|
231
|
+
// Set metadata globals
|
|
232
|
+
let root_str = v8::String::new(scope, root.to_str().unwrap_or(".")).unwrap();
|
|
233
|
+
let root_key = v8::String::new(scope, "__titan_root").unwrap();
|
|
234
|
+
global.set(scope, root_key.into(), root_str.into());
|
|
235
|
+
|
|
236
|
+
let action_str = v8::String::new(scope, &action_name_for_v8).unwrap();
|
|
237
|
+
let action_key = v8::String::new(scope, "__titan_action").unwrap();
|
|
238
|
+
global.set(scope, action_key.into(), action_str.into());
|
|
239
|
+
|
|
240
|
+
let source = v8::String::new(scope, &injected).unwrap();
|
|
241
|
+
|
|
242
|
+
let try_catch = &mut v8::TryCatch::new(scope);
|
|
243
|
+
|
|
244
|
+
let script = match v8::Script::compile(try_catch, source, None) {
|
|
245
|
+
Some(s) => s,
|
|
246
|
+
None => {
|
|
247
|
+
let err = try_catch.message().unwrap();
|
|
248
|
+
let msg = err.get(try_catch).to_rust_string_lossy(try_catch);
|
|
249
|
+
return serde_json::json!({ "error": msg, "phase": "compile" });
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
let result = script.run(try_catch);
|
|
254
|
+
|
|
255
|
+
match result {
|
|
256
|
+
Some(val) => {
|
|
257
|
+
// Convert v8 Value to Serde JSON
|
|
258
|
+
// Minimal impl: stringify
|
|
259
|
+
let json_obj = v8::json::stringify(try_catch, val).unwrap();
|
|
260
|
+
let json_str = json_obj.to_rust_string_lossy(try_catch);
|
|
261
|
+
serde_json::from_str(&json_str).unwrap_or(Value::Null)
|
|
262
|
+
},
|
|
263
|
+
None => {
|
|
264
|
+
let err = try_catch.message().unwrap();
|
|
265
|
+
let msg = err.get(try_catch).to_rust_string_lossy(try_catch);
|
|
266
|
+
serde_json::json!({ "error": msg, "phase": "execution" })
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}).await.unwrap_or(serde_json::json!({"error": "V8 task failed"}));
|
|
270
|
+
|
|
271
|
+
// ---------------------------
|
|
272
|
+
// FINAL LOG
|
|
273
|
+
// ---------------------------
|
|
274
|
+
let elapsed = start.elapsed();
|
|
275
|
+
|
|
276
|
+
// Check for errors in result
|
|
277
|
+
if let Some(err) = result_json.get("error") {
|
|
278
|
+
println!("{} {} {} {}", blue("[Titan]"), red(&format!("{} {}", method, path)), red("→ error"), gray(&format!("in {:.2?}", elapsed)));
|
|
279
|
+
println!("{}", red(err.as_str().unwrap_or("Unknown")));
|
|
280
|
+
return (StatusCode::INTERNAL_SERVER_ERROR, Json(result_json)).into_response();
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
match route_kind {
|
|
284
|
+
"dynamic" => println!("{} {} {} {} {} {}", blue("[Titan]"), green(&format!("{} {}", method, path)), white("→"), green(&route_label), white("(dynamic)"), gray(&format!("in {:.2?}", elapsed))),
|
|
285
|
+
"exact" => println!("{} {} {} {} {}", blue("[Titan]"), white(&format!("{} {}", method, path)), white("→"), yellow(&route_label), gray(&format!("in {:.2?}", elapsed))),
|
|
286
|
+
_ => {}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
Json(result_json).into_response()
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
// Entrypoint ---------------------------------------------------------------
|
|
294
|
+
|
|
295
|
+
#[tokio::main]
|
|
296
|
+
async fn main() -> Result<()> {
|
|
297
|
+
dotenvy::dotenv().ok();
|
|
298
|
+
init_v8(); // Init platform once
|
|
299
|
+
|
|
300
|
+
// Load routes.json
|
|
301
|
+
let raw = fs::read_to_string("./routes.json").unwrap_or_else(|_| "{}".to_string());
|
|
302
|
+
let json: Value = serde_json::from_str(&raw).unwrap_or_default();
|
|
303
|
+
|
|
304
|
+
let port = json["__config"]["port"].as_u64().unwrap_or(3000);
|
|
305
|
+
let routes_json = json["routes"].clone();
|
|
306
|
+
let map: HashMap<String, RouteVal> = serde_json::from_value(routes_json).unwrap_or_default();
|
|
307
|
+
let dynamic_routes: Vec<DynamicRoute> = serde_json::from_value(json["__dynamic_routes"].clone()).unwrap_or_default();
|
|
308
|
+
|
|
309
|
+
// Project root — heuristics
|
|
310
|
+
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
|
|
311
|
+
// Ensure we find the 'app' directory as sibling if running from 'server'
|
|
312
|
+
let project_root = if cwd.join("../app").exists() {
|
|
313
|
+
cwd.join("../app")
|
|
314
|
+
} else {
|
|
315
|
+
cwd
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
let state = AppState {
|
|
319
|
+
routes: Arc::new(map),
|
|
320
|
+
dynamic_routes: Arc::new(dynamic_routes),
|
|
321
|
+
project_root: project_root.clone(),
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
// Load extensions
|
|
325
|
+
extensions::load_project_extensions(project_root.clone());
|
|
326
|
+
|
|
327
|
+
let app = Router::new()
|
|
328
|
+
|
|
329
|
+
.route("/", any(root_route))
|
|
330
|
+
.fallback(any(dynamic_route))
|
|
331
|
+
.with_state(state);
|
|
332
|
+
|
|
333
|
+
let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).await?;
|
|
334
|
+
|
|
335
|
+
println!("\n\x1b[38;5;208m████████╗██╗████████╗ █████╗ ███╗ ██╗");
|
|
336
|
+
println!("╚══██╔══╝██║╚══██╔══╝██╔══██╗████╗ ██║");
|
|
337
|
+
println!(" ██║ ██║ ██║ ███████║██╔██╗ ██║");
|
|
338
|
+
println!(" ██║ ██║ ██║ ██╔══██║██║╚██╗██║");
|
|
339
|
+
println!(" ██║ ██║ ██║ ██║ ██║██║ ╚████║");
|
|
340
|
+
println!(" ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝\x1b[0m\n");
|
|
341
|
+
println!("\x1b[38;5;39mTitan server running at:\x1b[0m http://localhost:{}", port);
|
|
342
|
+
|
|
343
|
+
axum::serve(listener, app).await?;
|
|
344
|
+
Ok(())
|
|
345
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
pub fn blue(s: &str) -> String {
|
|
2
|
+
format!("\x1b[38;5;39m{}\x1b[0m", s)
|
|
3
|
+
}
|
|
4
|
+
pub fn white(s: &str) -> String {
|
|
5
|
+
format!("\x1b[39m{}\x1b[0m", s)
|
|
6
|
+
}
|
|
7
|
+
pub fn yellow(s: &str) -> String {
|
|
8
|
+
format!("\x1b[33m{}\x1b[0m", s)
|
|
9
|
+
}
|
|
10
|
+
pub fn green(s: &str) -> String {
|
|
11
|
+
format!("\x1b[32m{}\x1b[0m", s)
|
|
12
|
+
}
|
|
13
|
+
pub fn gray(s: &str) -> String {
|
|
14
|
+
format!("\x1b[90m{}\x1b[0m", s)
|
|
15
|
+
}
|
|
16
|
+
pub fn red(s: &str) -> String {
|
|
17
|
+
format!("\x1b[31m{}\x1b[0m", s)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
pub fn parse_expires_in(value: &str) -> Option<u64> {
|
|
21
|
+
let (num, unit) = value.split_at(value.len() - 1);
|
|
22
|
+
let n: u64 = num.parse().ok()?;
|
|
23
|
+
|
|
24
|
+
match unit {
|
|
25
|
+
"s" => Some(n),
|
|
26
|
+
"m" => Some(n * 60),
|
|
27
|
+
"h" => Some(n * 60 * 60),
|
|
28
|
+
"d" => Some(n * 60 * 60 * 24),
|
|
29
|
+
_ => None,
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import esbuild from "esbuild";
|
|
4
|
+
|
|
5
|
+
const root = process.cwd();
|
|
6
|
+
const actionsDir = path.join(root, "app", "actions");
|
|
7
|
+
const outDir = path.join(root, "server", "actions");
|
|
8
|
+
|
|
9
|
+
export async function bundle() {
|
|
10
|
+
console.log("[Titan] Bundling actions...");
|
|
11
|
+
|
|
12
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
13
|
+
|
|
14
|
+
// Clean old bundles
|
|
15
|
+
for (const file of fs.readdirSync(outDir)) {
|
|
16
|
+
fs.unlinkSync(path.join(outDir, file));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const files = fs.readdirSync(actionsDir).filter(f => f.endsWith(".js") || f.endsWith(".ts"));
|
|
20
|
+
|
|
21
|
+
for (const file of files) {
|
|
22
|
+
const actionName = path.basename(file, path.extname(file));
|
|
23
|
+
|
|
24
|
+
const entry = path.join(actionsDir, file);
|
|
25
|
+
|
|
26
|
+
// Rust runtime expects `.jsbundle` extension — consistent with previous design
|
|
27
|
+
const outfile = path.join(outDir, actionName + ".jsbundle");
|
|
28
|
+
|
|
29
|
+
console.log(`[Titan] Bundling ${entry} → ${outfile}`);
|
|
30
|
+
|
|
31
|
+
await esbuild.build({
|
|
32
|
+
entryPoints: [entry],
|
|
33
|
+
outfile,
|
|
34
|
+
bundle: true,
|
|
35
|
+
format: "iife",
|
|
36
|
+
globalName: "__titan_exports",
|
|
37
|
+
platform: "neutral",
|
|
38
|
+
target: "es2020",
|
|
39
|
+
banner: {
|
|
40
|
+
js: "const defineAction = (fn) => fn;"
|
|
41
|
+
},
|
|
42
|
+
|
|
43
|
+
footer: {
|
|
44
|
+
js: `
|
|
45
|
+
(function () {
|
|
46
|
+
const fn =
|
|
47
|
+
__titan_exports["${actionName}"] ||
|
|
48
|
+
__titan_exports.default;
|
|
49
|
+
|
|
50
|
+
if (typeof fn !== "function") {
|
|
51
|
+
throw new Error("[Titan] Action '${actionName}' not found or not a function");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
globalThis["${actionName}"] = fn;
|
|
55
|
+
})();
|
|
56
|
+
`
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
console.log("[Titan] Bundling finished.");
|
|
65
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
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
|
+
let serverProcess = null;
|
|
13
|
+
|
|
14
|
+
async function killServer() {
|
|
15
|
+
if (!serverProcess) return;
|
|
16
|
+
|
|
17
|
+
const pid = serverProcess.pid;
|
|
18
|
+
const killPromise = new Promise((resolve) => {
|
|
19
|
+
if (serverProcess.exitCode !== null) return resolve();
|
|
20
|
+
serverProcess.once("close", resolve);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
if (process.platform === "win32") {
|
|
24
|
+
try {
|
|
25
|
+
execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
|
|
26
|
+
} catch (e) {
|
|
27
|
+
// Ignore errors if process is already dead
|
|
28
|
+
}
|
|
29
|
+
} else {
|
|
30
|
+
serverProcess.kill();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
await killPromise;
|
|
35
|
+
} catch (e) { }
|
|
36
|
+
serverProcess = null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function startRustServer() {
|
|
40
|
+
await killServer();
|
|
41
|
+
|
|
42
|
+
// Give the OS a moment to release file locks on the binary
|
|
43
|
+
await new Promise(r => setTimeout(r, 500));
|
|
44
|
+
|
|
45
|
+
const serverPath = path.join(process.cwd(), "server");
|
|
46
|
+
|
|
47
|
+
serverProcess = spawn("cargo", ["run"], {
|
|
48
|
+
cwd: serverPath,
|
|
49
|
+
stdio: "inherit",
|
|
50
|
+
shell: true
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
serverProcess.on("close", (code) => {
|
|
54
|
+
if (code !== null && code !== 0 && code !== 1) {
|
|
55
|
+
// 1 is often just 'terminated' on windows if forced, but also error.
|
|
56
|
+
// We just log it.
|
|
57
|
+
}
|
|
58
|
+
console.log(`[Titan] Rust server exited: ${code}`);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function rebuild() {
|
|
63
|
+
console.log("[Titan] Regenerating routes.json & action_map.json...");
|
|
64
|
+
execSync("node app/app.js", { stdio: "inherit" });
|
|
65
|
+
|
|
66
|
+
console.log("[Titan] Bundling JS actions...");
|
|
67
|
+
await bundle();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function startDev() {
|
|
71
|
+
console.log("[Titan] Dev mode starting...");
|
|
72
|
+
|
|
73
|
+
if (fs.existsSync(path.join(process.cwd(), ".env"))) {
|
|
74
|
+
console.log("\x1b[33m[Titan] Env Configured\x1b[0m");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// FIRST BUILD
|
|
78
|
+
try {
|
|
79
|
+
await rebuild();
|
|
80
|
+
await startRustServer();
|
|
81
|
+
} catch (e) {
|
|
82
|
+
console.log("\x1b[31m[Titan] Initial build failed. Waiting for changes...\x1b[0m");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const watcher = chokidar.watch(["app", ".env"], {
|
|
86
|
+
ignoreInitial: true
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
let timer = null;
|
|
90
|
+
|
|
91
|
+
watcher.on("all", async (event, file) => {
|
|
92
|
+
if (timer) clearTimeout(timer);
|
|
93
|
+
|
|
94
|
+
timer = setTimeout(async () => {
|
|
95
|
+
if (file.includes(".env")) {
|
|
96
|
+
console.log("\x1b[33m[Titan] Env Refreshed\x1b[0m");
|
|
97
|
+
} else {
|
|
98
|
+
console.log(`[Titan] Change detected: ${file}`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
try {
|
|
102
|
+
await rebuild();
|
|
103
|
+
console.log("[Titan] Restarting Rust server...");
|
|
104
|
+
await startRustServer();
|
|
105
|
+
} catch (e) {
|
|
106
|
+
console.log("\x1b[31m[Titan] Build failed -- waiting for changes...\x1b[0m");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
}, 200);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
startDev();
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { bundle } from "./bundle.js";
|
|
4
|
+
|
|
5
|
+
const cyan = (t) => `\x1b[36m${t}\x1b[0m`;
|
|
6
|
+
const green = (t) => `\x1b[32m${t}\x1b[0m`;
|
|
7
|
+
|
|
8
|
+
const routes = {};
|
|
9
|
+
const dynamicRoutes = {};
|
|
10
|
+
const actionMap = {};
|
|
11
|
+
|
|
12
|
+
function addRoute(method, route) {
|
|
13
|
+
const key = `${method.toUpperCase()}:${route}`;
|
|
14
|
+
|
|
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
|
+
const t = {
|
|
44
|
+
get(route) {
|
|
45
|
+
return addRoute("GET", route);
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
post(route) {
|
|
49
|
+
return addRoute("POST", route);
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
log(module, msg) {
|
|
53
|
+
console.log(`[\x1b[35m${module}\x1b[0m] ${msg}`);
|
|
54
|
+
},
|
|
55
|
+
|
|
56
|
+
async start(port = 3000, msg = "") {
|
|
57
|
+
try {
|
|
58
|
+
console.log(cyan("[Titan] Preparing runtime..."));
|
|
59
|
+
await bundle();
|
|
60
|
+
|
|
61
|
+
const base = path.join(process.cwd(), "server");
|
|
62
|
+
if (!fs.existsSync(base)) {
|
|
63
|
+
fs.mkdirSync(base, { recursive: true });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const routesPath = path.join(base, "routes.json");
|
|
67
|
+
const actionMapPath = path.join(base, "action_map.json");
|
|
68
|
+
|
|
69
|
+
fs.writeFileSync(
|
|
70
|
+
routesPath,
|
|
71
|
+
JSON.stringify(
|
|
72
|
+
{
|
|
73
|
+
__config: { port },
|
|
74
|
+
routes,
|
|
75
|
+
__dynamic_routes: Object.values(dynamicRoutes).flat()
|
|
76
|
+
},
|
|
77
|
+
null,
|
|
78
|
+
2
|
|
79
|
+
)
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
fs.writeFileSync(
|
|
83
|
+
actionMapPath,
|
|
84
|
+
JSON.stringify(actionMap, null, 2)
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
console.log(green("✔ Titan metadata written successfully"));
|
|
88
|
+
if (msg) console.log(cyan(msg));
|
|
89
|
+
|
|
90
|
+
} catch (e) {
|
|
91
|
+
console.error(`\x1b[31m[Titan] Build Error: ${e.message}\x1b[0m`);
|
|
92
|
+
process.exit(1);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
globalThis.t = t;
|
|
98
|
+
export default t;
|