@ezetgalaxy/titan 26.13.6 → 26.13.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,82 +1,631 @@
1
- // -- Module Definitions (for imports from "titan") --
1
+ // =============================================================================
2
+ // Titan Planet — Type Definitions
3
+ // Framework: JavaScript-first backend compiled to native Rust + Axum binary
4
+ // Version: v26 (Stable)
5
+ // Docs: https://titan-docs-ez.vercel.app/docs
6
+ // GitHub: https://github.com/ezet-galaxy/titanpl
7
+ // =============================================================================
2
8
 
9
+ // ---------------------------------------------------------------------------
10
+ // Module Definitions — Imports from "titan"
11
+ // ---------------------------------------------------------------------------
12
+
13
+ /**
14
+ * Represents a normalized HTTP request object passed to every Titan action.
15
+ *
16
+ * This object is **stable, predictable, and serializable** — it is identical
17
+ * across both development (`titan dev`) and production (native binary) modes.
18
+ *
19
+ * @example
20
+ * ```js
21
+ * // Accessing the request inside an action
22
+ * export function getUser(req) {
23
+ * const userId = req.params.id; // Route parameter
24
+ * const page = req.query.page; // Query string ?page=2
25
+ * const data = req.body; // Parsed JSON body (POST/PUT/PATCH)
26
+ * const auth = req.headers["authorization"];
27
+ * return { userId, page, data, auth };
28
+ * }
29
+ * ```
30
+ *
31
+ * @see https://titan-docs-ez.vercel.app/docs/03-actions — Actions documentation
32
+ * @see https://titan-docs-ez.vercel.app/docs/02-routes — Routes & parameters
33
+ */
3
34
  export interface TitanRequest {
35
+ /**
36
+ * The parsed request body.
37
+ *
38
+ * - For `POST`, `PUT`, and `PATCH` requests, this contains the parsed JSON payload.
39
+ * - For `GET` and `DELETE` requests, this is typically `null`.
40
+ *
41
+ * Titan automatically parses `application/json` bodies — no middleware needed.
42
+ *
43
+ * @example
44
+ * ```js
45
+ * export function createUser(req) {
46
+ * const { name, email } = req.body;
47
+ * return { created: true, name, email };
48
+ * }
49
+ * ```
50
+ */
4
51
  body: any;
52
+
53
+ /**
54
+ * The HTTP method of the incoming request.
55
+ *
56
+ * Titan performs automatic method matching at the route level, so each
57
+ * action typically handles a single method. However, you can inspect
58
+ * this property to branch logic if needed.
59
+ *
60
+ * @example
61
+ * ```js
62
+ * export function handler(req) {
63
+ * if (req.method === "POST") return createItem(req.body);
64
+ * if (req.method === "GET") return listItems();
65
+ * }
66
+ * ```
67
+ */
5
68
  method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
69
+
70
+ /**
71
+ * The full URL path of the request (e.g., `"/user/42"`).
72
+ *
73
+ * This is the raw matched path including resolved dynamic segments.
74
+ */
6
75
  path: string;
76
+
77
+ /**
78
+ * All HTTP request headers as a flat key-value map.
79
+ *
80
+ * Header names are **lowercased** (e.g., `"content-type"`, `"authorization"`).
81
+ * A header may be `undefined` if it was not sent by the client.
82
+ *
83
+ * @example
84
+ * ```js
85
+ * export function secureAction(req) {
86
+ * const token = req.headers["authorization"];
87
+ * if (!token) return { error: "Unauthorized" };
88
+ * // ...
89
+ * }
90
+ * ```
91
+ */
7
92
  headers: Record<string, string | undefined>;
93
+
94
+ /**
95
+ * Dynamic route parameters extracted from the URL path.
96
+ *
97
+ * Defined by route segments like `:id` or typed segments like `:id<number>`.
98
+ * Values are always delivered as **strings** — cast them as needed.
99
+ *
100
+ * @example
101
+ * ```js
102
+ * // Route: /user/:id<number>
103
+ * export function getUser(req) {
104
+ * const id = Number(req.params.id); // "42" → 42
105
+ * return { id };
106
+ * }
107
+ * ```
108
+ *
109
+ * @see https://titan-docs-ez.vercel.app/docs/02-routes — Dynamic routes
110
+ */
8
111
  params: Record<string, string>;
112
+
113
+ /**
114
+ * Parsed query string parameters from the URL.
115
+ *
116
+ * For a request to `/search?q=titan&page=2`, this would be:
117
+ * `{ q: "titan", page: "2" }`.
118
+ *
119
+ * Values are always strings. Returns an empty object `{}` when no
120
+ * query parameters are present.
121
+ *
122
+ * @example
123
+ * ```js
124
+ * // GET /products?category=electronics&limit=10
125
+ * export function listProducts(req) {
126
+ * const category = req.query.category; // "electronics"
127
+ * const limit = Number(req.query.limit) || 20;
128
+ * return { category, limit };
129
+ * }
130
+ * ```
131
+ */
9
132
  query: Record<string, string>;
10
133
  }
11
134
 
135
+ /**
136
+ * Wraps an action handler function with type-safe request typing.
137
+ *
138
+ * `defineAction` is an optional helper that provides IntelliSense and
139
+ * type-checking for your action's `req` parameter and return value.
140
+ * It is **purely a development-time utility** — at runtime it simply
141
+ * returns the same function unchanged (zero overhead).
142
+ *
143
+ * @typeParam T - The return type of the action handler.
144
+ * @param handler - The action function that receives a `TitanRequest` and returns `T`.
145
+ * @returns The same handler function with proper type annotations.
146
+ *
147
+ * @example
148
+ * ```js
149
+ * import { defineAction } from "titan";
150
+ *
151
+ * export const getUser = defineAction((req) => {
152
+ * // req is fully typed as TitanRequest
153
+ * const id = Number(req.params.id);
154
+ * return { id, method: req.method };
155
+ * });
156
+ * ```
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * // TypeScript — with explicit return type
161
+ * import { defineAction } from "titan";
162
+ *
163
+ * interface UserResponse { id: number; name: string; }
164
+ *
165
+ * export const getUser = defineAction<UserResponse>((req) => {
166
+ * return { id: Number(req.params.id), name: "Titan" };
167
+ * });
168
+ * ```
169
+ *
170
+ * @see https://titan-docs-ez.vercel.app/docs/03-actions — Action definition patterns
171
+ */
12
172
  export function defineAction<T>(
13
173
  handler: (req: TitanRequest) => T
14
174
  ): (req: TitanRequest) => T;
15
175
 
176
+ /**
177
+ * Built-in Rust-powered HTTP client.
178
+ *
179
+ * Re-exported from the `t` global for module-style imports.
180
+ * @see {@link TitanRuntimeUtils.fetch} for full documentation.
181
+ */
16
182
  export const fetch: typeof t.fetch;
183
+
184
+ /**
185
+ * Action-scoped logging utility.
186
+ *
187
+ * Re-exported from the `t` global for module-style imports.
188
+ * @see {@link TitanRuntimeUtils.log} for full documentation.
189
+ */
17
190
  export const log: typeof t.log;
191
+
192
+ /**
193
+ * Synchronous file reader for local files.
194
+ *
195
+ * Re-exported from the `t` global for module-style imports.
196
+ * @see {@link TitanRuntimeUtils.read} for full documentation.
197
+ */
18
198
  export const read: typeof t.read;
19
199
 
200
+ /**
201
+ * JWT (JSON Web Token) signing and verification utilities.
202
+ *
203
+ * Re-exported from the `t` global for module-style imports.
204
+ * @see {@link TitanRuntimeUtils.jwt} for full documentation.
205
+ */
20
206
  export const jwt: typeof t.jwt;
207
+
208
+ /**
209
+ * Secure password hashing and verification (bcrypt-based).
210
+ *
211
+ * Re-exported from the `t` global for module-style imports.
212
+ * @see {@link TitanRuntimeUtils.password} for full documentation.
213
+ */
21
214
  export const password: typeof t.password;
215
+
216
+ /**
217
+ * Database connection and query interface.
218
+ *
219
+ * Re-exported from the `t` global for module-style imports.
220
+ * @see {@link TitanRuntimeUtils.db} for full documentation.
221
+ */
22
222
  export const db: typeof t.db;
23
223
 
224
+ /**
225
+ * Async file system operations (read, write, mkdir, stat, etc.).
226
+ *
227
+ * Re-exported from the `t` global for module-style imports.
228
+ * @see {@link TitanCore.FileSystem} for full documentation.
229
+ */
24
230
  export const fs: typeof t.fs;
231
+
232
+ /**
233
+ * Path manipulation utilities (join, resolve, extname, etc.).
234
+ *
235
+ * Re-exported from the `t` global for module-style imports.
236
+ * @see {@link TitanCore.Path} for full documentation.
237
+ */
25
238
  export const path: typeof t.path;
26
239
 
240
+ /**
241
+ * Cryptographic utilities (hashing, encryption, UUIDs, etc.).
242
+ *
243
+ * Re-exported from the `t` global for module-style imports.
244
+ * @see {@link TitanCore.Crypto} for full documentation.
245
+ */
27
246
  export const crypto: typeof t.crypto;
247
+
248
+ /**
249
+ * Buffer encoding/decoding utilities (Base64, Hex, UTF-8).
250
+ *
251
+ * Re-exported from the `t` global for module-style imports.
252
+ * @see {@link TitanCore.BufferModule} for full documentation.
253
+ */
28
254
  export const buffer: typeof t.buffer;
29
255
 
256
+ /**
257
+ * Persistent key-value local storage (shorthand alias).
258
+ *
259
+ * Re-exported from the `t` global for module-style imports.
260
+ * @see {@link TitanCore.LocalStorage} for full documentation.
261
+ */
30
262
  export const ls: typeof t.ls;
263
+
264
+ /**
265
+ * Persistent key-value local storage.
266
+ *
267
+ * Re-exported from the `t` global for module-style imports.
268
+ * @see {@link TitanCore.LocalStorage} for full documentation.
269
+ */
31
270
  export const localStorage: typeof t.localStorage;
