aipack 0.8.23

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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
//! Defines common text processing functions for the `aip.text` Lua module.
//!
//! ---
//!
//! ## Lua documentation
//!
//! This section of the `aip.text` module exposes common text processing and ensuring functions.
//!
//! ### Functions
//!
//! - `aip.text.escape_decode(content: string | nil): string | nil`
//! - `aip.text.escape_decode_if_needed(content: string | nil): string | nil`
//! - `aip.text.remove_first_line(content: string | nil): string | nil`
//! - `aip.text.remove_first_lines(content: string | nil, n: int): string | nil`
//! - `aip.text.remove_last_line(content: string | nil): string | nil`
//! - `aip.text.remove_last_lines(content: string | nil, n: int): string | nil`
//! - `aip.text.truncate(content: string | nil, max_len: int): string | nil`
//! - `aip.text.truncate(content: string | nil, max_len: int, ellipsis: string): string | nil`
//! - `aip.text.replace_markers(content: string | nil, new_sections: array): string | nil`
//! - `aip.text.extract_line_blocks(content: string | nil, options: {starts_with: string, extrude?: "content", first?: number}): (table | nil, string | nil)`
//! - `aip.text.ensure(content: string | nil, {prefix? = string, suffix? = string}): string | nil`
//! - `aip.text.ensure_single_trailing_newline(content: string | nil): string | nil`

use crate::script::support::{into_option_string, into_vec_of_strings};
use crate::script::{DEFAULT_MARKERS, LuaValueExt};
use crate::support::html::decode_html_entities;
use crate::support::text::{self, EnsureOptions, LineBlockIter, LineBlockIterOptions, truncate_with_ellipsis};
use crate::types::Extrude;
use mlua::{FromLua, IntoLua, Lua, MultiValue, Table, Value};

// region:    --- Transform

/// ## Lua Documentation
///
/// Replaces markers in `content` with corresponding sections from `new_sections`.
/// Each section in `new_sections` can be a string or a map containing a `.content` string.
/// If `content` is `nil`, returns `nil`.
///
/// ```lua
/// -- API Signature
/// aip.text.replace_markers(content: string | nil, new_sections: array): string | nil
/// ```
///
/// Assumes the markers are `<<START>>` and `<<END>>`.
///
/// ### Arguments
///
/// - `content: string | nil`: The content containing markers to replace.
/// - `new_sections: array`: An array of strings to replace the markers.
///
/// ### Returns
///
/// The string with markers replaced by the corresponding sections, or `nil` if input `content` is `nil`.
pub fn replace_markers_with_default_parkers(
	lua: &Lua,
	(content_val, new_sections_val): (Value, Value),
) -> mlua::Result<Value> {
	let Some(content) = into_option_string(content_val, "aip.text.replace_markers")? else {
		return Ok(Value::Nil);
	};
	let sections = into_vec_of_strings(new_sections_val, "new_sections")?;
	let sections: Vec<&str> = sections.iter().map(|s| s.as_str()).collect();
	let new_content = text::replace_markers(&content, &sections, DEFAULT_MARKERS)?;
	lua.create_string(&new_content).map(Value::String)
}

/// ## Lua Documentation
///
/// Returns `content` truncated to a maximum length of `max_len`.
/// If the content exceeds `max_len`, it appends the optional `ellipsis` string to indicate truncation.
/// If `ellipsis` is not provided, no additional characters are added after truncation.
/// If `content` is `nil`, returns `nil`.
///
/// ```lua
/// -- API Signature
/// aip.text.truncate(content: string | nil, max_len: int, ellipsis?: string): string | nil
/// ```
///
/// This function is useful for limiting the length of text output while preserving meaningful context.
///
/// ### Arguments
///
/// - `content: string | nil`: The content to truncate.
/// - `max_len: int`: The maximum length of the truncated string.
/// - `ellipsis: string` (optional): The string to append if truncation occurs.
///
/// ### Returns
///
/// The truncated string, or `nil` if input `content` is `nil`.
pub fn aip_truncate(
	lua: &Lua,
	(content_val, max_len, ellipsis): (Value, usize, Option<String>),
) -> mlua::Result<Value> {
	let Some(content) = into_option_string(content_val, "aip.text.truncate")? else {
		return Ok(Value::Nil);
	};
	let ellipsis_str = ellipsis.unwrap_or_default();
	let res_cow = truncate_with_ellipsis(&content, max_len, &ellipsis_str);
	lua.create_string(res_cow.as_ref() as &str).map(Value::String)
}

// endregion: --- Transform

// region:    --- Ensure

