@ezetgalaxy/titan 26.8.3 → 26.9.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.
Files changed (97) hide show
  1. package/README.md +63 -14
  2. package/index.js +62 -15
  3. package/package.json +1 -1
  4. package/templates/extension/README.md +104 -104
  5. package/templates/extension/index.js +27 -27
  6. package/templates/extension/jsconfig.json +12 -12
  7. package/templates/extension/native/Cargo.toml +9 -9
  8. package/templates/extension/native/src/lib.rs +5 -5
  9. package/templates/extension/package.json +20 -20
  10. package/templates/extension/titan.json +17 -17
  11. package/templates/js/Dockerfile +66 -66
  12. package/templates/js/_dockerignore +3 -3
  13. package/templates/js/_gitignore +1 -0
  14. package/templates/js/app/actions/hello.js +5 -5
  15. package/templates/js/app/titan.d.ts +87 -87
  16. package/templates/js/jsconfig.json +18 -18
  17. package/templates/js/server/src/action_management.rs +131 -131
  18. package/templates/js/server/src/errors.rs +10 -10
  19. package/templates/js/server/src/extensions.rs +989 -989
  20. package/templates/js/server/src/utils.rs +33 -33
  21. package/templates/js/titan/bundle.js +78 -78
  22. package/templates/js/titan/dev.js +9 -1
  23. package/templates/js/titan/titan.js +122 -122
  24. package/templates/rust/Dockerfile +66 -66
  25. package/templates/rust/_dockerignore +3 -3
  26. package/templates/rust/_gitignore +1 -0
  27. package/templates/rust/app/actions/hello.js +5 -5
  28. package/templates/rust/app/actions/rust_hello.rs +14 -14
  29. package/templates/rust/app/titan.d.ts +101 -101
  30. package/templates/rust/jsconfig.json +18 -18
  31. package/templates/rust/server/src/action_management.rs +131 -131
  32. package/templates/rust/server/src/errors.rs +10 -10
  33. package/templates/rust/server/src/extensions.rs +989 -989
  34. package/templates/rust/server/src/utils.rs +33 -33
  35. package/templates/rust/titan/dev.js +9 -1
  36. package/templates/rust-ts/Dockerfile +66 -0
  37. package/templates/rust-ts/_dockerignore +3 -0
  38. package/templates/rust-ts/_gitignore +38 -0
  39. package/templates/rust-ts/app/actions/hello.ts +5 -0
  40. package/templates/rust-ts/app/actions/rust_hello.rs +14 -0
  41. package/templates/rust-ts/app/app.ts +11 -0
  42. package/templates/rust-ts/app/titan.d.ts +101 -0
  43. package/templates/rust-ts/package.json +14 -0
  44. package/templates/rust-ts/server/Cargo.lock +2869 -0
  45. package/templates/rust-ts/server/Cargo.toml +39 -0
  46. package/templates/rust-ts/server/src/action_management.rs +131 -0
  47. package/templates/rust-ts/server/src/errors.rs +51 -0
  48. package/templates/rust-ts/server/src/extensions.rs +989 -0
  49. package/templates/rust-ts/server/src/main.rs +468 -0
  50. package/templates/rust-ts/server/src/utils.rs +33 -0
  51. package/templates/rust-ts/titan/bundle.js +157 -0
  52. package/templates/rust-ts/titan/dev.js +402 -0
  53. package/templates/rust-ts/titan/titan.js +122 -0
  54. package/templates/rust-ts/tsconfig.json +21 -0
  55. package/templates/ts/Dockerfile +66 -0
  56. package/templates/ts/_dockerignore +3 -0
  57. package/templates/ts/_gitignore +38 -0
  58. package/templates/ts/app/actions/hello.ts +9 -0
  59. package/templates/ts/app/app.ts +10 -0
  60. package/templates/ts/app/titan.d.ts +102 -0
  61. package/templates/ts/package.json +26 -0
  62. package/templates/ts/server/Cargo.lock +2869 -0
  63. package/templates/ts/server/Cargo.toml +27 -0
  64. package/templates/ts/server/src/action_management.rs +131 -0
  65. package/templates/ts/server/src/errors.rs +51 -0
  66. package/templates/ts/server/src/extensions.rs +989 -0
  67. package/templates/ts/server/src/main.rs +437 -0
  68. package/templates/ts/server/src/utils.rs +33 -0
  69. package/templates/ts/titan/bundle.js +78 -0
  70. package/templates/ts/titan/dev.js +402 -0
  71. package/templates/ts/titan/titan.js +122 -0
  72. package/templates/ts/tsconfig.json +16 -0
  73. package/titanpl-sdk/README.md +109 -109
  74. package/titanpl-sdk/bin/run.js +254 -254
  75. package/titanpl-sdk/index.d.ts +46 -46
  76. package/titanpl-sdk/index.js +5 -5
  77. package/titanpl-sdk/package.json +32 -32
  78. package/titanpl-sdk/templates/.dockerignore +3 -3
  79. package/titanpl-sdk/templates/Dockerfile +53 -53
  80. package/titanpl-sdk/templates/app/actions/hello.js +5 -5
  81. package/titanpl-sdk/templates/app/titan.d.ts +87 -87
  82. package/titanpl-sdk/templates/jsconfig.json +18 -18
  83. package/titanpl-sdk/templates/server/src/action_management.rs +131 -131
  84. package/titanpl-sdk/templates/server/src/errors.rs +10 -10
  85. package/titanpl-sdk/templates/server/src/extensions.rs +640 -640
  86. package/titanpl-sdk/templates/server/src/utils.rs +33 -33
  87. package/titanpl-sdk/templates/titan/bundle.js +65 -65
  88. package/titanpl-sdk/templates/titan/dev.js +113 -113
  89. package/titanpl-sdk/templates/titan/titan.js +98 -98
  90. package/templates/js/server/action_map.json +0 -3
  91. package/templates/js/server/actions/hello.jsbundle +0 -48
  92. package/templates/js/server/routes.json +0 -16
  93. package/templates/rust/server/action_map.json +0 -3
  94. package/templates/rust/server/actions/hello.jsbundle +0 -47
  95. package/templates/rust/server/routes.json +0 -22
  96. package/templates/rust/server/src/actions_rust/mod.rs +0 -19
  97. package/templates/rust/server/src/actions_rust/rust_hello.rs +0 -14