271
+
272
+ /**
273
+ * Server-side session management by session ID.
274
+ *
275
+ * Re-exported from the `t` global for module-style imports.
276
+ * @see {@link TitanCore.Session} for full documentation.
277
+ */
32
278
  export const session: typeof t.session;
279
+
280
+ /**
281
+ * HTTP cookie read/write/delete utilities.
282
+ *
283
+ * Re-exported from the `t` global for module-style imports.
284
+ * @see {@link TitanCore.Cookies} for full documentation.
285
+ */
33
286
  export const cookies: typeof t.cookies;
34
287
 
288
+ /**
289
+ * Operating system information (platform, CPU count, memory).
290
+ *
291
+ * Re-exported from the `t` global for module-style imports.
292
+ * @see {@link TitanCore.OS} for full documentation.
293
+ */
35
294
  export const os: typeof t.os;
295
+
296
+ /**
297
+ * Network utilities (DNS resolution, IP lookup, ping).
298
+ *
299
+ * Re-exported from the `t` global for module-style imports.
300
+ * @see {@link TitanCore.Net} for full documentation.
301
+ */
36
302
  export const net: typeof t.net;
303
+
304
+ /**
305
+ * Process-level information (PID, uptime, memory usage).
306
+ *
307
+ * Re-exported from the `t` global for module-style imports.
308
+ * @see {@link TitanCore.Process} for full documentation.
309
+ */
37
310
  export const proc: typeof t.proc;
38
311
 
312
+ /**
313
+ * Time utilities (sleep, timestamps, high-resolution clock).
314
+ *
315
+ * Re-exported from the `t` global for module-style imports.
316
+ * @see {@link TitanCore.Time} for full documentation.
317
+ */
39
318
  export const time: typeof t.time;
319
+
320
+ /**
321
+ * URL parsing and formatting utilities.
322
+ *
323
+ * Re-exported from the `t` global for module-style imports.
324
+ * @see {@link TitanCore.URLModule} for full documentation.
325
+ */
40
326
  export const url: typeof t.url;
327
+
328
+ /**
329
+ * HTTP response builder for controlling status codes, headers, and content types.
330
+ *
331
+ * Re-exported from the `t` global for module-style imports.
332
+ * @see {@link TitanCore.ResponseModule} for full documentation.
333
+ */
41
334
  export const response: typeof t.response;
42
- export const valid: any;
43
335
 
44
- // -- Global Definitions (Runtime Environment) --
45
-
46
- /**
47
- * # Drift - Orchestration Engine
48
- *
49
- * Revolutionary system for high-performance asynchronous operations using a **Deterministic Replay-based Suspension** model.
50
- *
51
- * ## Mechanism
52
- * Drift utilizes a suspension model similar to **Algebraic Effects**. When a `drift()` operation is encountered,
53
- * the runtime suspends the isolate, offloads the task to the background Tokio executor, and frees the isolate
54
- * to handle other requests. Upon completion, the code is efficiently **re-played** with the result injected.
55
- *
56
- * @param promise - The promise or expression to drift.
57
- * @returns The resolved value of the input promise.
58
- *
59
- * @example
60
- * ```javascript
61
- * const resp = drift t.fetch("http://api.titan.com");
62
- * ```
336
+ /**
337
+ * Runtime validation utilities.
338
+ *
339
+ * Provides schema-based validation for request data. Works with
340
+ * the `@titanpl/valid` package for advanced validation rules.
341
+ *
342
+ * @see https://titan-docs-ez.vercel.app/docs/12-sdk — TitanPl SDK
63
343
  */
344
+ export const valid: any;
345
+
346
+
347
+ // ---------------------------------------------------------------------------
348
+ // Global Definitions — Runtime Environment
349
+ // ---------------------------------------------------------------------------
64
350
 