impl FromLua for EnsureOptions {
	fn from_lua(value: Value, _lua: &Lua) -> mlua::Result<Self> {
		let table = value.as_table().ok_or_else(|| {
			mlua::Error::runtime(
				"Ensure argument needs to be a table with the format {start = string, end = string} (both optional",
			)
		})?;

		//
		let prefix = table.get::<String>("prefix").ok();
		let suffix = table.get::<String>("suffix").ok();

		for (key, _value) in table.pairs::<Value, Value>().flatten() {
			if let Some(k) = key.x_as_lua_str()
				&& k != "prefix"
				&& k != "suffix"
			{
				let msg = format!(
					"Ensure argument contains invalid table property `{k}`. Can only contain `prefix` and/or `suffix`"
				);
				return Err(mlua::Error::RuntimeError(msg));
			}
		}

		//
		Ok(EnsureOptions { prefix, suffix })
	}
}

/// ## Lua Documentation
///
/// Ensure the content start and/or end with the text given in the second argument dictionary.
/// If `content` is `nil`, returns `nil`.
///
/// ```lua
/// -- API Signature
/// aip.text.ensure(content: string | nil, {prefix? = string, suffix? = string}): string | nil
/// ```
///
/// This function is useful for code normalization.
///
/// ### Arguments
///
/// - `content: string | nil`: The content to ensure. (if nil will return nil)
/// - `options: table`: A table with optional `prefix` and `suffix` keys.
///
/// ### Returns
///
/// The ensured string, or `nil` if input `content` is `nil`.
pub fn ensure(lua: &Lua, (content_val, inst_val): (Value, Value)) -> mlua::Result<Value> {
	let Some(content) = into_option_string(content_val, "aip.text.ensure")? else {
		return Ok(Value::Nil);
	};
	let inst = EnsureOptions::from_lua(inst_val, lua)?;
	let res = crate::support::text::ensure(&content, inst);
	let res = res.to_string();
	res.into_lua(lua)
}

/// ## Lua Documentation
///
/// Ensures that `content` ends with a single newline character.
/// If `content` is empty, it returns a newline character.
/// If `content` is `nil`, returns `nil`.
///
/// ```lua
/// -- API Signature
/// aip.text.ensure_single_trailing_newline(content: string | nil): string | nil
///
/// -- (was aip.text.ensure_single_trailing_newline)
/// ```
///
/// This function is useful for code normalization.
///
/// ### Arguments
///
/// - `content: string | nil`: The content to process.
///
/// ### Returns
///
/// The string with a single ending newline, or `nil` if input `content` is `nil`.
pub fn ensure_single_trailing_newline(lua: &Lua, content_val: Value) -> mlua::Result<Value> {
	let Some(content) = into_option_string(content_val, "aip.text.ensure_single_trailing_newline")? else {
		return Ok(Value::Nil);
	};
	let res = crate::support::text::ensure_single_trailing_newline(content);
	lua.create_string(&res).map(Value::String)
}

// endregion: --- Ensure

// region:    --- Remove

/// ## Lua Documentation
///
/// Returns `content` with the first line removed.
/// If `content` is `nil`, returns `nil`.
///
/// ```lua
/// -- API Signature
/// aip.text.remove_first_line(content: string | nil): string | nil
/// ```
///
/// ### Arguments
///
/// - `content: string | nil`: The content to process.
///
/// ### Returns
///
/// The string with the first line removed, or `nil` if input `content` is `nil`.
pub fn remove_first_line(lua: &Lua, content_val: Value) -> mlua::Result<Value> {
	let Some(content) = into_option_string(content_val, "aip.text.remove_first_line")? else {
		return Ok(Value::Nil);
	};
	let res = remove_first_lines_impl(&content, 1).to_string();
	lua.create_string(&res).map(Value::String)
}

/// ## Lua Documentation
///
/// Returns `content` with the first `n` lines removed.
/// If `content` is `nil`, returns `nil`.
///
/// ```lua
/// -- API Signature
/// aip.text.remove_first_lines(content: string | nil, n: int): string | nil
/// ```
///
/// ### Arguments
///
/// - `content: string | nil`: The content to process.
/// - `n: int`: The number of lines to remove.
///
/// ### Returns
///
/// The string with the first `n` lines removed, or `nil` if input `content` is `nil`.
pub fn remove_first_lines(lua: &Lua, (content_val, num_of_lines): (Value, i64)) -> mlua::Result<Value> {
	let Some(content) = into_option_string(content_val, "aip.text.remove_first_lines")? else {
		return Ok(Value::Nil);
	};
	let res = remove_first_lines_impl(&content, num_of_lines as usize).to_string();
	lua.create_string(&res).map(Value::String)
}