@@ -0,0 +1,468 @@
1
+ use anyhow::Result;
2
+ use axum::{
3
+ Router,
4
+ body::{Body, to_bytes},
5
+ extract::State,
6
+ http::{Request, StatusCode},
7
+ response::{IntoResponse, Json},
8
+ routing::any,
9
+ };
10
+ use serde_json::Value;
11
+ use std::time::Instant;
12
+ use std::{collections::HashMap, fs, path::PathBuf, sync::Arc};
13
+ use tokio::net::TcpListener;
14
+
15
+ mod utils;
16
+ mod errors;
17
+
18
+ mod action_management;
19
+ mod extensions;
20
+ mod actions_rust;
21
+
22
+ use action_management::{
23
+ DynamicRoute, RouteVal, find_actions_dir, match_dynamic_route, resolve_actions_dir,
24
+ };
25
+ use extensions::{init_v8, inject_extensions};
26
+ use utils::{blue, gray, green, red, white, yellow};
27
+
28
+ #[derive(Clone)]
29
+ struct AppState {
30
+ routes: Arc<HashMap<String, RouteVal>>,
31
+ dynamic_routes: Arc<Vec<DynamicRoute>>,
32
+ project_root: PathBuf,
33
+ }
34
+
35
+ // Root/dynamic handlers -----------------------------------------------------
36
+
37
+ async fn root_route(state: State<AppState>, req: Request<Body>) -> impl IntoResponse {
38
+ dynamic_handler_inner(state, req).await
39
+ }
40
+
41
+ async fn dynamic_route(state: State<AppState>, req: Request<Body>) -> impl IntoResponse {
42
+ dynamic_handler_inner(state, req).await
43
+ }
44
+
45
+ async fn dynamic_handler_inner(
46
+ State(state): State<AppState>,
47
+ req: Request<Body>,
48
+ ) -> impl IntoResponse {
49
+ // ---------------------------
50
+ // BASIC REQUEST INFO (No body consumption yet)
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
+ // ROUTE RESOLUTION
65
+ // ---------------------------
66
+ let mut params: HashMap<String, String> = HashMap::new();
67
+ let mut action_name: Option<String> = None;
68
+
69
+ // Exact route
70
+ if let Some(route) = state.routes.get(&key) {
71
+ route_kind = "exact";
72
+ if route.r#type == "action" {
73
+ let name = route.value.as_str().unwrap_or("unknown").to_string();
74
+ route_label = name.clone();
75
+ action_name = Some(name);
76
+ } else if route.r#type == "json" {
77
+ let elapsed = start.elapsed();
78
+ println!(
79
+ "{} {} {} {}",
80
+ blue("[Titan]"),
81
+ white(&format!("{} {}", method, path)),
82
+ white("→ json"),
83
+ gray(&format!("in {:.2?}", elapsed))
84
+ );
85
+ return Json(route.value.clone()).into_response();
86
+ } else if let Some(s) = route.value.as_str() {
87
+ let elapsed = start.elapsed();
88
+ println!(
89
+ "{} {} {} {}",
90
+ blue("[Titan]"),
91
+ white(&format!("{} {}", method, path)),
92
+ white("→ reply"),
93
+ gray(&format!("in {:.2?}", elapsed))
94
+ );
95
+ return s.to_string().into_response();
96
+ }
97
+ }
98
+
99
+ // Dynamic route
100
+ if action_name.is_none() {
101
+ if let Some((action, p)) =
102
+ match_dynamic_route(&method, &path, state.dynamic_routes.as_slice())
103
+ {
104
+ route_kind = "dynamic";
105
+ route_label = action.clone();
106
+ action_name = Some(action);
107
+ params = p;
108
+ }
109
+ }
110
+
111
+ // ---------------------------
112
+ // RUST ACTION CHECK
113
+ // ---------------------------
114
+ if let Some(name) = &action_name {
115
+ if let Some(rust_action) = actions_rust::get_action(name) {
116
+ let elapsed = start.elapsed();
117
+ match route_kind {
118
+ "dynamic" => println!(
119
+ "{} {} {} {} {} {}",
120
+ blue("[Titan]"),
121
+ green(&format!("{} {}", method, path)),
122
+ white("→"),
123
+ green(&route_label),
124
+ white("(rust)"),
125
+ gray(&format!("in {:.2?}", elapsed))
126
+ ),
127
+ "exact" => println!(
128
+ "{} {} {} {} {} {}",
129
+ blue("[Titan]"),
130
+ white(&format!("{} {}", method, path)),
131
+ white("→"),
132
+ yellow(&route_label),
133
+ white("(rust)"),
134
+ gray(&format!("in {:.2?}", elapsed))
135
+ ),
136
+ _ => {}
137
+ }
138
+ return rust_action(req).await.into_response();
139
+ }
140
+ }
141
+
142
+ // ---------------------------
143
+ // QUERY PARSING (For JS)
144
+ // ---------------------------
145
+ let query: HashMap<String, String> = req
146
+ .uri()
147
+ .query()
148
+ .map(|q| {
149
+ q.split('&')
150
+ .filter_map(|pair| {
151
+ let mut it = pair.splitn(2, '=');
152
+ Some((it.next()?.to_string(), it.next().unwrap_or("").to_string()))
153
+ })
154
+ .collect()
155
+ })
156
+ .unwrap_or_default();
157
+
158
+ // ---------------------------
159
+ // HEADERS & BODY (CONSUME REQ)
160
+ // ---------------------------
161
+ let (parts, body) = req.into_parts();
162
+
163
+ let headers = parts
164
+ .headers
165
+ .iter()
166
+ .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
167
+ .collect::<HashMap<String, String>>();
168
+
169
+ let body_bytes = match to_bytes(body, usize::MAX).await {
170
+ Ok(b) => b,
171
+ Err(_) => return (StatusCode::BAD_REQUEST, "Failed to read request body").into_response(),
172
+ };
173
+
174
+ let body_str = String::from_utf8_lossy(&body_bytes).to_string();
175
+ let body_json: Value = if body_str.is_empty() {
176
+ Value::Null
177
+ } else {
178
+ serde_json::from_str(&body_str).unwrap_or(Value::String(body_str))
179
+ };
180
+
181
+ let action_name = match action_name {
182
+ Some(a) => a,
183
+ None => {
184
+ let elapsed = start.elapsed();
185
+ println!(
186
+ "{} {} {} {}",
187
+ blue("[Titan]"),
188
+ white(&format!("{} {}", method, path)),
189
+ white("→ 404"),
190
+ gray(&format!("in {:.2?}", elapsed))
191
+ );
192
+ return (StatusCode::NOT_FOUND, "Not Found").into_response();
193
+ }
194
+ };
195
+
196
+ // ---------------------------
197
+ // LOAD JS ACTION
198
+ // ---------------------------
199
+ let resolved = resolve_actions_dir();
200
+ let actions_dir = resolved
201
+ .exists()
202
+ .then(|| resolved)
203
+ .or_else(|| find_actions_dir(&state.project_root))
204
+ .unwrap();
205
+
206
+ let mut action_path = actions_dir.join(format!("{}.jsbundle", action_name));
207
+ if !action_path.exists() {
208
+ let js_path = actions_dir.join(format!("{}.js", action_name));
209
+ if js_path.exists() {
210
+ action_path = js_path;
211
+ }
212
+ }
213
+
214
+ let js_code =
215
+ match fs::read_to_string(&action_path) {
216
+ Ok(c) => c,
217
+ Err(_) => return (
218
+ StatusCode::INTERNAL_SERVER_ERROR,
219
+ Json(
220
+ serde_json::json!({"error": "Action bundle not found", "action": action_name}),
221
+ ),
222
+ )
223
+ .into_response(),
224
+ };
225
+
226
+ // ---------------------------
227
+ // EXECUTE IN V8
228
+ // ---------------------------
229
+ let env_json = std::env::vars()
230
+ .map(|(k, v)| (k, Value::String(v)))
231
+ .collect::<serde_json::Map<_, _>>();
232
+
233
+ let injected = format!(
234
+ r#"
235
+ globalThis.process = {{ env: {} }};
236
+ const __titan_req = {{
237
+ body: {},
238
+ method: "{}",
239
+ path: "{}",
240
+ headers: {},
241
+ params: {},
242
+ query: {}
243
+ }};
244
+ (function() {{
245
+ {}
246
+ }})(); // Run the bundle
247
+ // Call the action
248
+ if (typeof globalThis["{}"] === 'function') {{
249
+ globalThis["{}"](__titan_req);
250
+ }} else {{
251
+ throw new Error("Action function '{}' not found in bundle");
252
+ }}
253
+ "#,
254
+ Value::Object(env_json).to_string(),
255
+ body_json.to_string(),
256
+ method,
257
+ path,
258
+ serde_json::to_string(&headers).unwrap(),
259
+ serde_json::to_string(&params).unwrap(),
260
+ serde_json::to_string(&query).unwrap(),
261
+ js_code,
262
+ action_name,
263
+ action_name,
264
+ action_name
265
+ );
266
+
267
+ // Run V8 in a blocking task safely?
268
+ // Axum handlers are async. V8 operations should be blocking.
269
+ // We can use `task::spawn_blocking`.
270
+ let root = state.project_root.clone();
271
+ let action_name_for_v8 = action_name.clone();
272
+
273
+ let result_json: Value = tokio::task::spawn_blocking(move || {
274
+ let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
275
+ let handle_scope = &mut v8::HandleScope::new(isolate);
276
+ let context = v8::Context::new(handle_scope, v8::ContextOptions::default());
277
+ let scope = &mut v8::ContextScope::new(handle_scope, context);
278
+
279
+ let global = context.global(scope);
280
+
281
+ // Inject extensions (t.read, etc)
282
+ inject_extensions(scope, global);
283
+
284
+ // Set metadata globals
285
+ let root_str = v8::String::new(scope, root.to_str().unwrap_or(".")).unwrap();
286
+ let root_key = v8::String::new(scope, "__titan_root").unwrap();
287
+ global.set(scope, root_key.into(), root_str.into());
288
+
289
+ let action_str = v8::String::new(scope, &action_name_for_v8).unwrap();
290
+ let action_key = v8::String::new(scope, "__titan_action").unwrap();
291
+ global.set(scope, action_key.into(), action_str.into());
292
+
293
+ let try_catch = &mut v8::TryCatch::new(scope);
294
+
295
+ let source = v8::String::new(try_catch, &injected).unwrap();
296
+ let resource_name = v8::String::new(try_catch, &format!("app/actions/{}.ts", action_name_for_v8)).unwrap();
297
+ let source_map_url = v8::String::new(try_catch, "").unwrap();
298
+
299
+ let origin = v8::ScriptOrigin::new(
300
+ try_catch,
301
+ resource_name.into(),
302
+ 0, // line offset
303
+ 0, // column offset
304
+ false, // is_shared_cross_origin
305
+ 123, // script_id
306
+ None, // source_map_url
307
+ true, // is_opaque
308
+ false, // is_wasm
309
+ false, // is_module
310
+ None,
311
+ );
312
+
313
+ let script = match v8::Script::compile(try_catch, source, Some(&origin)) {
314
+ Some(s) => s,
315
+ None => {
316
+ let msg = crate::errors::format_v8_error(try_catch, &action_name_for_v8);
317
+ return serde_json::json!({ "error": msg, "phase": "compile" });
318
+ }
319
+ };
320
+
321
+ let result = script.run(try_catch);
322
+
323
+ match result {
324
+ Some(val) => {
325
+ // Convert v8 Value to Serde JSON
326
+ // Minimal impl: stringify
327
+ let json_obj = v8::json::stringify(try_catch, val).unwrap();
328
+ let json_str = json_obj.to_rust_string_lossy(try_catch);
329
+ serde_json::from_str(&json_str).unwrap_or(Value::Null)
330
+ }
331
+ None => {
332
+ let msg = crate::errors::format_v8_error(try_catch, &action_name_for_v8);
333
+ serde_json::json!({ "error": msg, "phase": "execution" })
334
+ }
335
+ }
336
+ })
337
+ .await
338
+ .unwrap_or(serde_json::json!({"error": "V8 task failed"}));
339
+
340
+ // ---------------------------
341
+ // FINAL LOG
342
+ // ---------------------------
343
+ let elapsed = start.elapsed();
344
+
345
+ // Check for errors in result
346
+ if let Some(err) = result_json.get("error") {
347
+ println!(
348
+ "{} {} {} {}",
349
+ blue("[Titan]"),
350
+ red(&format!("{} {}", method, path)),
351
+ red("→ error"),
352
+ gray(&format!("in {:.2?}", elapsed))
353
+ );
354
+ println!("{}", red(err.as_str().unwrap_or("Unknown")));
355
+ return (StatusCode::INTERNAL_SERVER_ERROR, Json(result_json)).into_response();
356
+ }
357
+
358
+ match route_kind {
359
+ "dynamic" => println!(
360
+ "{} {} {} {} {} {}",
361
+ blue("[Titan]"),
362
+ green(&format!("{} {}", method, path)),
363
+ white("→"),
364
+ green(&route_label),
365
+ white("(dynamic)"),
366
+ gray(&format!("in {:.2?}", elapsed))
367
+ ),
368
+ "exact" => println!(
369
+ "{} {} {} {} {}",
370
+ blue("[Titan]"),
371
+ white(&format!("{} {}", method, path)),
372
+ white("→"),
373
+ yellow(&route_label),
374
+ gray(&format!("in {:.2?}", elapsed))
375
+ ),
376
+ _ => {}
377
+ }
378
+
379
+ Json(result_json).into_response()
380
+ }
381
+
382
+ // Entrypoint ---------------------------------------------------------------
383
+
384
+ #[tokio::main]
385
+ async fn main() -> Result<()> {
386
+ dotenvy::dotenv().ok();
387
+ init_v8(); // Init platform once
388
+
389
+ // Load routes.json
390
+ let raw = fs::read_to_string("./routes.json").unwrap_or_else(|_| "{}".to_string());
391
+ let json: Value = serde_json::from_str(&raw).unwrap_or_default();
392
+
393
+ let port = json["__config"]["port"].as_u64().unwrap_or(3000);
394
+ let routes_json = json["routes"].clone();
395
+ let map: HashMap<String, RouteVal> = serde_json::from_value(routes_json).unwrap_or_default();
396
+ let dynamic_routes: Vec<DynamicRoute> =
397
+ serde_json::from_value(json["__dynamic_routes"].clone()).unwrap_or_default();
398
+
399
+ // Identify project root (where .ext or node_modules lives)
400
+ let project_root = resolve_project_root();
401
+
402
+ let state = AppState {
403
+ routes: Arc::new(map),
404
+ dynamic_routes: Arc::new(dynamic_routes),
405
+ project_root: project_root.clone(),
406
+ };
407
+
408
+ // Load extensions
409
+ extensions::load_project_extensions(project_root.clone());
410
+
411
+ let app = Router::new()
412
+ .route("/", any(root_route))
413
+ .fallback(any(dynamic_route))
414
+ .with_state(state);
415
+
416
+ let listener = loop {
417
+ match TcpListener::bind(format!("0.0.0.0:{}", port)).await {
418
+ Ok(l) => break l,
419
+ Err(e) => {
420
+ if e.kind() == std::io::ErrorKind::AddrInUse {
421
+ println!(
422
+ "{} {}",
423
+ utils::yellow("[Titan]"),
424
+ utils::gray("Port in use, waiting for orbit to clear...")
425
+ );
426
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
427
+ continue;
428
+ }
429
+ return Err(e.into());
430
+ }
431
+ }
432
+ };
433
+
434
+ println!(
435
+ "\x1b[38;5;39mTitan server running at:\x1b[0m http://localhost:{}",
436
+ port
437
+ );
438
+
439
+ axum::serve(listener, app).await?;
440
+ Ok(())
441
+ }
442
+
443
+ fn resolve_project_root() -> PathBuf {
444
+ // 1. Check CWD (preferred for local dev/tooling)
445
+ if let Ok(cwd) = std::env::current_dir() {
446
+ if cwd.join("node_modules").exists()
447
+ || cwd.join("package.json").exists()
448
+ || cwd.join(".ext").exists()
449
+ {
450
+ return cwd;
451
+ }
452
+ }
453
+
454
+ // 2. Check executable persistence (Docker / Production)
455
+ // Walk up from the executable to find .ext or node_modules
456
+ if let Ok(exe) = std::env::current_exe() {
457
+ let mut current = exe.parent();
458
+ while let Some(dir) = current {
459
+ if dir.join(".ext").exists() || dir.join("node_modules").exists() {
460
+ return dir.to_path_buf();
461
+ }
462
+ current = dir.parent();
463
+ }
464
+ }
465
+
466
+ // 3. Fallback to CWD
467
+ std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
468
+ }
@@ -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,157 @@
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
+ const rustOutDir = path.join(root, "server", "src", "actions_rust");
9
+
10
+ export async function bundle() {
11
+ const start = Date.now();
12
+ await bundleJs();
13
+ await bundleRust();
14
+ // console.log(`[Titan] Bundle finished in ${((Date.now() - start) / 1000).toFixed(2)}s`);
15
+ }
16
+
17
+ async function bundleJs() {
18
+ // console.log("[Titan] Bundling JS actions...");
19
+
20
+ fs.mkdirSync(outDir, { recursive: true });
21
+
22
+ // Clean old bundles
23
+ const oldFiles = fs.readdirSync(outDir);
24
+ for (const file of oldFiles) {
25
+ fs.unlinkSync(path.join(outDir, file));
26
+ }
27
+
28
+ const files = fs.readdirSync(actionsDir).filter(f => f.endsWith(".js") || f.endsWith(".ts"));
29
+ if (files.length === 0) return;
30
+
31
+ // console.log(`[Titan] Bundling ${files.length} JS actions...`);
32
+
33
+ for (const file of files) {
34
+ const actionName = path.basename(file, path.extname(file));
35
+
36
+ const entry = path.join(actionsDir, file);
37
+
38
+ // Rust runtime expects `.jsbundle` extension — consistent with previous design
39
+ const outfile = path.join(outDir, actionName + ".jsbundle");
40
+
41
+ // console.log(`[Titan] Bundling ${entry} → ${outfile}`);
42
+
43
+ await esbuild.build({
44
+ entryPoints: [entry],
45
+ outfile,
46
+ bundle: true,
47
+ format: "iife",
48
+ globalName: "__titan_exports",
49
+ platform: "neutral",
50
+ target: "es2020",
51
+ logLevel: "silent",
52
+ banner: {
53
+ js: "const defineAction = (fn) => fn;"
54
+ },
55
+
56
+ footer: {
57
+ js: `
58
+ (function () {
59
+ const fn =
60
+ __titan_exports["${actionName}"] ||
61
+ __titan_exports.default;
62
+
63
+ if (typeof fn !== "function") {
64
+ throw new Error("[Titan] Action '${actionName}' not found or not a function");
65
+ }
66
+
67
+ globalThis["${actionName}"] = function(request_arg) {
68
+ globalThis.req = request_arg;
69
+ return fn(request_arg);
70
+ };
71
+ })();
72
+ `
73
+ }
74
+ });
75
+ }
76
+
77
+ // console.log("[Titan] JS Bundling finished.");
78
+ }
79
+
80
+ export async function bundleRust() {
81
+ // console.log("[Titan] Bundling Rust actions...");
82
+
83
+ if (!fs.existsSync(rustOutDir)) {
84
+ fs.mkdirSync(rustOutDir, { recursive: true });
85
+ }
86
+
87
+ // Clean old rust actions
88
+ for (const file of fs.readdirSync(rustOutDir)) {
89
+ fs.unlinkSync(path.join(rustOutDir, file));
90
+ }
91
+
92
+ const files = fs.readdirSync(actionsDir).filter(f => f.endsWith(".rs"));
93
+ if (files.length > 0) {
94
+ // console.log(`[Titan] Bundling ${files.length} Rust actions...`);
95
+ }
96
+
97
+ const modules = [];
98
+
99
+ for (const file of files) {
100
+ const actionName = path.basename(file, ".rs");
101
+ const entry = path.join(actionsDir, file);
102
+ let outfile = path.join(rustOutDir, file);
103
+
104
+ let content = fs.readFileSync(entry, 'utf-8');
105
+
106
+ // Prepend implicit imports if not present
107
+ let finalContent = content;
108
+ if (!content.includes("use crate::extensions::t;")) {
109
+ finalContent = "use crate::extensions::t;\n" + content;
110
+ }
111
+
112
+ // Basic validation - check if it has a run function
113
+ if (!content.includes("async fn run")) {
114
+ console.warn(`[Titan] Warning: ${file} does not appear to have an 'async fn run'. It might fail to compile.`);
115
+ }
116
+
117
+ fs.writeFileSync(outfile, finalContent);
118
+ modules.push(actionName);
119
+ // console.log(`[Titan] Copied Rust action ${actionName}`);
120
+ }
121
+
122
+ // Generate mod.rs
123
+ let modContent = `// Auto-generated by Titan. Do not edit.
124
+ use axum::response::IntoResponse;
125
+ use axum::http::Request;
126
+ use axum::body::Body;
127
+ use std::future::Future;
128
+ use std::pin::Pin;
129
+
130
+ `;
131
+
132
+ // Add mod declarations
133
+ for (const mod of modules) {
134
+ modContent += `pub mod ${mod};\n`;
135
+ }
136
+
137
+ modContent += `
138
+ pub type ActionFn = fn(Request<Body>) -> Pin<Box<dyn Future<Output = axum::response::Response> + Send>>;
139
+
140
+ pub fn get_action(name: &str) -> Option<ActionFn> {
141
+ match name {
142
+ `;
143
+
144
+ for (const mod of modules) {
145
+ modContent += ` "${mod}" => Some(|req| Box::pin(async move {
146
+ ${mod}::run(req).await.into_response()
147
+ })),\n`;
148
+ }
149
+
150
+ modContent += ` _ => None
151
+ }
152
+ }
153
+ `;
154
+
155
+ fs.writeFileSync(path.join(rustOutDir, "mod.rs"), modContent);
156
+ // console.log("[Titan] Rust Bundling finished.");
157
+ }