aipack 0.8.22

Command Agent runner to accelerate production coding with genai.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! Defines the `aip.uuid` module, used in the lua engine.
//!
//! ---
//!
//! ## Lua documentation
//!
//! The `aip.uuid` module exposes functions for generating various UUIDs and converting timestamped UUIDs.
//!
//! ### Functions
//!
//! - `aip.uuid.new(): string` - Generates a new UUID version 4. Alias for `new_v4`.
//! - `aip.uuid.new_v4(): string` - Generates a new UUID version 4.
//! - `aip.uuid.new_v7(): string` - Generates a new UUID version 7.
//! - `aip.uuid.new_v4_b64(): string` - Generates a new UUID version 4, standard Base64 encoded.
//! - `aip.uuid.new_v4_b64u(): string` - Generates a new UUID version 4, URL-safe Base64 encoded (no padding).
//! - `aip.uuid.new_v4_b58(): string` - Generates a new UUID version 4, Base58 encoded.
//! - `aip.uuid.new_v7_b64(): string` - Generates a new UUID version 7, standard Base64 encoded.
//! - `aip.uuid.new_v7_b64u(): string` - Generates a new UUID version 7, URL-safe Base64 encoded (no padding).
//! - `aip.uuid.new_v7_b58(): string` - Generates a new UUID version 7, Base58 encoded.
//! - `aip.uuid.to_time_epoch_ms(value: string | nil): integer | nil` - Converts a timestamped UUID string (V1, V6, V7) to milliseconds since Unix epoch. Returns `nil` if input is `nil`, not a valid UUID, or a UUID type without an extractable timestamp (e.g., V4).

use crate::runtime::Runtime;
use crate::script::support::into_option_string;
use mlua::{Lua, Table, Value};
use uuid::Uuid;

// region:    --- Lua Interface

/// Initializes the `uuid` Lua module.
///
/// Registers the UUID generation functions in the module table.
pub fn init_module(lua: &Lua, _runtime: &Runtime) -> crate::Result<Table> {
	let table = lua.create_table()?;

	table.set("new", lua.create_function(lua_new_v4)?)?;
	table.set("new_v4", lua.create_function(lua_new_v4)?)?;
	table.set("new_v7", lua.create_function(lua_new_v7)?)?;
	table.set("new_v4_b64", lua.create_function(lua_new_v4_b64)?)?;
	table.set("new_v4_b64u", lua.create_function(lua_new_v4_b64url_nopad)?)?;
	table.set("new_v4_b58", lua.create_function(lua_new_v4_b58)?)?;
	table.set("new_v7_b64", lua.create_function(lua_new_v7_b64)?)?;
	table.set("new_v7_b64u", lua.create_function(lua_new_v7_b64url_nopad)?)?;
	table.set("new_v7_b58", lua.create_function(lua_new_v7_b58)?)?;
	table.set("to_time_epoch_ms", lua.create_function(lua_to_time_epoch_ms)?)?;

	Ok(table)
}

// region:    --- Lua Functions

/// ## Lua Documentation aip.uuid.new
///
/// Generates a new UUID version 4. This is an alias for `aip.uuid.new_v4()`.
///
/// ```lua
/// -- API Signature
/// aip.uuid.new(): string
/// ```
///
/// ### Returns
///
/// `string`: The generated UUIDv4 as a string (e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479").
///
/// ### Example
///
/// ```lua
/// local id = aip.uuid.new()
/// print(id)
/// ```
///
/// ## Lua Documentation aip.uuid.new_v4
///
/// Generates a new UUID version 4.
///
/// ```lua
/// -- API Signature
/// aip.uuid.new_v4(): string
/// ```
///
/// ### Returns
///
/// `string`: The generated UUIDv4 as a string (e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479").
///
/// ### Example
///
/// ```lua
/// local id_v4 = aip.uuid.new_v4()
/// print(id_v4)
/// ```
fn lua_new_v4(_lua: &Lua, (): ()) -> mlua::Result<String> {
	Ok(uuid_extra::new_v4().to_string())
}

/// ## Lua Documentation aip.uuid.new_v7
///
/// Generates a new UUID version 7 (time-ordered).
///
/// ```lua
/// -- API Signature
/// aip.uuid.new_v7(): string
/// ```
///
/// ### Returns
///
/// `string`: The generated UUIDv7 as a string.
///
/// ### Example
///
/// ```lua
/// local id_v7 = aip.uuid.new_v7()
/// print(id_v7)
/// ```
fn lua_new_v7(_lua: &Lua, (): ()) -> mlua::Result<String> {
	Ok(uuid_extra::new_v7().to_string())
}