pub fn remove_first_lines_impl(content: &str, num_of_lines: usize) -> &str {
	let mut start_idx = 0;
	let mut newline_count = 0;

	for (i, c) in content.char_indices() {
		if c == '\n' {
			newline_count += 1;
			if newline_count == num_of_lines {
				start_idx = i + 1;
				break;
			}
		}
	}

	if newline_count < num_of_lines {
		return "";
	}

	&content[start_idx..]
}

/// ## Lua Documentation
///
/// Returns `content` with the last line removed.
/// If `content` is `nil`, returns `nil`.
///
/// ```lua
/// -- API Signature
/// aip.text.remove_last_line(content: string | nil): string | nil
/// ```
///
/// ### Arguments
///
/// - `content: string | nil`: The content to process.
///
/// ### Returns
///
/// The string with the last line removed, or `nil` if input `content` is `nil`.
pub fn remove_last_line(lua: &Lua, content_val: Value) -> mlua::Result<Value> {
	let Some(content) = into_option_string(content_val, "aip.text.remove_last_line")? else {
		return Ok(Value::Nil);
	};
	let res = remove_last_lines_impl(&content, 1).to_string();
	lua.create_string(&res).map(Value::String)
}

/// ## Lua Documentation
///
/// Returns `content` with the last `n` lines removed.
/// If `content` is `nil`, returns `nil`.
///
/// ```lua
/// -- API Signature
/// aip.text.remove_last_lines(content: string | nil, n: int): string | nil
/// ```
///
/// ### Arguments
///
/// - `content: string | nil`: The content to process.
/// - `n: int`: The number of lines to remove.
///
/// ### Returns
///
/// The string with the last `n` lines removed, or `nil` if input `content` is `nil`.
pub fn remove_last_lines(lua: &Lua, (content_val, num_of_lines): (Value, i64)) -> mlua::Result<Value> {
	let Some(content) = into_option_string(content_val, "aip.text.remove_last_lines")? else {
		return Ok(Value::Nil);
	};
	let res = remove_last_lines_impl(&content, num_of_lines as usize).to_string();
	lua.create_string(&res).map(Value::String)
}

pub fn remove_last_lines_impl(content: &str, num_of_lines: usize) -> &str {
	let mut end_idx = content.len();
	let mut newline_count = 0;

	for (i, c) in content.char_indices().rev() {
		if c == '\n' {
			newline_count += 1;
			if newline_count == num_of_lines {
				end_idx = i;
				break;
			}
		}
	}

	if newline_count < num_of_lines {
		return "";
	}

	&content[..end_idx]
}

// endregion: --- Remove

// region:    --- Escape Fns

/// ## Lua Documentation
///
/// Only escape if needed. Right now, the test only tests `&lt;`.
/// If `content` is `nil`, returns `nil`.
///
/// ```lua
/// -- API Signature
/// aip.text.escape_decode_if_needed(content: string | nil): string | nil
/// ```
///
/// Some LLMs HTML-encode their responses. This function returns `content`
/// after selectively decoding certain HTML tags.
///
/// Right now, the only tag that gets decoded is `&lt;`.
///
/// ### Arguments
///
/// - `content: string | nil`: The content to process.
///
/// ### Returns
///
/// The HTML-decoded string, or `nil` if input `content` is `nil`.
pub fn escape_decode_if_needed(lua: &Lua, content_val: Value) -> mlua::Result<Value> {
	let Some(content) = into_option_string(content_val, "aip.text.escape_decode_if_needed")? else {
		return Ok(Value::Nil);
	};
	if !content.contains("&lt;") {
		lua.create_string(&content).map(Value::String)
	} else {
		let res = decode_html_entities(&content);
		lua.create_string(&res).map(Value::String)
	}
}

/// ## Lua Documentation
///
/// Some LLMs HTML-encode their responses. This function returns `content`,
/// HTML-decoded.
/// If `content` is `nil`, returns `nil`.
///
/// ```lua
/// -- API Signature
/// aip.text.escape_decode(content: string | nil): string | nil
/// ```
///
/// ### Arguments
///
/// - `content: string | nil`: The content to process.
///
/// ### Returns
///
/// The HTML-decoded string, or `nil` if input `content` is `nil`.
pub fn escape_decode(lua: &Lua, content_val: Value) -> mlua::Result<Value> {
	let Some(content) = into_option_string(content_val, "aip.text.escape_decode")? else {
		return Ok(Value::Nil);
	};
	let res = decode_html_entities(&content);
	lua.create_string(&res).map(Value::String)
}