65
351
  declare global {
352
+
353
+ // -----------------------------------------------------------------------
354
+ // Drift — Asynchronous Orchestration Engine
355
+ // -----------------------------------------------------------------------
356
+
66
357
  /**
67
- * Titan Global Drift
358
+ * # Drift — Deterministic Replay-based Suspension Engine
359
+ *
360
+ * `drift` is Titan's revolutionary mechanism for handling asynchronous
361
+ * operations inside the **strictly synchronous Gravity V8 runtime**.
362
+ *
363
+ * ## How it works
364
+ *
365
+ * When the runtime encounters a `drift()` call:
366
+ *
367
+ * 1. **Suspend** — The current V8 isolate is suspended (not blocked).
368
+ * 2. **Offload** — The async task is dispatched to Rust's Tokio executor.
369
+ * 3. **Free** — The isolate is released to handle other incoming requests.
370
+ * 4. **Replay** — Once the task completes, the action code is **re-played**
371
+ * from the beginning with the resolved value injected deterministically.
372
+ *
373
+ * This model is conceptually similar to **Algebraic Effects** — your code
374
+ * reads as synchronous while the runtime handles concurrency under the hood.
375
+ *
376
+ * ## Important notes
377
+ *
378
+ * - `drift` is the **only** way to await promises in Titan actions.
379
+ * - The action function may be re-executed (replayed) — avoid side effects
380
+ * before the `drift` call that shouldn't be repeated.
381
+ * - Can be used with any Titan API that returns a `Promise` (e.g.,
382
+ * `t.fetch`, `t.db.connect`, `t.password.hash`, `t.fs.readFile`, etc.).
383
+ *
384
+ * @typeParam T - The resolved type of the promise.
385
+ * @param promise - The promise or expression to drift (suspend and resolve).
386
+ * @returns The synchronously resolved value of the input promise.
387
+ *
388
+ * @example
389
+ * ```js
390
+ * // Basic fetch with drift
391
+ * export function getExternalData(req) {
392
+ * const resp = drift(t.fetch("https://api.example.com/data"));
393
+ * return { ok: resp.ok, data: JSON.parse(resp.body) };
394
+ * }
395
+ * ```
396
+ *
397
+ * @example
398
+ * ```js
399
+ * // Multiple drift calls (sequential)
400
+ * export function processOrder(req) {
401
+ * const user = drift(t.fetch("https://api.example.com/user/1"));
402
+ * const order = drift(t.fetch("https://api.example.com/order/99"));
403
+ * return { user: JSON.parse(user.body), order: JSON.parse(order.body) };
404
+ * }
405
+ * ```
406
+ *
407
+ * @example
408
+ * ```js
409
+ * // Drift with database operations
410
+ * export function getUsers(req) {
411
+ * const conn = drift(t.db.connect(process.env.DATABASE_URL));
412
+ * const users = drift(conn.query("SELECT * FROM users LIMIT 10"));
413
+ * return { users };
414
+ * }
415
+ * ```
416
+ *
417
+ * @see https://titan-docs-ez.vercel.app/docs/14-drift — Drift documentation
418
+ * @see https://titan-docs-ez.vercel.app/docs/runtime-architecture — Gravity Runtime
68
419
  */
69
420
  var drift: <T>(promise: Promise<T> | T) => T;
70
421
 
71
422
 
423
+ // -----------------------------------------------------------------------
424
+ // Database Connection Interface
425
+ // -----------------------------------------------------------------------
72
426
 
427
+ /**
428
+ * Represents an active database connection returned by `t.db.connect()`.
429
+ *
430
+ * Provides a single `query()` method for executing SQL statements with
431
+ * optional parameterized values to prevent SQL injection.
432
+ *
433
+ * @example
434
+ * ```js
435
+ * export function listUsers(req) {
436
+ * const conn = drift(t.db.connect(process.env.DATABASE_URL));
437
+ *
438
+ * // Simple query
439
+ * const all = drift(conn.query("SELECT * FROM users"));
440
+ *
441
+ * // Parameterized query (safe from SQL injection)
442
+ * const one = drift(conn.query(
443
+ * "SELECT * FROM users WHERE id = $1",
444
+ * [req.params.id]
445
+ * ));
446
+ *
447
+ * return { all, user: one[0] };
448
+ * }
449
+ * ```
450
+ *
451
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs
452
+ */
73
453
  interface DbConnection {
74
- query(sql: string, params?: any[]): any[];
454
+ /**
455
+ * Execute a SQL query against the connected database.
456
+ *
457
+ * Supports parameterized queries using positional placeholders (`$1`, `$2`, etc.)
458
+ * to prevent SQL injection attacks.
459
+ *
460
+ * @param sql - The SQL query string. Use `$1`, `$2`, ... for parameter placeholders.
461
+ * @param params - Optional array of values to bind to the query placeholders (in order).
462
+ * @returns A promise that resolves to an array of result rows (as plain objects).
463
+ *
464
+ * @example
465
+ * ```js
466
+ * // SELECT with parameters
467
+ * const users = drift(conn.query(
468
+ * "SELECT * FROM users WHERE role = $1 AND active = $2",
469
+ * ["admin", true]
470
+ * ));
471
+ *
472
+ * // INSERT
473
+ * drift(conn.query(
474
+ * "INSERT INTO users (name, email) VALUES ($1, $2)",
475
+ * ["Alice", "alice@example.com"]
476
+ * ));
477
+ *
478
+ * // UPDATE
479
+ * drift(conn.query(
480
+ * "UPDATE users SET name = $1 WHERE id = $2",
481
+ * ["Bob", 42]
482
+ * ));
483
+ * ```
484
+ */
485
+ query(sql: string, params?: any[]): Promise<any[]>;
75
486
  }
76
487
 
488
+
489
+ // -----------------------------------------------------------------------
490
+ // Titan Runtime Utils — The `t` / `Titan` global object
491
+ // -----------------------------------------------------------------------
492
+
493
+ /**
494
+ * The Titan Runtime Utilities interface — the core API surface available
495
+ * globally as `t` (or `Titan`) in every action.
496
+ *
497
+ * All methods on `t` are powered by native Rust implementations under
498
+ * the hood, providing near-zero overhead and memory safety. Async methods
499
+ * must be consumed via the `drift()` operator.
500
+ *
501
+ * @example
502
+ * ```js
503
+ * // The `t` object is always available — no imports needed
504
+ * export function myAction(req) {
505
+ * t.log("Request received:", req.method, req.path);
506
+ * const resp = drift(t.fetch("https://api.example.com/data"));
507
+ * return { status: resp.status, body: JSON.parse(resp.body) };
508
+ * }
509
+ * ```
510
+ *
511
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Complete Runtime APIs reference
512
+ */
77
513
  interface TitanRuntimeUtils {
514
+
515
+ // -------------------------------------------------------------------
516
+ // Core I/O
517
+ // -------------------------------------------------------------------
518
+
519
+ /**
520
+ * Action-scoped, sandboxed logging utility.
521
+ *
522
+ * Writes messages to the Titan **Gravity Logs** system. Logs are
523
+ * prefixed with the action name for easy filtering and debugging.
524
+ * Accepts any number of arguments of any type (they are serialized
525
+ * automatically).
526
+ *
527
+ * Output in the terminal appears as:
528
+ * ```
529
+ * [Titan] log(myAction): your message here
530
+ * ```
531
+ *
532
+ * @param args - One or more values to log (strings, numbers, objects, etc.).
533
+ *
534
+ * @example
535
+ * ```js
536
+ * t.log("Processing user", req.params.id);
537
+ * t.log("Body received:", req.body);
538
+ * t.log("Multiple", "values", { are: "supported" }, 42);
539
+ * ```
540
+ *
541
+ * @see https://titan-docs-ez.vercel.app/docs/06-logs — Gravity Logs
542
+ */
78
543
  log(...args: any[]): void;
544
+
545
+ /**
546
+ * Synchronously reads the contents of a local file as a UTF-8 string.
547
+ *
548
+ * This is a **blocking, synchronous** operation — suitable for reading
549
+ * small configuration files, templates, or static assets at startup.
550
+ * For larger or async file operations, prefer `t.fs.readFile()` with `drift()`.
551
+ *
552
+ * @param path - Absolute or relative path to the file to read.
553
+ * @returns The file contents as a UTF-8 string.
554
+ * @throws If the file does not exist or cannot be read.
555
+ *
556
+ * @example
557
+ * ```js
558
+ * export function getConfig(req) {
559
+ * const raw = t.read("./config.json");
560
+ * return JSON.parse(raw);
561
+ * }
562
+ * ```
563
+ *
564
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs
565
+ */
79
566
  read(path: string): string;
567
+
568
+ /**
569
+ * Built-in Rust-powered HTTP client for making outbound requests.
570
+ *
571
+ * Powered by Rust's native HTTP stack — **not** `node-fetch` or any
572
+ * JS-based client. Provides high-performance, non-blocking HTTP calls.
573
+ *
574
+ * Returns a `Promise` — use with `drift()` to resolve it inside an action.
575
+ *
576
+ * @param url - The target URL to request (must include protocol, e.g. `"https://..."`).
577
+ * @param options - Optional request configuration.
578
+ * @param options.method - HTTP method. Defaults to `"GET"`.
579
+ * @param options.headers - Key-value map of request headers.
580
+ * @param options.body - Request body. Strings are sent as-is; objects are
581
+ * automatically JSON-serialized with `Content-Type: application/json`.
582
+ *
583
+ * @returns A promise resolving to a response object with:
584
+ * - `ok` — `true` if the status code is 2xx.
585
+ * - `status` — The HTTP status code (e.g., `200`, `404`, `500`).
586
+ * - `body` — The response body as a string (parse with `JSON.parse()` if needed).
587
+ * - `error` — An error message string if the request failed at the network level.
588
+ *
589
+ * @example
590
+ * ```js
591
+ * // Simple GET
592
+ * export function getData(req) {
593
+ * const resp = drift(t.fetch("https://api.example.com/items"));
594
+ * return JSON.parse(resp.body);
595
+ * }
596
+ * ```
597
+ *
598
+ * @example
599
+ * ```js
600
+ * // POST with JSON body and headers
601
+ * export function createItem(req) {
602
+ * const resp = drift(t.fetch("https://api.example.com/items", {
603
+ * method: "POST",
604
+ * headers: {
605
+ * "Authorization": "Bearer " + process.env.API_KEY,
606
+ * "Content-Type": "application/json"
607
+ * },
608
+ * body: { name: req.body.name, price: req.body.price }
609
+ * }));
610
+ *
611
+ * if (!resp.ok) return { error: "Failed", status: resp.status };
612
+ * return JSON.parse(resp.body);
613
+ * }
614
+ * ```
615
+ *
616
+ * @example
617
+ * ```js
618
+ * // Error handling
619
+ * export function safeFetch(req) {
620
+ * const resp = drift(t.fetch("https://unreliable-api.com/data"));
621
+ * if (resp.error) return { error: resp.error };
622
+ * if (!resp.ok) return { error: `HTTP ${resp.status}` };
623
+ * return JSON.parse(resp.body);
624
+ * }
625
+ * ```
626
+ *
627
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.fetch)
628
+ */
80
629
  fetch(url: string, options?: {
81
630
  method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
82
631
  headers?: Record<string, string>;
@@ -88,167 +637,1428 @@ declare global {
88
637
  error?: string;
89
638
  }>;
90
639
 
640
+
641
+ // -------------------------------------------------------------------
642
+ // Authentication & Security
643
+ // -------------------------------------------------------------------
644
+
645
+ /**
646
+ * JSON Web Token (JWT) utilities for stateless authentication.
647
+ *
648
+ * Provides `sign` and `verify` methods backed by Rust cryptographic
649
+ * implementations. Ideal for issuing access tokens and validating
650
+ * incoming Bearer tokens in API actions.
651
+ *
652
+ * > **Note:** Both methods are **synchronous** — no `drift()` needed.
653
+ *
654
+ * @example
655
+ * ```js
656
+ * // Sign a token
657
+ * export function login(req) {
658
+ * const { username, password } = req.body;
659
+ * // ... validate credentials ...
660
+ * const token = t.jwt.sign(
661
+ * { sub: userId, role: "admin" },
662
+ * process.env.JWT_SECRET,
663
+ * { expiresIn: "7d" }
664
+ * );
665
+ * return { token };
666
+ * }
667
+ *
668
+ * // Verify a token
669
+ * export function protectedAction(req) {
670
+ * const token = req.headers["authorization"]?.replace("Bearer ", "");
671
+ * try {
672
+ * const payload = t.jwt.verify(token, process.env.JWT_SECRET);
673
+ * return { userId: payload.sub, role: payload.role };
674
+ * } catch (e) {
675
+ * return t.response.json({ error: "Invalid token" }, 401);
676
+ * }
677
+ * }
678
+ * ```
679
+ *
680
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.jwt)
681
+ */
91
682
  jwt: {
683
+ /**
684
+ * Create a signed JWT from a payload object.
685
+ *
686
+ * @param payload - The data to encode in the token (e.g., `{ sub: "user123", role: "admin" }`).
687
+ * Avoid putting sensitive data here — JWTs are encoded, not encrypted.
688
+ * @param secret - The secret key used for HMAC signing. Store in environment variables.
689
+ * @param options - Optional signing options.
690
+ * @param options.expiresIn - Token expiration time.
691
+ * Accepts duration strings (`"1h"`, `"7d"`, `"30m"`) or
692
+ * a number representing seconds.
693
+ * @returns The signed JWT as a string (e.g., `"eyJhbGciOi..."`).
694
+ *
695
+ * @example
696
+ * ```js
697
+ * const token = t.jwt.sign({ userId: 1 }, "my-secret", { expiresIn: "24h" });
698
+ * ```
699
+ */
92
700
  sign(payload: object, secret: string, options?: { expiresIn?: string | number }): string;
701
+
702
+ /**
703
+ * Verify and decode a JWT, returning the original payload.
704
+ *
705
+ * @param token - The JWT string to verify.
706
+ * @param secret - The secret key used to verify the signature.
707
+ * @returns The decoded payload object if the token is valid and not expired.
708
+ * @throws If the token is invalid, expired, or the signature doesn't match.
709
+ *
710
+ * @example
711
+ * ```js
712
+ * try {
713
+ * const payload = t.jwt.verify(token, process.env.JWT_SECRET);
714
+ * t.log("User:", payload.sub);
715
+ * } catch (err) {
716
+ * t.log("Token verification failed");
717
+ * }
718
+ * ```
719
+ */
93
720
  verify(token: string, secret: string): any;
94
721
  };
95
722
 
723
+ /**
724
+ * Secure password hashing and verification powered by bcrypt (Rust implementation).
725
+ *
726
+ * Both methods return `Promise` values — use `drift()` to resolve them.
727
+ *
728
+ * @example
729
+ * ```js
730
+ * // Registration: hash the password before storing
731
+ * export function register(req) {
732
+ * const { email, password } = req.body;
733
+ * const hashed = drift(t.password.hash(password));
734
+ * // Store `hashed` in your database
735
+ * return { success: true, email };
736
+ * }
737
+ *
738
+ * // Login: compare submitted password against stored hash
739
+ * export function login(req) {
740
+ * const { email, password } = req.body;
741
+ * // Retrieve `storedHash` from your database
742
+ * const valid = drift(t.password.verify(password, storedHash));
743
+ * if (!valid) return t.response.json({ error: "Invalid credentials" }, 401);
744
+ * return { token: t.jwt.sign({ email }, process.env.JWT_SECRET) };
745
+ * }
746
+ * ```
747
+ *
748
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.password)
749
+ */
96
750
  password: {
97
- hash(password: string): string;
98
- verify(password: string, hash: string): boolean;
751
+ /**
752
+ * Hash a plain-text password using bcrypt.
753
+ *
754
+ * Automatically generates a secure salt. The resulting hash string
755
+ * includes the salt, making it safe to store directly in a database.
756
+ *
757
+ * @param password - The plain-text password to hash.
758
+ * @returns A promise resolving to the bcrypt hash string.
759
+ *
760
+ * @example
761
+ * ```js
762
+ * const hash = drift(t.password.hash("my-secure-password"));
763
+ * // hash → "$2b$12$LJ3m4ys..."
764
+ * ```
765
+ */
766
+ hash(password: string): Promise<string>;
767
+
768
+ /**
769
+ * Verify a plain-text password against a previously hashed value.
770
+ *
771
+ * @param password - The plain-text password to check.
772
+ * @param hash - The bcrypt hash string to compare against.
773
+ * @returns A promise resolving to `true` if the password matches, `false` otherwise.
774
+ *
775
+ * @example
776
+ * ```js
777
+ * const isValid = drift(t.password.verify("my-password", storedHash));
778
+ * if (!isValid) return { error: "Wrong password" };
779
+ * ```
780
+ */
781
+ verify(password: string, hash: string): Promise<boolean>;
99
782
  };
100
783
 
101
- /** ### `db` (Database Connection) */
784
+
785
+ // -------------------------------------------------------------------
786
+ // Database
787
+ // -------------------------------------------------------------------
788
+
789
+ /**
790
+ * Database connection interface.
791
+ *
792
+ * Establish connections to SQL databases (PostgreSQL, MySQL, SQLite, etc.)
793
+ * using a connection URL. Returns a `DbConnection` instance for executing queries.
794
+ *
795
+ * > **Important:** `connect()` returns a `Promise` — always wrap it with `drift()`.
796
+ *
797
+ * @example
798
+ * ```js
799
+ * export function getUsers(req) {
800
+ * const conn = drift(t.db.connect(process.env.DATABASE_URL));
801
+ * const users = drift(conn.query("SELECT id, name, email FROM users"));
802
+ * return { users };
803
+ * }
804
+ * ```
805
+ *
806
+ * @example
807
+ * ```js
808
+ * // Full CRUD example
809
+ * export function createUser(req) {
810
+ * const conn = drift(t.db.connect(process.env.DATABASE_URL));
811
+ * const { name, email } = req.body;
812
+ *
813
+ * drift(conn.query(
814
+ * "INSERT INTO users (name, email) VALUES ($1, $2)",
815
+ * [name, email]
816
+ * ));
817
+ *
818
+ * return { created: true, name, email };
819
+ * }
820
+ * ```
821
+ *
822
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.db)
823
+ */
102
824
  db: {
103
- connect(url: string): DbConnection;
825
+ /**
826
+ * Establish a database connection.
827
+ *
828
+ * @param url - A database connection string.
829
+ *
830
+ * Supported formats:
831
+ * - PostgreSQL: `"postgres://user:pass@host:5432/dbname"`
832
+ * - MySQL: `"mysql://user:pass@host:3306/dbname"`
833
+ * - SQLite: `"sqlite://./data.db"`
834
+ *
835
+ * @returns A promise resolving to a {@link DbConnection} instance.
836
+ *
837
+ * @example
838
+ * ```js
839
+ * const conn = drift(
840
+ * t.db.connect("postgres://admin:secret@localhost:5432/mydb")
841
+ * );
842
+ * ```
843
+ */
844
+ connect(url: string): Promise<DbConnection>;
845
+
846
+ /**
847
+ * Execute a SQL query using the default database connection.
848
+ *
849
+ * Uses the configured `DATABASE_URL` internally.
850
+ * Ideal for simple and one-off queries.
851
+ *
852
+ * @example
853
+ * ```js
854
+ * const users = drift(
855
+ * t.db.query("SELECT * FROM users")
856
+ * );
857
+ * ```
858
+ *
859
+ * @example
860
+ * ```js
861
+ * const user = drift(
862
+ * t.db.query(
863
+ * "SELECT * FROM users WHERE id = $1",
864
+ * [42]
865
+ * )
866
+ * );
867
+ * ```
868
+ *
869
+ * @example
870
+ * ```js
871
+ * const sql = drift(t.fs.readFile("./db/login.sql"));
872
+ * const rows = drift(t.db.query(sql, [email, hash]));
873
+ * ```
874
+ *
875
+ * @param sql - SQL query string.
876
+ * @param params - Optional positional parameters.
877
+ * @returns A promise resolving to query result rows.
878
+ */
879
+ query(sql: string, params?: any[]): Promise<any[]>;
104
880
  };
105
881
 
106
- /** ### `fs` (File System) */
882
+
883
+
884
+ // -------------------------------------------------------------------
885
+ // File System & Paths
886
+ // -------------------------------------------------------------------
887
+
888
+ /**
889
+ * Asynchronous file system operations.
890
+ *
891
+ * Provides async methods for reading, writing, and managing files and
892
+ * directories. All methods return `Promise` — use `drift()` to resolve.
893
+ *
894
+ * @see {@link TitanCore.FileSystem} for method signatures.
895
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.fs)
896
+ */
107
897
  fs: TitanCore.FileSystem;
108
898
 
109
- /** ### `path` (Path Manipulation) */
899
+ /**
900
+ * Path manipulation utilities.
901
+ *
902
+ * All methods are **synchronous** — no `drift()` needed. Provides
903
+ * cross-platform path joining, resolving, and component extraction.
904
+ *
905
+ * @see {@link TitanCore.Path} for method signatures.
906
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.path)
907
+ */
110
908
  path: TitanCore.Path;
111
909
 
112
- /** ### `crypto` (Cryptography) */
910
+
911
+ // -------------------------------------------------------------------
912
+ // Cryptography & Encoding
913
+ // -------------------------------------------------------------------
914
+
915
+ /**
916
+ * Cryptographic utilities powered by Rust's native crypto libraries.
917
+ *
918
+ * Includes hashing (SHA-256, SHA-512, MD5), HMAC, symmetric encryption/decryption,
919
+ * random bytes generation, and UUID creation. Async methods require `drift()`.
920
+ *
921
+ * @see {@link TitanCore.Crypto} for method signatures.
922
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.crypto)
923
+ */
113
924
  crypto: TitanCore.Crypto;
114
925
 
115
- /** ### `buffer` (Buffer Utilities) */
926
+ /**
927
+ * Buffer encoding and decoding utilities for Base64, Hex, and UTF-8 conversions.
928
+ *
929
+ * All methods are **synchronous** — no `drift()` needed.
930
+ *
931
+ * @see {@link TitanCore.BufferModule} for method signatures.
932
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.buffer)
933
+ */
116
934
  buffer: TitanCore.BufferModule;
117
935
 
118
- /** ### `ls` / `localStorage` (Persistent Storage) */
936
+
937
+ // -------------------------------------------------------------------
938
+ // Storage & State
939
+ // -------------------------------------------------------------------
940
+
941
+ /**
942
+ * Persistent key-value local storage (shorthand alias for `t.localStorage`).
943
+ *
944
+ * Data persists across requests and server restarts. All methods are
945
+ * **synchronous**. Useful for caching, feature flags, or small config values.
946
+ *
947
+ * @use Perfect for caching frequently accessed data and complex objects within a single process.
948
+ * @suggestion Use `setObject`/`getObject` for complex data structures to maintain types.
949
+
950
+ * @see {@link TitanCore.LocalStorage} for method signatures.
951
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.ls)
952
+ */
119
953
  ls: TitanCore.LocalStorage;
954
+
955
+ /**
956
+ * Persistent key-value local storage.
957
+ *
958
+ * Data persists across requests and server restarts. All methods are
959
+ * **synchronous**. Identical to `t.ls` — use whichever alias you prefer.
960
+ *
961
+ * @see {@link TitanCore.LocalStorage} for method signatures.
962
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.localStorage)
963
+ */
120
964
  localStorage: TitanCore.LocalStorage;
121
965
 
122
- /** ### `session` (Server-side Sessions) */
966
+ /**
967
+ * Server-side session management.
968
+ *
969
+ * Store and retrieve data by session ID. Sessions are scoped per client
970
+ * and useful for tracking authentication state, user preferences, or
971
+ * multi-step form data.
972
+ *
973
+ * All methods are **synchronous**.
974
+ *
975
+ * @see {@link TitanCore.Session} for method signatures.
976
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.session)
977
+ */
123
978
  session: TitanCore.Session;
124
979
 
125
- /** ### `cookies` (HTTP Cookies) */
980
+ /**
981
+ * HTTP cookie utilities for reading, setting, and deleting cookies.
982
+ *
983
+ * @see {@link TitanCore.Cookies} for method signatures.
984
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.cookies)
985
+ */
126
986
  cookies: TitanCore.Cookies;
127
987
 
128
- /** ### `os` (Operating System) */
988
+
989
+ // -------------------------------------------------------------------
990
+ // System & Network
991
+ // -------------------------------------------------------------------
992
+
993
+ /**
994
+ * Operating system information.
995
+ *
996
+ * Retrieve platform details, CPU count, and memory statistics of the
997
+ * host machine running the Titan server.
998
+ *
999
+ * @see {@link TitanCore.OS} for method signatures.
1000
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.os)
1001
+ */
129
1002
  os: TitanCore.OS;
130
1003
 
131
- /** ### `net` (Network) */
1004
+ /**
1005
+ * Network utilities for DNS resolution, IP lookup, and host pinging.
1006
+ *
1007
+ * All methods return `Promise` — use `drift()` to resolve.
1008
+ *
1009
+ * @see {@link TitanCore.Net} for method signatures.
1010
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.net)
1011
+ */
132
1012
  net: TitanCore.Net;
133
1013
 
134
- /** ### `proc` (Process) */
1014
+ /**
1015
+ * Process-level information for the running Titan server binary.
1016
+ *
1017
+ * All methods are **synchronous**.
1018
+ *
1019
+ * @see {@link TitanCore.Process} for method signatures.
1020
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.proc)
1021
+ */
135
1022
  proc: TitanCore.Process;
136
1023
 
137
- /** ### `time` (Time) */
1024
+
1025
+ // -------------------------------------------------------------------
1026
+ // Utilities
1027
+ // -------------------------------------------------------------------
1028
+
1029
+ /**
1030
+ * Time-related utilities including sleep, timestamps, and high-resolution clock.
1031
+ *
1032
+ * `t.time.sleep()` is async (requires `drift()`); other methods are synchronous.
1033
+ *
1034
+ * @see {@link TitanCore.Time} for method signatures.
1035
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.time)
1036
+ */
138
1037
  time: TitanCore.Time;
139
1038
 
140
- /** ### `url` (URL) */
1039
+ /**
1040
+ * URL parsing and formatting utilities.
1041
+ *
1042
+ * @see {@link TitanCore.URLModule} for method signatures.
1043
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs (t.url)
1044
+ */
141
1045
  url: TitanCore.URLModule;
142
1046
 
143
- /** ### `response` (HTTP Response Builder) */
1047
+ /**
1048
+
1049
+
1050
+ /**
1051
+ * HTTP response builder utilities.
1052
+ * @see https://www.npmjs.com/package/@titanpl/13-titan-core — TitanCore Valid Extension
1053
+ */
144
1054
  response: TitanCore.ResponseModule;
145
1055
 
1056
+
1057
+
1058
+ /**
1059
+ * Runtime validation utilities.
1060
+ *
1061
+ * Provides schema-based validation for request payloads and other data.
1062
+ * Works with the `@titanpl/valid` package for advanced rules.
1063
+ *
1064
+ * @see https://www.npmjs.com/package/@titanpl/valid — TitanPl Valid Extension
1065
+ */
146
1066
  valid: any;
1067
+
1068
+ /**
1069
+ * Extension index signature — allows access to dynamically loaded
1070
+ * Titan Extensions registered via `titan create ext`.
1071
+ *
1072
+ * Custom extensions attach their methods to the `t` object at runtime,
1073
+ * making them available as `t.myExtension.someMethod()`.
1074
+ *
1075
+ * @see https://titan-docs-ez.vercel.app/docs/10-extensions — Extensions documentation
1076
+ */
147
1077
  [key: string]: any;
148
1078
  }
149
1079
 
1080
+ /**
1081
+ * The primary global Titan runtime object.
1082
+ *
1083
+ * Available in every action without imports. Provides access to all
1084
+ * built-in Titan APIs: HTTP client, logging, JWT, database, file system,
1085
+ * crypto, storage, sessions, cookies, OS info, networking, and more.
1086
+ *
1087
+ * @example
1088
+ * ```js
1089
+ * export function myAction(req) {
1090
+ * t.log("Hello from Titan!");
1091
+ * return { message: "It works" };
1092
+ * }
1093
+ * ```
1094
+ *
1095
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Full API reference
1096
+ * @see https://titan-docs-ez.vercel.app/docs/13-titan-core — TitanCore Runtime APIs
1097
+ */
150
1098
  const t: TitanRuntimeUtils;
1099
+
1100
+ /**
1101
+ * Alias for the `t` global runtime object.
1102
+ *
1103
+ * `Titan` and `t` are interchangeable — use whichever you prefer.
1104
+ * Both reference the exact same runtime utilities instance.
1105
+ *
1106
+ * @example
1107
+ * ```js
1108
+ * export function myAction(req) {
1109
+ * Titan.log("Using the Titan alias");
1110
+ * const resp = drift(Titan.fetch("https://api.example.com"));
1111
+ * return JSON.parse(resp.body);
1112
+ * }
1113
+ * ```
1114
+ */
151
1115
  const Titan: TitanRuntimeUtils;
152
1116
 
1117
+
1118
+ // -----------------------------------------------------------------------
1119
+ // TitanCore Namespace — Detailed Sub-module Interfaces
1120
+ // -----------------------------------------------------------------------
1121
+
153
1122
  namespace TitanCore {
1123
+ interface TitanResponse {
1124
+ readonly __titan_response: true;
1125
+ }
1126
+ /**
1127
+ * Asynchronous file system operations.
1128
+ *
1129
+ * All methods return `Promise` and must be used with `drift()`.
1130
+ *
1131
+ * @example
1132
+ * ```js
1133
+ * export function fileOps(req) {
1134
+ * // Check if a file exists
1135
+ * const exists = drift(t.fs.exists("./data/config.json"));
1136
+ *
1137
+ * // Read a file
1138
+ * const content = drift(t.fs.readFile("./data/config.json"));
1139
+ *
1140
+ * // Write a file
1141
+ * drift(t.fs.writeFile("./data/output.json", JSON.stringify({ ok: true })));
1142
+ *
1143
+ * // Create a directory
1144
+ * drift(t.fs.mkdir("./data/backups"));
1145
+ *
1146
+ * // List directory contents
1147
+ * const files = drift(t.fs.readdir("./data"));
1148
+ *
1149
+ * // Get file metadata
1150
+ * const info = drift(t.fs.stat("./data/config.json"));
1151
+ * t.log("Size:", info.size, "Is file:", info.isFile);
1152
+ *
1153
+ * // Delete a file
1154
+ * drift(t.fs.remove("./data/temp.txt"));
1155
+ *
1156
+ * return { exists, files, info };
1157
+ * }
1158
+ * ```
1159
+ *
1160
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.fs)
1161
+ */
154
1162
  interface FileSystem {
155
- readFile(path: string): string;
156
- writeFile(path: string, content: string): void;
157
- readdir(path: string): string[];
158
- mkdir(path: string): void;
159
- exists(path: string): boolean;
160
- stat(path: string): { size: number, isFile: boolean, isDir: boolean, modified: number };
161
- remove(path: string): void;
1163
+ /**
1164
+ * Read the entire contents of a file as a UTF-8 string.
1165
+ *
1166
+ * @param path - Path to the file to read.
1167
+ * @returns A promise resolving to the file contents.
1168
+ * @throws If the file does not exist or cannot be read.
1169
+ */
1170
+ readFile(path: string): Promise<string>;
1171
+
1172
+ /**
1173
+ * Write a string to a file, creating or overwriting it.
1174
+ *
1175
+ * @param path - Path to the file to write.
1176
+ * @param content - The string content to write.
1177
+ * @returns A promise that resolves when writing is complete.
1178
+ */
1179
+ writeFile(path: string, content: string): Promise<void>;
1180
+
1181
+ /**
1182
+ * List the names of all entries in a directory.
1183
+ *
1184
+ * @param path - Path to the directory.
1185
+ * @returns A promise resolving to an array of file/directory names.
1186
+ */
1187
+ readdir(path: string): Promise<string[]>;
1188
+
1189
+ /**
1190
+ * Create a directory (and parent directories if needed).
1191
+ *
1192
+ * @param path - Path of the directory to create.
1193
+ * @returns A promise that resolves when the directory is created.
1194
+ */
1195
+ mkdir(path: string): Promise<void>;
1196
+
1197
+ /**
1198
+ * Check whether a file or directory exists at the given path.
1199
+ *
1200
+ * @param path - Path to check.
1201
+ * @returns A promise resolving to `true` if the path exists, `false` otherwise.
1202
+ */
1203
+ exists(path: string): Promise<boolean>;
1204
+
1205
+ /**
1206
+ * Get metadata about a file or directory.
1207
+ *
1208
+ * @param path - Path to the file or directory.
1209
+ * @returns A promise resolving to a stat object with:
1210
+ * - `size` — File size in bytes.
1211
+ * - `isFile` — `true` if the path is a regular file.
1212
+ * - `isDir` — `true` if the path is a directory.
1213
+ * - `modified` — Last modification time as a Unix timestamp (ms).
1214
+ */
1215
+ stat(path: string): Promise<{
1216
+ size: number;
1217
+ isFile: boolean;
1218
+ isDir: boolean;
1219
+ modified: number;
1220
+ }>;
1221
+
1222
+ /**
1223
+ * Delete a file or directory.
1224
+ *
1225
+ * @param path - Path to the file or directory to remove.
1226
+ * @returns A promise that resolves when the removal is complete.
1227
+ * @throws If the path does not exist.
1228
+ */
1229
+ remove(path: string): Promise<void>;
162
1230
  }
163
1231
 
1232
+ /**
1233
+ * Cross-platform path manipulation utilities.
1234
+ *
1235
+ * All methods are **synchronous** — no `drift()` needed.
1236
+ *
1237
+ * @example
1238
+ * ```js
1239
+ * const full = t.path.join("data", "users", "profile.json");
1240
+ * // → "data/users/profile.json"
1241
+ *
1242
+ * const abs = t.path.resolve("./config.json");
1243
+ * // → "/app/config.json"
1244
+ *
1245
+ * t.path.extname("photo.png"); // → ".png"
1246
+ * t.path.dirname("/a/b/c.txt"); // → "/a/b"
1247
+ * t.path.basename("/a/b/c.txt"); // → "c.txt"
1248
+ * ```
1249
+ *
1250
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.path)
1251
+ */
164
1252
  interface Path {
1253
+ /**
1254
+ * Join multiple path segments into a single normalized path.
1255
+ *
1256
+ * @param args - Two or more path segments to join.
1257
+ * @returns The joined and normalized path string.
1258
+ *
1259
+ * @example
1260
+ * ```js
1261
+ * t.path.join("data", "users", "profile.json");
1262
+ * // → "data/users/profile.json"
1263
+ * ```
1264
+ */
165
1265
  join(...args: string[]): string;
1266
+
1267
+ /**
1268
+ * Resolve a sequence of paths into an absolute path.
1269
+ *
1270
+ * @param args - Path segments. Relative segments are resolved against the working directory.
1271
+ * @returns The resolved absolute path string.
1272
+ *
1273
+ * @example
1274
+ * ```js
1275
+ * t.path.resolve("./config.json");
1276
+ * // → "/app/config.json"
1277
+ * ```
1278
+ */
166
1279
  resolve(...args: string[]): string;
1280
+
1281
+ /**
1282
+ * Get the file extension (including the leading dot).
1283
+ *
1284
+ * @param path - The file path.
1285
+ * @returns The extension string (e.g., `".json"`, `".png"`), or `""` if none.
1286
+ */
167
1287
  extname(path: string): string;
1288
+
1289
+ /**
1290
+ * Get the directory portion of a path.
1291
+ *
1292
+ * @param path - The file path.
1293
+ * @returns The directory path (e.g., `"/a/b"` from `"/a/b/c.txt"`).
1294
+ */
168
1295
  dirname(path: string): string;
1296
+
1297
+ /**
1298
+ * Get the last segment (filename) of a path.
1299
+ *
1300
+ * @param path - The file path.
1301
+ * @returns The filename (e.g., `"c.txt"` from `"/a/b/c.txt"`).
1302
+ */
169
1303
  basename(path: string): string;
170
1304
  }
171
1305
 
1306
+ /**
1307
+ * Cryptographic operations powered by Rust's native crypto libraries.
1308
+ *
1309
+ * Includes hashing, HMAC, symmetric encryption/decryption, random bytes,
1310
+ * UUID generation, and constant-time comparison.
1311
+ *
1312
+ * Async methods (`hash`, `encrypt`, `decrypt`, `hashKeyed`) require `drift()`.
1313
+ * Sync methods (`randomBytes`, `uuid`, `compare`) do not.
1314
+ *
1315
+ * @example
1316
+ * ```js
1317
+ * export function cryptoDemo(req) {
1318
+ * // Hash a string
1319
+ * const sha = drift(t.crypto.hash("sha256", "hello world"));
1320
+ *
1321
+ * // Generate a UUID
1322
+ * const id = t.crypto.uuid();
1323
+ *
1324
+ * // Random bytes (hex-encoded)
1325
+ * const rand = t.crypto.randomBytes(32);
1326
+ *
1327
+ * // HMAC signing
1328
+ * const sig = drift(t.crypto.hashKeyed("hmac-sha256", "secret", "message"));
1329
+ *
1330
+ * // Encrypt / Decrypt
1331
+ * const encrypted = drift(t.crypto.encrypt("aes-256-gcm", "my-key", "secret data"));
1332
+ * const decrypted = drift(t.crypto.decrypt("aes-256-gcm", "my-key", encrypted));
1333
+ *
1334
+ * return { sha, id, rand, sig, decrypted };
1335
+ * }
1336
+ * ```
1337
+ *
1338
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.crypto)
1339
+ */
172
1340
  interface Crypto {
173
- hash(algorithm: 'sha256' | 'sha512' | 'md5', data: string): string;
1341
+ /**
1342
+ * Compute a cryptographic hash of the input data.
1343
+ *
1344
+ * @param algorithm - The hash algorithm: `"sha256"`, `"sha512"`, or `"md5"`.
1345
+ * @param data - The string to hash.
1346
+ * @returns A promise resolving to the hex-encoded hash string.
1347
+ *
1348
+ * @example
1349
+ * ```js
1350
+ * const hash = drift(t.crypto.hash("sha256", "hello"));
1351
+ * // → "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1352
+ * ```
1353
+ */
1354
+ hash(algorithm: 'sha256' | 'sha512' | 'md5', data: string): Promise<string>;
1355
+
1356
+ /**
1357
+ * Generate cryptographically secure random bytes as a hex string.
1358
+ *
1359
+ * This is a **synchronous** operation — no `drift()` needed.
1360
+ *
1361
+ * @param size - Number of random bytes to generate.
1362
+ * @returns A hex-encoded string of `size` random bytes (length = `size * 2`).
1363
+ *
1364
+ * @example
1365
+ * ```js
1366
+ * const secret = t.crypto.randomBytes(32);
1367
+ * // → "a1b2c3d4e5f6..." (64 hex chars)
1368
+ * ```
1369
+ */
174
1370
  randomBytes(size: number): string;
1371
+
1372
+ /**
1373
+ * Generate a random UUID v4 string.
1374
+ *
1375
+ * This is a **synchronous** operation — no `drift()` needed.
1376
+ *
1377
+ * @returns A UUID v4 string (e.g., `"550e8400-e29b-41d4-a716-446655440000"`).
1378
+ *
1379
+ * @example
1380
+ * ```js
1381
+ * const id = t.crypto.uuid();
1382
+ * // → "f47ac10b-58cc-4372-a567-0e02b2c3d479"
1383
+ * ```
1384
+ */
175
1385
  uuid(): string;
1386
+
1387
+ /**
1388
+ * Perform a constant-time string comparison to prevent timing attacks.
1389
+ *
1390
+ * This is a **synchronous** operation — no `drift()` needed.
1391
+ *
1392
+ * @param hash - The first string (typically a hash or token).
1393
+ * @param target - The second string to compare against.
1394
+ * @returns `true` if the strings are identical, `false` otherwise.
1395
+ *
1396
+ * @example
1397
+ * ```js
1398
+ * const isMatch = t.crypto.compare(computedHash, expectedHash);
1399
+ * ```
1400
+ */
176
1401
  compare(hash: string, target: string): boolean;
177
- encrypt(algorithm: string, key: string, plaintext: string): string;
178
- decrypt(algorithm: string, key: string, ciphertext: string): string;
179
- hashKeyed(algorithm: 'hmac-sha256' | 'hmac-sha512', key: string, message: string): string;
1402
+
1403
+ /**
1404
+ * Encrypt data using a symmetric encryption algorithm.
1405
+ *
1406
+ * @param algorithm - The encryption algorithm (e.g., `"aes-256-gcm"`).
1407
+ * @param key - The encryption key string.
1408
+ * @param plaintext - The data to encrypt.
1409
+ * @returns A promise resolving to the encrypted ciphertext string.
1410
+ *
1411
+ * @example
1412
+ * ```js
1413
+ * const encrypted = drift(t.crypto.encrypt("aes-256-gcm", myKey, "secret data"));
1414
+ * ```
1415
+ */
1416
+ encrypt(algorithm: string, key: string, plaintext: string): Promise<string>;
1417
+
1418
+ /**
1419
+ * Decrypt data previously encrypted with `t.crypto.encrypt()`.
1420
+ *
1421
+ * @param algorithm - The same algorithm used for encryption.
1422
+ * @param key - The same key used for encryption.
1423
+ * @param ciphertext - The encrypted string to decrypt.
1424
+ * @returns A promise resolving to the original plaintext string.
1425
+ *
1426
+ * @example
1427
+ * ```js
1428
+ * const plaintext = drift(t.crypto.decrypt("aes-256-gcm", myKey, encrypted));
1429
+ * ```
1430
+ */
1431
+ decrypt(algorithm: string, key: string, ciphertext: string): Promise<string>;
1432
+
1433
+ /**
1434
+ * Compute an HMAC (Hash-based Message Authentication Code).
1435
+ *
1436
+ * Useful for verifying message integrity and authenticity
1437
+ * (e.g., webhook signature validation).
1438
+ *
1439
+ * @param algorithm - The HMAC algorithm: `"hmac-sha256"` or `"hmac-sha512"`.
1440
+ * @param key - The secret key for the HMAC.
1441
+ * @param message - The message to authenticate.
1442
+ * @returns A promise resolving to the hex-encoded HMAC string.
1443
+ *
1444
+ * @example
1445
+ * ```js
1446
+ * // Verify a webhook signature
1447
+ * export function webhook(req) {
1448
+ * const signature = req.headers["x-signature"];
1449
+ * const computed = drift(t.crypto.hashKeyed(
1450
+ * "hmac-sha256",
1451
+ * process.env.WEBHOOK_SECRET,
1452
+ * JSON.stringify(req.body)
1453
+ * ));
1454
+ * if (!t.crypto.compare(computed, signature)) {
1455
+ * return t.response.json({ error: "Invalid signature" }, 401);
1456
+ * }
1457
+ * return { verified: true };
1458
+ * }
1459
+ * ```
1460
+ */
1461
+ hashKeyed(algorithm: 'hmac-sha256' | 'hmac-sha512', key: string, message: string): Promise<string>;
180
1462
  }
181
1463
 
1464
+ /**
1465
+ * Buffer encoding and decoding utilities.
1466
+ *
1467
+ * Convert between `string`, `Uint8Array`, Base64, Hex, and UTF-8
1468
+ * representations. All methods are **synchronous** — no `drift()` needed.
1469
+ *
1470
+ * @example
1471
+ * ```js
1472
+ * // Base64 encode/decode
1473
+ * const encoded = t.buffer.toBase64("Hello, Titan!");
1474
+ * const decoded = t.buffer.toUtf8(t.buffer.fromBase64(encoded));
1475
+ *
1476
+ * // Hex encode/decode
1477
+ * const hex = t.buffer.toHex("Hello");
1478
+ * const bytes = t.buffer.fromHex(hex);
1479
+ * ```
1480
+ *
1481
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.buffer)
1482
+ */
182
1483
  interface BufferModule {
1484
+ /**
1485
+ * Decode a Base64-encoded string into a `Uint8Array`.
1486
+ *
1487
+ * @param str - The Base64-encoded string.
1488
+ * @returns The decoded byte array.
1489
+ */
183
1490
  fromBase64(str: string): Uint8Array;
1491
+
1492
+ /**
1493
+ * Encode bytes or a string to Base64.
1494
+ *
1495
+ * @param bytes - A `Uint8Array` or plain string to encode.
1496
+ * @returns The Base64-encoded string.
1497
+ */
184
1498
  toBase64(bytes: Uint8Array | string): string;
1499
+
1500
+ /**
1501
+ * Decode a hex-encoded string into a `Uint8Array`.
1502
+ *
1503
+ * @param str - The hex-encoded string (e.g., `"48656c6c6f"`).
1504
+ * @returns The decoded byte array.
1505
+ */
185
1506
  fromHex(str: string): Uint8Array;
1507
+
1508
+ /**
1509
+ * Encode bytes or a string to hexadecimal.
1510
+ *
1511
+ * @param bytes - A `Uint8Array` or plain string to encode.
1512
+ * @returns The hex-encoded string.
1513
+ */
186
1514
  toHex(bytes: Uint8Array | string): string;
1515
+
1516
+ /**
1517
+ * Encode a UTF-8 string into a `Uint8Array`.
1518
+ *
1519
+ * @param str - The string to encode.
1520
+ * @returns The UTF-8 encoded byte array.
1521
+ */
187
1522
  fromUtf8(str: string): Uint8Array;
1523
+
1524
+ /**
1525
+ * Decode a `Uint8Array` back into a UTF-8 string.
1526
+ *
1527
+ * @param bytes - The byte array to decode.
1528
+ * @returns The decoded UTF-8 string.
1529
+ */
188
1530
  toUtf8(bytes: Uint8Array): string;
189
1531
  }
190
1532
 
1533
+ /**
1534
+ * Persistent server-side key-value storage.
1535
+ *
1536
+ * Data persists across requests and server restarts. Accessible via
1537
+ * `t.ls` (shorthand) or `t.localStorage` (full name).
1538
+ *
1539
+ * Values are stored as strings — serialize complex objects with
1540
+ * `JSON.stringify()` and parse with `JSON.parse()`.
1541
+ *
1542
+ * All methods are **synchronous** — no `drift()` needed.
1543
+ *
1544
+ * @example
1545
+ * ```js
1546
+ * // Set and retrieve values
1547
+ * t.ls.set("app:version", "2.0.0");
1548
+ * const version = t.ls.get("app:version"); // → "2.0.0"
1549
+ *
1550
+ * // Store objects (serialize manually)
1551
+ * t.ls.set("config", JSON.stringify({ theme: "dark", lang: "en" }));
1552
+ * const config = JSON.parse(t.ls.get("config"));
1553
+ *
1554
+ * // List all keys
1555
+ * const allKeys = t.ls.keys(); // → ["app:version", "config"]
1556
+ *
1557
+ * // Delete a key
1558
+ * t.ls.remove("app:version");
1559
+ *
1560
+ * // Clear all stored data
1561
+ * t.ls.clear();
1562
+ * ```
1563
+ *
1564
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.ls / t.localStorage)
1565
+ */
191
1566
  interface LocalStorage {
1567
+ /**
1568
+ * Retrieve the value associated with a key.
1569
+ *
1570
+ * @param key - The storage key.
1571
+ * @returns The stored string value, or `null` if the key does not exist.
1572
+ */
192
1573
  get(key: string): string | null;
1574
+
1575
+ /**
1576
+ * Store a value under the given key (creates or overwrites).
1577
+ *
1578
+ * @param key - The storage key.
1579
+ * @param value - The string value to store.
1580
+ */
193
1581
  set(key: string, value: string): void;
1582
+
1583
+ /**
1584
+ * Delete a single key from storage.
1585
+ *
1586
+ * @param key - The key to remove. No error if the key doesn't exist.
1587
+ */
194
1588
  remove(key: string): void;
1589
+
1590
+ /**
1591
+ * Clear all keys and values from local storage.
1592
+ *
1593
+ * ⚠️ **Destructive** — removes everything. Use with caution.
1594
+ */
195
1595
  clear(): void;
1596
+
1597
+ /**
1598
+ * Get a list of all stored keys.
1599
+ *
1600
+ * @returns An array of all key names currently in storage.
1601
+ */
196
1602
  keys(): string[];
1603
+
1604
+ /** Stores a complex JavaScript object using V8 serialization and Base64 encoding. */
1605
+ setObject(key: string, value: any): void;
1606
+ /** Retrieves and deserializes a complex JavaScript object. Returns null if not found or invalid. */
1607
+ getObject<T = any>(key: string): T | null;
1608
+
1609
+ /**
1610
+ * Serialize a JavaScript value to a V8-compatible binary format.
1611
+ *
1612
+ * **Features:**
1613
+ * - Supports Map, Set, Date, RegExp, BigInt, TypedArray
1614
+ * - Supports Circular references
1615
+ * - ~50x faster than JSON.stringify
1616
+ *
1617
+ * @param value The value to serialize.
1618
+ */
1619
+ serialize(value: any): Uint8Array;
1620
+
1621
+ /**
1622
+ * Deserialize a V8-compatible binary format back to a JavaScript value.
1623
+ *
1624
+ * @param bytes The binary data to deserialize.
1625
+ */
1626
+ deserialize(bytes: Uint8Array): any;
1627
+
1628
+ /**
1629
+ * Register a class for hydration/serialization support.
1630
+ */
1631
+ register(ClassRef: Function, hydrateFn?: Function, typeName?: string): void;
1632
+
1633
+ /**
1634
+ * Hydrate a custom object from data.
1635
+ */
1636
+ hydrate(typeName: string, data: object): any;
197
1637
  }
198
1638
 
1639
+ /**
1640
+ * Server-side session management scoped by session ID.
1641
+ *
1642
+ * Sessions store ephemeral per-client data on the server. Each session
1643
+ * is identified by a unique `sessionId` (typically from a cookie or token).
1644
+ *
1645
+ * All methods are **synchronous** — no `drift()` needed.
1646
+ *
1647
+ * @example
1648
+ * ```js
1649
+ * export function setPreference(req) {
1650
+ * const sid = req.headers["x-session-id"];
1651
+ * t.session.set(sid, "theme", "dark");
1652
+ * t.session.set(sid, "lang", "en");
1653
+ * return { saved: true };
1654
+ * }
1655
+ *
1656
+ * export function getPreference(req) {
1657
+ * const sid = req.headers["x-session-id"];
1658
+ * const theme = t.session.get(sid, "theme");
1659
+ * return { theme };
1660
+ * }
1661
+ *
1662
+ * export function logout(req) {
1663
+ * const sid = req.headers["x-session-id"];
1664
+ * t.session.clear(sid); // Destroy entire session
1665
+ * return { loggedOut: true };
1666
+ * }
1667
+ * ```
1668
+ *
1669
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.session)
1670
+ */
199
1671
  interface Session {
1672
+ /**
1673
+ * Retrieve a value from a session.
1674
+ *
1675
+ * @param sessionId - The unique session identifier.
1676
+ * @param key - The key to look up within the session.
1677
+ * @returns The stored value, or `null` if not found.
1678
+ */
200
1679
  get(sessionId: string, key: string): string | null;
1680
+
1681
+ /**
1682
+ * Store a value in a session (creates or overwrites).
1683
+ *
1684
+ * @param sessionId - The unique session identifier.
1685
+ * @param key - The key to store under.
1686
+ * @param value - The string value to store.
1687
+ */
201
1688
  set(sessionId: string, key: string, value: string): void;
1689
+
1690
+ /**
1691
+ * Delete a single key from a session.
1692
+ *
1693
+ * @param sessionId - The unique session identifier.
1694
+ * @param key - The key to delete.
1695
+ */
202
1696
  delete(sessionId: string, key: string): void;
1697
+
1698
+ /**
1699
+ * Destroy an entire session, removing all its data.
1700
+ *
1701
+ * @param sessionId - The unique session identifier to clear.
1702
+ */
203
1703
  clear(sessionId: string): void;
204
1704
  }
205
1705
 
1706
+ /**
1707
+ * HTTP cookie management utilities.
1708
+ *
1709
+ * Read, set, and delete cookies from incoming requests and outgoing responses.
1710
+ *
1711
+ * @example
1712
+ * ```js
1713
+ * export function handleCookies(req) {
1714
+ * // Read a cookie from the request
1715
+ * const token = t.cookies.get(req, "auth_token");
1716
+ *
1717
+ * // Set a cookie (attach to response)
1718
+ * t.cookies.set(req, "visited", "true", {
1719
+ * httpOnly: true,
1720
+ * secure: true,
1721
+ * maxAge: 86400 // 1 day in seconds
1722
+ * });
1723
+ *
1724
+ * // Delete a cookie
1725
+ * t.cookies.delete(req, "old_cookie");
1726
+ *
1727
+ * return { hasToken: !!token };
1728
+ * }
1729
+ * ```
1730
+ *
1731
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.cookies)
1732
+ */
206
1733
  interface Cookies {
1734
+ /**
1735
+ * Read a cookie value from the request.
1736
+ *
1737
+ * @param req - The Titan request object (or response context).
1738
+ * @param name - The cookie name.
1739
+ * @returns The cookie value string, or `null` if the cookie is not present.
1740
+ */
207
1741
  get(req: any, name: string): string | null;
1742
+
1743
+ /**
1744
+ * Set a cookie on the response.
1745
+ *
1746
+ * @param res - The response context object.
1747
+ * @param name - The cookie name.
1748
+ * @param value - The cookie value.
1749
+ * @param options - Optional cookie attributes (e.g., `httpOnly`, `secure`, `maxAge`, `path`, `sameSite`).
1750
+ */
208
1751
  set(res: any, name: string, value: string, options?: any): void;
1752
+
1753
+ /**
1754
+ * Delete a cookie by setting its expiration in the past.
1755
+ *
1756
+ * @param res - The response context object.
1757
+ * @param name - The cookie name to delete.
1758
+ */
209
1759
  delete(res: any, name: string): void;
210
1760
  }
211
1761
 
1762
+ /**
1763
+ * Operating system information about the host running the Titan server.
1764
+ *
1765
+ * All methods are **synchronous** — no `drift()` needed.
1766
+ *
1767
+ * @example
1768
+ * ```js
1769
+ * export function serverInfo(req) {
1770
+ * return {
1771
+ * platform: t.os.platform(), // e.g., "linux"
1772
+ * cpus: t.os.cpus(), // e.g., 8
1773
+ * totalMemory: t.os.totalMemory(), // bytes
1774
+ * freeMemory: t.os.freeMemory(), // bytes
1775
+ * tmpdir: t.os.tmpdir() // e.g., "/tmp"
1776
+ * };
1777
+ * }
1778
+ * ```
1779
+ *
1780
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.os)
1781
+ */
212
1782
  interface OS {
1783
+ /**
1784
+ * Get the operating system platform identifier.
1785
+ *
1786
+ * @returns A string like `"linux"`, `"darwin"` (macOS), or `"win32"` (Windows).
1787
+ */
213
1788
  platform(): string;
1789
+
1790
+ /**
1791
+ * Get the number of logical CPU cores available.
1792
+ *
1793
+ * @returns The number of CPU cores.
1794
+ */
214
1795
  cpus(): number;
1796
+
1797
+ /**
1798
+ * Get the total system memory in bytes.
1799
+ *
1800
+ * @returns Total memory in bytes.
1801
+ */
215
1802
  totalMemory(): number;
1803
+
1804
+ /**
1805
+ * Get the currently available (free) system memory in bytes.
1806
+ *
1807
+ * @returns Free memory in bytes.
1808
+ */
216
1809
  freeMemory(): number;
1810
+
1811
+ /**
1812
+ * Get the path to the system's temporary directory.
1813
+ *
1814
+ * @returns The temporary directory path (e.g., `"/tmp"`).
1815
+ */
217
1816
  tmpdir(): string;
218
1817
  }
219
1818
 
1819
+ /**
1820
+ * Network utility functions.
1821
+ *
1822
+ * All methods return `Promise` — use `drift()` to resolve.
1823
+ *
1824
+ * @example
1825
+ * ```js
1826
+ * export function networkInfo(req) {
1827
+ * const ips = drift(t.net.resolveDNS("example.com"));
1828
+ * const myIp = drift(t.net.ip());
1829
+ * const reachable = drift(t.net.ping("8.8.8.8"));
1830
+ * return { ips, myIp, reachable };
1831
+ * }
1832
+ * ```
1833
+ *
1834
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.net)
1835
+ */
220
1836
  interface Net {
221
- resolveDNS(hostname: string): string[];
222
- ip(): string;
223
- ping(host: string): boolean;
1837
+ /**
1838
+ * Resolve a hostname to its IP addresses via DNS lookup.
1839
+ *
1840
+ * @param hostname - The domain to resolve (e.g., `"example.com"`).
1841
+ * @returns A promise resolving to an array of IP address strings.
1842
+ */
1843
+ resolveDNS(hostname: string): Promise<string[]>;
1844
+
1845
+ /**
1846
+ * Get the public IP address of the current server.
1847
+ *
1848
+ * @returns A promise resolving to the server's public IP string.
1849
+ */
1850
+ ip(): Promise<string>;
1851
+
1852
+ /**
1853
+ * Ping a host to check if it is reachable.
1854
+ *
1855
+ * @param host - The hostname or IP address to ping.
1856
+ * @returns A promise resolving to `true` if the host responds, `false` otherwise.
1857
+ */
1858
+ ping(host: string): Promise<boolean>;
224
1859
  }
225
1860
 
1861
+ /**
1862
+ * Process-level information about the running Titan server binary.
1863
+ *
1864
+ * All methods are **synchronous** — no `drift()` needed.
1865
+ *
1866
+ * @example
1867
+ * ```js
1868
+ * export function processInfo(req) {
1869
+ * return {
1870
+ * pid: t.proc.pid(), // e.g., 12345
1871
+ * uptime: t.proc.uptime(), // seconds since start
1872
+ * memory: t.proc.memory() // { rss, heapTotal, heapUsed, ... }
1873
+ * };
1874
+ * }
1875
+ * ```
1876
+ *
1877
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.proc)
1878
+ */
226
1879
  interface Process {
1880
+ /**
1881
+ * Get the process ID (PID) of the Titan server.
1882
+ *
1883
+ * @returns The numeric process ID.
1884
+ */
227
1885
  pid(): number;
1886
+
1887
+ /**
1888
+ * Get the server uptime in seconds since the process started.
1889
+ *
1890
+ * @returns Uptime in seconds.
1891
+ */
228
1892
  uptime(): number;
1893
+
1894
+ /**
1895
+ * Get memory usage statistics for the server process.
1896
+ *
1897
+ * @returns An object with memory metrics (e.g., `rss`, `heapTotal`, `heapUsed`).
1898
+ */
229
1899
  memory(): Record<string, any>;
230
1900
  }
231
1901
 
1902
+ /**
1903
+ * Time-related utilities.
1904
+ *
1905
+ * `sleep()` is async (requires `drift()`). `now()` and `timestamp()` are synchronous.
1906
+ *
1907
+ * @example
1908
+ * ```js
1909
+ * export function timeDemo(req) {
1910
+ * const start = t.time.now(); // High-resolution ms timestamp
1911
+ * drift(t.time.sleep(100)); // Wait 100ms
1912
+ * const elapsed = t.time.now() - start;
1913
+ * const iso = t.time.timestamp(); // "2026-01-15T12:30:45.123Z"
1914
+ * return { elapsed, iso };
1915
+ * }
1916
+ * ```
1917
+ *
1918
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.time)
1919
+ */
232
1920
  interface Time {
233
- sleep(ms: number): void;
1921
+ /**
1922
+ * Pause execution for the given number of milliseconds.
1923
+ *
1924
+ * Returns a `Promise` — use `drift()` to suspend the action without blocking
1925
+ * the entire server. Useful for rate limiting, retry delays, or testing.
1926
+ *
1927
+ * @param ms - Duration to sleep in milliseconds.
1928
+ * @returns A promise that resolves after the specified duration.
1929
+ *
1930
+ * @example
1931
+ * ```js
1932
+ * drift(t.time.sleep(500)); // Wait 500ms
1933
+ * ```
1934
+ */
1935
+ sleep(ms: number): Promise<void>;
1936
+
1937
+ /**
1938
+ * Get the current time as a high-resolution millisecond timestamp.
1939
+ *
1940
+ * This is a **synchronous** operation.
1941
+ *
1942
+ * @returns A numeric timestamp in milliseconds (similar to `Date.now()`).
1943
+ */
234
1944
  now(): number;
1945
+
1946
+ /**
1947
+ * Get the current time as an ISO 8601 formatted string.
1948
+ *
1949
+ * This is a **synchronous** operation.
1950
+ *
1951
+ * @returns An ISO timestamp string (e.g., `"2026-01-15T12:30:45.123Z"`).
1952
+ */
235
1953
  timestamp(): string;
236
1954
  }
237
1955
 
1956
+ /**
1957
+ * URL parsing and formatting utilities.
1958
+ *
1959
+ * @example
1960
+ * ```js
1961
+ * const parsed = t.url.parse("https://example.com/path?q=titan&page=1");
1962
+ * // → { protocol: "https:", host: "example.com", pathname: "/path", ... }
1963
+ *
1964
+ * const url = t.url.format({
1965
+ * protocol: "https:",
1966
+ * host: "api.example.com",
1967
+ * pathname: "/v2/users"
1968
+ * });
1969
+ * // → "https://api.example.com/v2/users"
1970
+ * ```
1971
+ *
1972
+ * @see https://titan-docs-ez.vercel.app/docs/04-runtime-apis — Runtime APIs (t.url)
1973
+ */
238
1974
  interface URLModule {
1975
+ /**
1976
+ * Parse a URL string into its component parts.
1977
+ *
1978
+ * @param url - The URL string to parse.
1979
+ * @returns An object with URL components (protocol, host, pathname, search, hash, etc.).
1980
+ */
239
1981
  parse(url: string): any;
1982
+
1983
+ /**
1984
+ * Format a URL object back into a URL string.
1985
+ *
1986
+ * @param urlObj - An object with URL components.
1987
+ * @returns The formatted URL string.
1988
+ */
240
1989
  format(urlObj: any): string;
1990
+
1991
+ /**
1992
+ * URL search parameters utility (similar to the Web API `URLSearchParams`).
1993
+ */
241
1994
  SearchParams: any;
242
1995
  }
243
1996
 
1997
+
1998
+
244
1999
  interface ResponseModule {
245
- (options: any): any;
246
- text(content: string, status?: number): any;
247
- html(content: string, status?: number): any;
248
- json(content: any, status?: number): any;
249
- redirect(url: string, status?: number): any;
250
- empty(status?: number): any;
2000
+
2001
+ /**
2002
+ * Return a JSON response.
2003
+ * Body is automatically JSON.stringify-ed.
2004
+ *
2005
+ * @example
2006
+ * ```js
2007
+ * return t.response.json({ ok: true });
2008
+ * ```
2009
+ */
2010
+ json(
2011
+ data: any,
2012
+ status?: number,
2013
+ extraHeaders?: Record<string, string>
2014
+ ): TitanResponse;
2015
+
2016
+ /**
2017
+ * Return a plain-text response.
2018
+ * Content-Type: text/plain
2019
+ *
2020
+ * @example
2021
+ * ```js
2022
+ * return t.response.text("Hello World");
2023
+ * ```
2024
+ */
2025
+ text(
2026
+ content: string,
2027
+ status?: number,
2028
+ extraHeaders?: Record<string, string>
2029
+ ): TitanResponse;
2030
+
2031
+ /**
2032
+ * Return an HTML response.
2033
+ * Content-Type: text/html
2034
+ *
2035
+ * @example
2036
+ * ```js
2037
+ * return t.response.html("<h1>Hello</h1>");
2038
+ * ```
2039
+ */
2040
+ html(
2041
+ content: string,
2042
+ status?: number,
2043
+ extraHeaders?: Record<string, string>
2044
+ ): TitanResponse;
2045
+
2046
+ /**
2047
+ * Return a redirect response.
2048
+ * Defaults to HTTP 302.
2049
+ *
2050
+ * @example
2051
+ * ```js
2052
+ * return t.response.redirect("/login");
2053
+ * ```
2054
+ */
2055
+ redirect(
2056
+ url: string,
2057
+ status?: number,
2058
+ extraHeaders?: Record<string, string>
2059
+ ): TitanResponse;
251
2060
  }
2061
+
252
2062
  }
253
2063
  }
254
2064