/// ## Lua Documentation aip.uuid.new_v4_b64
///
/// Generates a new UUID version 4 and encodes it using standard Base64.
///
/// ```lua
/// -- API Signature
/// aip.uuid.new_v4_b64(): string
/// ```
///
/// ### Returns
///
/// `string`: The Base64 encoded UUIDv4 string.
///
/// ### Example
///
/// ```lua
/// local id_v4_b64 = aip.uuid.new_v4_b64()
/// print(id_v4_b64)
/// ```
fn lua_new_v4_b64(_lua: &Lua, (): ()) -> mlua::Result<String> {
	Ok(uuid_extra::new_v4_b64())
}

/// ## Lua Documentation aip.uuid.new_v4_b64u
///
/// Generates a new UUID version 4 and encodes it using URL-safe Base64 without padding.
///
/// ```lua
/// -- API Signature
/// aip.uuid.new_v4_b64u(): string
/// ```
///
/// ### Returns
///
/// `string`: The URL-safe Base64 encoded (no padding) UUIDv4 string.
///
/// ### Example
///
/// ```lua
/// local id_v4_b64u = aip.uuid.new_v4_b64u()
/// print(id_v4_b64u)
/// ```
fn lua_new_v4_b64url_nopad(_lua: &Lua, (): ()) -> mlua::Result<String> {
	Ok(uuid_extra::new_v4_b64url_nopad())
}

/// ## Lua Documentation aip.uuid.new_v4_b58
///
/// Generates a new UUID version 4 and encodes it using Base58.
///
/// ```lua
/// -- API Signature
/// aip.uuid.new_v4_b58(): string
/// ```
///
/// ### Returns
///
/// `string`: The Base58 encoded UUIDv4 string.
///
/// ### Example
///
/// ```lua
/// local id_v4_b58 = aip.uuid.new_v4_b58()
/// print(id_v4_b58)
/// ```
fn lua_new_v4_b58(_lua: &Lua, (): ()) -> mlua::Result<String> {
	Ok(uuid_extra::new_v4_b58())
}

/// ## Lua Documentation aip.uuid.new_v7_b64
///
/// Generates a new UUID version 7 and encodes it using standard Base64.
///
/// ```lua
/// -- API Signature
/// aip.uuid.new_v7_b64(): string
/// ```
///
/// ### Returns
///
/// `string`: The Base64 encoded UUIDv7 string.
///
/// ### Example
///
/// ```lua
/// local id_v7_b64 = aip.uuid.new_v7_b64()
/// print(id_v7_b64)
/// ```
fn lua_new_v7_b64(_lua: &Lua, (): ()) -> mlua::Result<String> {
	Ok(uuid_extra::new_v7_b64())
}

/// ## Lua Documentation aip.uuid.new_v7_b64u
///
/// Generates a new UUID version 7 and encodes it using URL-safe Base64 without padding.
///
/// ```lua
/// -- API Signature
/// aip.uuid.new_v7_b64u(): string
/// ```
///
/// ### Returns
///
/// `string`: The URL-safe Base64 encoded (no padding) UUIDv7 string.
///
/// ### Example
///
/// ```lua
/// local id_v7_b64u = aip.uuid.new_v7_b64u()
/// print(id_v7_b64u)
/// ```
fn lua_new_v7_b64url_nopad(_lua: &Lua, (): ()) -> mlua::Result<String> {
	Ok(uuid_extra::new_v7_b64url_nopad())
}

/// ## Lua Documentation aip.uuid.new_v7_b58
///
/// Generates a new UUID version 7 and encodes it using Base58.
///
/// ```lua
/// -- API Signature
/// aip.uuid.new_v7_b58(): string
/// ```
///
/// ### Returns
///
/// `string`: The Base58 encoded UUIDv7 string.
///
/// ### Example
///
/// ```lua
/// local id_v7_b58 = aip.uuid.new_v7_b58()
/// print(id_v7_b58)
/// ```
fn lua_new_v7_b58(_lua: &Lua, (): ()) -> mlua::Result<String> {
	Ok(uuid_extra::new_v7_b58())
}