// endregion: --- Escape Fns

// region: --- Extract Line Blocks

/// ## Lua Documentation
///
/// Extracts line blocks from `content` using the given options. The options table
/// must include a required `starts_with` field.
/// If `content` is `nil`, returns `(nil, nil)`.
///
/// ```lua
/// -- API Signature
/// local blocks, extruded = aip.text.extract_line_blocks(content: string | nil, { starts_with = ">", extrude = "content", first = number })
/// ```
///
/// Optionally, you can provide a `first` field as a number, which limits the number
/// of blocks returned by performing that many `next()` iterations. If `extrude` is set to "content",
/// the remaining lines (after extracting the specified number of blocks) are captured via `collect_remains`.
/// If the `extrude` option is not set, the extruded content is returned as `nil`.
///
/// ### Arguments
///
/// - `content: string | nil`: The content to extract line blocks from.
/// - `options: table`: A table with the following keys:
///   - `starts_with: string` (required): The prefix that indicates the start of a line block.
///   - `extrude: "content"` (optional): If set to `"content"`, the remaining content after extracting the blocks is returned.
///   - `first: number` (optional): Limits the number of blocks returned (the rest will be treated as the remaining content)
///
/// ### Returns
///
/// A tuple containing:
///   - `blocks: table | nil`: A Lua table (array-like) where each element is a string representing a line block. `nil` if input `content` is `nil`.
///   - `extruded: string | nil`: The remaining content after extracting the blocks, if `extrude` is set to `"content"`. Otherwise, `nil`. `nil` if input `content` is `nil`.
///
/// ```ts
/// [string[] | nil, string | nil]
/// ```
pub fn extract_line_blocks(lua: &Lua, (content_val, options): (Value, Table)) -> mlua::Result<MultiValue> {
	let Some(content) = into_option_string(content_val, "aip.text.extract_line_blocks")? else {
		return Ok(MultiValue::from_vec(vec![Value::Nil, Value::Nil]));
	};

	let starts_with: Option<String> = options.get("starts_with")?;
	let Some(starts_with_str) = starts_with else {
		return Err(crate::Error::custom(
			r#"aip.text.extract_line_blocks requires to options with {starts_with = ".."} "#,
		)
		.into());
	};
	let extrude_param: Option<String> = options.get("extrude").ok();
	let return_extrude = matches!(extrude_param.as_deref(), Some("content"));
	let first_opt: Option<i64> = options.get("first").ok();
	let first_count: Option<usize> = first_opt.map(|n| n as usize);

	let iter_options = LineBlockIterOptions {
		starts_with: &starts_with_str,
		extrude: if return_extrude { Some(Extrude::Content) } else { None },
	};

	let mut iterator = LineBlockIter::new(content.as_str(), iter_options);

	let (blocks, extruded_content) = if let Some(n) = first_count {
		let mut limited_blocks = Vec::new();
		for _ in 0..n {
			if let Some(block) = iterator.next() {
				limited_blocks.push(block);
			} else {
				break;
			}
		}
		let remains = if return_extrude {
			let (_ignored, extruded) = iterator.collect_remains();
			extruded
		} else {
			String::new()
		};
		(limited_blocks, remains)
	} else {
		iterator.collect_blocks_and_extruded_content()
	};

	let blocks_table = lua.create_table()?;
	for block in blocks.iter() {
		// Use table.push so that the returned Lua table is an array-like table.
		blocks_table.push(block.as_str())?;
	}

	let extruded_value = if return_extrude {
		Value::String(lua.create_string(&extruded_content)?)
	} else {
		Value::Nil
	};

	Ok(MultiValue::from_vec(vec![Value::Table(blocks_table), extruded_value]))
}

// endregion: --- Extract Line Blocks

// region:    --- Tests

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

	use crate::_test_support::{assert_contains, eval_lua, setup_lua};
	use crate::script::aip_modules::aip_text;
	use value_ext::JsonValueExt as _;

	#[tokio::test]
	async fn test_lua_text_replace_markers_nil_content() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(aip_text::init_module, "text").await?;
		let script = r#"return aip.text.replace_markers(nil, {"new1", "new2"})"#;

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

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

	#[tokio::test]
	async fn test_lua_text_truncate_nil_content() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(aip_text::init_module, "text").await?;
		let script = r#"return aip.text.truncate(nil, 10, "...")"#;

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

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

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

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

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

	#[tokio::test]
	async fn test_lua_text_remove_first_lines_nil_content() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(aip_text::init_module, "text").await?;
		let script = r#"return aip.text.remove_first_lines(nil, 2)"#;

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

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

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

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

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

	#[tokio::test]
	async fn test_lua_text_remove_last_lines_nil_content() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(aip_text::init_module, "text").await?;
		let script = r#"return aip.text.remove_last_lines(nil, 2)"#;

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

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

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

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

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

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

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

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

	#[tokio::test]
	async fn test_lua_text_extract_line_blocks_simple() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(aip_text::init_module, "text").await?;
		let lua_code = r#"
local content = [[
> one
> two
Some line A
> 3
The end
]]
local a, b = aip.text.extract_line_blocks(content, { starts_with = ">", extrude = "content" })
return {blocks = a, extruded = b}
		"#;

		// -- Exec
		let res = eval_lua(&lua, lua_code)?;

		// -- Check
		let block = res.x_get_str("/blocks/0")?;
		assert_eq!(block, "> one\n> two\n");
		let block = res.x_get_str("/blocks/1")?;
		assert_eq!(block, "> 3\n");
		let content = res.x_get_str("/extruded")?;
		assert_contains(content, "Some line A");
		assert_contains(content, "The end");

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_text_extract_line_blocks_nil_content() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(aip_text::init_module, "text").await?;
		let script = r#"
        local blocks, extruded = aip.text.extract_line_blocks(nil, { starts_with = ">", extrude = "content" })
        return {blocks, blocks}
    "#;

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

		// -- Check
		// NOTE: Because it returns {nil, nil}, then the json ignore the nil, and we have empty json object (since lua have one constructs for both)
		let res = res.as_object().ok_or("Should be object")?;
		assert!(res.is_empty(), "Should be empty");

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_text_extract_line_blocks_with_first_extrude() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(aip_text::init_module, "text").await?;
		let lua_code = r#"
local content = [[
> one
> two
line1
> three
line2
> four
line3
]]
local a, b = aip.text.extract_line_blocks(content, { starts_with = ">", extrude = "content", first = 2 })
return { blocks = a, extruded = b }
		"#;

		// -- Exec
		let res = eval_lua(&lua, lua_code)?;

		// -- Check
		let block1 = res.x_get_str("/blocks/0")?;
		assert_eq!(block1, "> one\n> two\n");
		let block2 = res.x_get_str("/blocks/1")?;
		assert_eq!(block2, "> three\n");
		let extruded = res.x_get_str("/extruded")?;
		assert_eq!(extruded, "line1\nline2\n> four\nline3\n");

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_text_extract_line_blocks_with_first_no_extrude() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(aip_text::init_module, "text").await?;
		let lua_code = r#"
local content = [[
> one
> two
line1
> three
line2
> four
line3
]]
local a, b = aip.text.extract_line_blocks(content, { starts_with = ">", first = 2 })
return { blocks = a, extruded = b }
		"#;

		// -- Exec
		let res = eval_lua(&lua, lua_code)?;

		// -- Check
		let blocks = res
			.get("blocks")
			.ok_or("Should have blocks")?
			.as_array()
			.ok_or("Should be array")?;
		assert_eq!(blocks.len(), 2, "should have only 2 blocks");
		assert_eq!(blocks[0].as_str().ok_or("Should be str")?, "> one\n> two\n");
		assert_eq!(blocks[1].as_str().ok_or("Should be str")?, "> three\n");

		let extruded_val = res.get("extruded");
		assert!(
			extruded_val.is_none(),
			"extruded should be nil when extrude option is not set"
		);

		Ok(())
	}

	// --- Tests for ensure functions (moved from text_trim.rs)
	#[tokio::test]
	async fn test_lua_text_ensure_simple() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(aip_text::init_module, "text").await?;
		let data = [
			(
				"some- ! -path",
				r#"{prefix = "./", suffix = ".md"}"#,
				"./some- ! -path.md",
			),
			("some- ! -path", r#"{suffix = ".md"}"#, "some- ! -path.md"),
			(" ~ some- ! -path", r#"{prefix = " ~ "}"#, " ~ some- ! -path"),
			("~ some- ! -path", r#"{prefix = " ~ "}"#, " ~ ~ some- ! -path"),
		];

		// -- Exec & Check
		for (content, arg, expected) in data {
			let script = format!("return aip.text.ensure(\"{content}\", {arg})");
			let res = eval_lua(&lua, &script)?;
			assert_eq!(res.as_str().ok_or("Should have res")?, expected);
		}

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_text_ensure_nil_content() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(aip_text::init_module, "text").await?;
		let script = r#"return aip.text.ensure(nil, {prefix = "./", suffix = ".md"})"#;

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

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

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

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

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

// endregion: --- Tests