/// ## Lua Documentation aip.uuid.to_time_epoch_ms
///
/// Converts a timestamped UUID string (V1, V6, V7) to milliseconds since Unix epoch.
/// Returns `nil` if the input is `nil`, not a valid UUID string, or if the UUID type
/// does not contain an extractable timestamp (e.g., V4).
///
/// ```lua
/// -- API Signature
/// aip.uuid.to_time_epoch_ms(value: string | nil): integer | nil
/// ```
///
/// ### Arguments
///
/// - `value: string | nil`: The UUID string or `nil`.
///
/// ### Returns
///
/// `integer | nil`: Milliseconds since Unix epoch, or `nil`.
///
/// ### Example
///
/// ```lua
/// local v7_uuid_str = aip.uuid.new_v7()
/// local millis = aip.uuid.to_time_epoch_ms(v7_uuid_str)
/// if millis then
///   print("Timestamp in ms: " .. millis)
/// else
///   print("Could not extract timestamp.")
/// end
///
/// local v4_uuid_str = aip.uuid.new_v4()
/// local millis_v4 = aip.uuid.to_time_epoch_ms(v4_uuid_str)
/// -- millis_v4 will be nil
///
/// local invalid_millis = aip.uuid.to_time_epoch_ms("not-a-uuid")
/// -- invalid_millis will be nil
///
/// local nil_millis = aip.uuid.to_time_epoch_ms(nil)
/// -- nil_millis will be nil
/// ```
fn lua_to_time_epoch_ms(_lua: &Lua, value: Value) -> mlua::Result<Value> {
	let Some(uuid_str) = into_option_string(value, "aip.uuid.to_time_epoch_ms")? else {
		return Ok(Value::Nil);
	};

	match Uuid::parse_str(&uuid_str) {
		Ok(uuid) => {
			if let Some(timestamp) = uuid.get_timestamp() {
				let (secs, nanos) = timestamp.to_unix();
				let millis = (secs as i64 * 1000) + (nanos as i64 / 1_000_000);
				Ok(Value::Integer(millis))
			} else {
				// UUID does not have an extractable timestamp (e.g., V4)
				Ok(Value::Nil)
			}
		}
		Err(_) => {
			// Invalid UUID string
			Ok(Value::Nil)
		}
	}
}

// endregion: --- Lua Functions

// endregion: --- Lua Interface

// region:    --- Tests

#[cfg(test)]
mod tests {
	type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>; // For tests.

	use super::*;
	use crate::_test_support::{eval_lua, setup_lua};
	use uuid::Uuid;

	// region:    --- Support
	fn is_base64_url_chars(s: &str) -> bool {
		s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
	}

	fn is_base64_standard_chars(s: &str) -> bool {
		s.chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '=')
	}

	fn is_base58_chars(s: &str) -> bool {
		const BASE58_CHARS: &str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
		s.chars().all(|c| BASE58_CHARS.contains(c))
	}
	// endregion: --- Support

	#[tokio::test]
	async fn test_lua_aip_uuid_new_v4_simple() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;

		// -- Exec
		let res_new = eval_lua(&lua, "return aip.uuid.new()")?;
		let res_new_v4 = eval_lua(&lua, "return aip.uuid.new_v4()")?;

		// -- Check
		let uuid_str_new = res_new.as_str().ok_or("aip.uuid.new() should return a string")?;
		let parsed_uuid_new = Uuid::parse_str(uuid_str_new)?;
		assert_eq!(
			parsed_uuid_new.get_version_num(),
			4,
			"UUID from new() should be version 4"
		);

		let uuid_str_new_v4 = res_new_v4.as_str().ok_or("aip.uuid.new_v4() should return a string")?;
		let parsed_uuid_new_v4 = Uuid::parse_str(uuid_str_new_v4)?;
		assert_eq!(
			parsed_uuid_new_v4.get_version_num(),
			4,
			"UUID from new_v4() should be version 4"
		);

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_new_v7_simple() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;

		// -- Exec
		let res = eval_lua(&lua, "return aip.uuid.new_v7()")?;

		// -- Check
		let uuid_str = res.as_str().ok_or("Result should be a string")?;
		let parsed_uuid = Uuid::parse_str(uuid_str)?;
		assert_eq!(parsed_uuid.get_version_num(), 7, "UUID should be version 7");

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_new_v4_b64_simple() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;

		// -- Exec
		let res = eval_lua(&lua, "return aip.uuid.new_v4_b64()")?;

		// -- Check
		let b64_str = res.as_str().ok_or("Result should be a string")?;
		assert!(
			is_base64_standard_chars(b64_str),
			"String should contain only Base64 standard characters (possibly with padding)"
		);
		// Standard Base64 of 16 bytes is typically 24 chars if padded with '=='
		// or 22 if unpadded (not standard for this function, new_v4_b64u is for unpadded)
		assert!(
			(22..=24).contains(&b64_str.len()),
			"Base64 string length for UUIDv4 should be between 22 and 24. Got: {b64_str_len}",
			b64_str_len = b64_str.len()
		);

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_new_v4_b64u_simple() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;

		// -- Exec
		let res = eval_lua(&lua, "return aip.uuid.new_v4_b64u()")?;

		// -- Check
		let b64u_str = res.as_str().ok_or("Result should be a string")?;
		assert!(
			is_base64_url_chars(b64u_str),
			"String should contain only Base64 URL safe characters"
		);
		assert_eq!(
			b64u_str.len(),
			22,
			"Base64 URL (no pad) string length for UUID should be 22"
		);
		assert!(!b64u_str.contains('='), "String should not contain padding");

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_new_v4_b58_simple() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;

		// -- Exec
		let res = eval_lua(&lua, "return aip.uuid.new_v4_b58()")?;

		// -- Check
		let b58_str = res.as_str().ok_or("Result should be a string")?;
		assert!(is_base58_chars(b58_str), "String should contain only Base58 characters");
		// Base58 of 16 bytes is usually around 22 characters
		assert!(
			(21..=23).contains(&b58_str.len()),
			"Base58 string length for UUIDv4 should be around 21-23. Got: {b58_str_len}",
			b58_str_len = b58_str.len()
		);

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_new_v7_b64_simple() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;

		// -- Exec
		let res = eval_lua(&lua, "return aip.uuid.new_v7_b64()")?;

		// -- Check
		let b64_str = res.as_str().ok_or("Result should be a string")?;
		assert!(
			is_base64_standard_chars(b64_str),
			"String should contain only Base64 standard characters"
		);
		assert!(
			(22..=24).contains(&b64_str.len()),
			"Base64 string length for UUIDv7 should be between 22 and 24. Got: {b64_str_len}",
			b64_str_len = b64_str.len()
		);

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_new_v7_b64u_simple() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;

		// -- Exec
		let res = eval_lua(&lua, "return aip.uuid.new_v7_b64u()")?;

		// -- Check
		let b64u_str = res.as_str().ok_or("Result should be a string")?;
		assert!(
			is_base64_url_chars(b64u_str),
			"String should contain only Base64 URL safe characters"
		);
		assert_eq!(
			b64u_str.len(),
			22,
			"Base64 URL (no pad) string length for UUIDv7 should be 22"
		);
		assert!(!b64u_str.contains('='), "String should not contain padding");

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_new_v7_b58_simple() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;

		// -- Exec
		let res = eval_lua(&lua, "return aip.uuid.new_v7_b58()")?;

		// -- Check
		let b58_str = res.as_str().ok_or("Result should be a string")?;
		assert!(is_base58_chars(b58_str), "String should contain only Base58 characters");
		assert!(
			(21..=23).contains(&b58_str.len()),
			"Base58 string length for UUIDv7 should be around 21-23. Got: {b58_str_len}",
			b58_str_len = b58_str.len()
		);

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_to_time_epoch_ms_nil_input() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;
		let script = "return aip.uuid.to_time_epoch_ms(nil)";

		// -- Exec
		let result_val = eval_lua(&lua, script)?;

		// -- Check
		assert!(result_val.is_null(), "Expected nil for nil input");
		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_to_time_epoch_ms_invalid_uuid_string() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;
		let script = "return aip.uuid.to_time_epoch_ms('not-a-valid-uuid')";

		// -- Exec
		let result_val = eval_lua(&lua, script)?;

		// -- Check
		assert!(result_val.is_null(), "Expected nil for invalid UUID string");
		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_to_time_epoch_ms_v4_uuid() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;
		let v4_uuid_str = uuid_extra::new_v4().to_string();
		let script = format!("return aip.uuid.to_time_epoch_ms('{v4_uuid_str}')");

		// -- Exec
		let result_val = eval_lua(&lua, &script)?;

		// -- Check
		assert!(
			result_val.is_null(),
			"Expected nil for V4 UUID as it has no extractable timestamp"
		);
		Ok(())
	}

	#[tokio::test]
	async fn test_lua_aip_uuid_to_time_epoch_ms_v7_uuid() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(init_module, "uuid").await?;

		// Generate a V7 UUID and get its expected millisecond timestamp
		let v7_uuid = uuid_extra::new_v7(); // Uses current time
		let v7_uuid_str = v7_uuid.to_string();
		let ts_opt = v7_uuid.get_timestamp();
		let expected_millis = ts_opt
			.map(|ts| {
				let (secs, nanos) = ts.to_unix();
				(secs as i64 * 1000) + (nanos as i64 / 1_000_000)
			})
			.ok_or("Failed to get timestamp from generated V7 UUID")?;

		let script = format!("return aip.uuid.to_time_epoch_ms('{v7_uuid_str}')");

		// -- Exec
		let result_val = eval_lua(&lua, &script)?;

		// -- Check
		let actual_millis = result_val.as_i64().ok_or("Result should be an integer (milliseconds)")?;
		assert_eq!(actual_millis, expected_millis, "Timestamp mismatch for V7 UUID");
		Ok(())
	}
}

// endregion: --- Tests