1use crate::codegen::resolve_field;
8use crate::config::E2eConfig;
9use crate::escape::sanitize_filename;
10use crate::field_access::FieldResolver;
11use crate::fixture::{Assertion, Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
12use alef_core::backend::GeneratedFile;
13use alef_core::config::ResolvedCrateConfig;
14use alef_core::hash::{self, CommentStyle};
15use alef_core::template_versions::pub_dev;
16use anyhow::Result;
17use heck::ToLowerCamelCase;
18use std::cell::Cell;
19use std::fmt::Write as FmtWrite;
20use std::path::PathBuf;
21
22use super::E2eCodegen;
23use super::client;
24
25pub struct DartE2eCodegen;
27
28impl E2eCodegen for DartE2eCodegen {
29 fn generate(
30 &self,
31 groups: &[FixtureGroup],
32 e2e_config: &E2eConfig,
33 config: &ResolvedCrateConfig,
34 _type_defs: &[alef_core::ir::TypeDef],
35 _enums: &[alef_core::ir::EnumDef],
36 ) -> Result<Vec<GeneratedFile>> {
37 let lang = self.language_name();
38 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
39
40 let mut files = Vec::new();
41
42 let dart_pkg = e2e_config.resolve_package("dart");
44 let pkg_name = dart_pkg
45 .as_ref()
46 .and_then(|p| p.name.as_ref())
47 .cloned()
48 .unwrap_or_else(|| config.dart_pubspec_name());
49 let pkg_path = dart_pkg
50 .as_ref()
51 .and_then(|p| p.path.as_ref())
52 .cloned()
53 .unwrap_or_else(|| "../../packages/dart".to_string());
54 let pkg_version = dart_pkg
55 .as_ref()
56 .and_then(|p| p.version.as_ref())
57 .cloned()
58 .or_else(|| config.resolved_version())
59 .unwrap_or_else(|| "0.1.0".to_string());
60
61 files.push(GeneratedFile {
63 path: output_base.join("pubspec.yaml"),
64 content: render_pubspec(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
65 generated_header: false,
66 });
67
68 files.push(GeneratedFile {
71 path: output_base.join("dart_test.yaml"),
72 content: concat!(
73 "# Generated by alef — DO NOT EDIT.\n",
74 "# Run test files sequentially to avoid overwhelming the mock server with\n",
75 "# concurrent keep-alive connections.\n",
76 "concurrency: 1\n",
77 )
78 .to_string(),
79 generated_header: false,
80 });
81
82 let test_base = output_base.join("test");
83
84 let bridge_class = config.dart_bridge_class_name();
86
87 let frb_module_name = config.name.replace('-', "_");
91
92 let dart_stub_methods: std::collections::HashSet<String> = config
97 .dart
98 .as_ref()
99 .map(|d| d.stub_methods.iter().cloned().collect())
100 .unwrap_or_default();
101
102 for group in groups {
103 let active: Vec<&Fixture> = group
104 .fixtures
105 .iter()
106 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
107 .filter(|f| {
108 let call_config = e2e_config.resolve_call_for_fixture(
109 f.call.as_deref(),
110 &f.id,
111 &f.resolved_category(),
112 &f.tags,
113 &f.input,
114 );
115 let resolved_function = call_config
116 .overrides
117 .get(lang)
118 .and_then(|o| o.function.as_ref())
119 .cloned()
120 .unwrap_or_else(|| call_config.function.clone());
121 !dart_stub_methods.contains(&resolved_function)
122 })
123 .collect();
124
125 if active.is_empty() {
126 continue;
127 }
128
129 let filename = format!("{}_test.dart", sanitize_filename(&group.category));
130 let content = render_test_file(
131 &group.category,
132 &active,
133 e2e_config,
134 lang,
135 &pkg_name,
136 &frb_module_name,
137 &bridge_class,
138 );
139 files.push(GeneratedFile {
140 path: test_base.join(filename),
141 content,
142 generated_header: true,
143 });
144 }
145
146 Ok(files)
147 }
148
149 fn language_name(&self) -> &'static str {
150 "dart"
151 }
152}
153
154fn render_pubspec(
159 pkg_name: &str,
160 pkg_path: &str,
161 pkg_version: &str,
162 dep_mode: crate::config::DependencyMode,
163) -> String {
164 let test_ver = pub_dev::TEST_PACKAGE;
165 let http_ver = pub_dev::HTTP_PACKAGE;
166
167 let dep_block = match dep_mode {
168 crate::config::DependencyMode::Registry => {
169 format!(" {pkg_name}: ^{pkg_version}")
170 }
171 crate::config::DependencyMode::Local => {
172 format!(" {pkg_name}:\n path: {pkg_path}")
173 }
174 };
175
176 let sdk = alef_core::template_versions::toolchain::DART_SDK_CONSTRAINT;
177 format!(
178 r#"name: e2e_dart
179version: 0.1.0
180publish_to: none
181
182environment:
183 sdk: "{sdk}"
184
185dependencies:
186{dep_block}
187
188dev_dependencies:
189 test: {test_ver}
190 http: {http_ver}
191"#
192 )
193}
194
195fn render_test_file(
196 category: &str,
197 fixtures: &[&Fixture],
198 e2e_config: &E2eConfig,
199 lang: &str,
200 pkg_name: &str,
201 frb_module_name: &str,
202 bridge_class: &str,
203) -> String {
204 let mut out = String::new();
205 out.push_str(&hash::header(CommentStyle::DoubleSlash));
206 out.push_str("// ignore_for_file: unused_local_variable\n\n");
210
211 let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
213
214 let has_batch_byte_items = fixtures.iter().any(|f| {
216 let call_config =
217 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
218 call_config.args.iter().any(|a| {
219 a.element_type.as_deref() == Some("BatchBytesItem") && resolve_field(&f.input, &a.field).is_array()
220 })
221 });
222
223 let needs_chdir = fixtures.iter().any(|f| {
227 if f.is_http_test() {
228 return false;
229 }
230 let call_config =
231 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
232 call_config
233 .args
234 .iter()
235 .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
236 });
237
238 let has_handle_args = fixtures.iter().any(|f| {
244 if f.is_http_test() {
245 return false;
246 }
247 let call_config =
248 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
249 call_config
250 .args
251 .iter()
252 .any(|a| a.arg_type == "json_object" && super::resolve_field(&f.input, &a.field).is_array())
253 });
254
255 let lang_client_factory = e2e_config
261 .call
262 .overrides
263 .get(lang)
264 .and_then(|o| o.client_factory.as_deref())
265 .is_some();
266 let has_mock_url_refs = lang_client_factory
267 || fixtures.iter().any(|f| {
268 if f.is_http_test() {
269 return false;
270 }
271 let call_config = e2e_config.resolve_call_for_fixture(
272 f.call.as_deref(),
273 &f.id,
274 &f.resolved_category(),
275 &f.tags,
276 &f.input,
277 );
278 if call_config.args.iter().any(|a| a.arg_type == "mock_url") {
279 return true;
280 }
281 call_config
282 .overrides
283 .get(lang)
284 .and_then(|o| o.client_factory.as_deref())
285 .is_some()
286 });
287
288 let _ = writeln!(out, "import 'package:test/test.dart';");
289 if has_http_fixtures || needs_chdir || has_mock_url_refs {
294 let _ = writeln!(out, "import 'dart:io';");
295 }
296 if has_batch_byte_items {
297 let _ = writeln!(out, "import 'dart:typed_data';");
298 }
299 let _ = writeln!(out, "import 'package:{pkg_name}/{pkg_name}.dart';");
300 let _ = writeln!(
306 out,
307 "import 'package:{pkg_name}/src/{frb_module_name}_bridge_generated/frb_generated.dart' show RustLib;"
308 );
309 if has_http_fixtures {
310 let _ = writeln!(out, "import 'dart:async';");
311 }
312 if has_http_fixtures || has_handle_args {
314 let _ = writeln!(out, "import 'dart:convert';");
315 }
316 let _ = writeln!(out);
317
318 if has_http_fixtures {
328 let _ = writeln!(out, "HttpClient _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
329 let _ = writeln!(out);
330 let _ = writeln!(out, "var _lock = Future<void>.value();");
331 let _ = writeln!(out);
332 let _ = writeln!(out, "Future<T> _serialized<T>(Future<T> Function() fn) async {{");
333 let _ = writeln!(out, " final current = _lock;");
334 let _ = writeln!(out, " final next = Completer<void>();");
335 let _ = writeln!(out, " _lock = next.future;");
336 let _ = writeln!(out, " try {{");
337 let _ = writeln!(out, " await current;");
338 let _ = writeln!(out, " return await fn();");
339 let _ = writeln!(out, " }} finally {{");
340 let _ = writeln!(out, " next.complete();");
341 let _ = writeln!(out, " }}");
342 let _ = writeln!(out, "}}");
343 let _ = writeln!(out);
344 let _ = writeln!(out, "Future<T> _withRetry<T>(Future<T> Function() fn) async {{");
347 let _ = writeln!(out, " try {{");
348 let _ = writeln!(out, " return await fn();");
349 let _ = writeln!(out, " }} on SocketException {{");
350 let _ = writeln!(out, " _httpClient.close(force: true);");
351 let _ = writeln!(out, " _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
352 let _ = writeln!(out, " return fn();");
353 let _ = writeln!(out, " }} on HttpException {{");
354 let _ = writeln!(out, " _httpClient.close(force: true);");
355 let _ = writeln!(out, " _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
356 let _ = writeln!(out, " return fn();");
357 let _ = writeln!(out, " }}");
358 let _ = writeln!(out, "}}");
359 let _ = writeln!(out);
360 }
361
362 let _ = writeln!(out, "// E2e tests for category: {category}");
363 let _ = writeln!(out);
364
365 let _ = writeln!(out, "String _alefE2eText(Object? value) {{");
371 let _ = writeln!(out, " if (value == null) return '';");
372 let _ = writeln!(
373 out,
374 " // Check if it's an enum by examining its toString representation."
375 );
376 let _ = writeln!(out, " final str = value.toString();");
377 let _ = writeln!(out, " if (str.contains('.')) {{");
378 let _ = writeln!(
379 out,
380 " // Enum.toString() returns 'EnumName.variantName'. Extract the variant name."
381 );
382 let _ = writeln!(out, " final parts = str.split('.');");
383 let _ = writeln!(out, " if (parts.length == 2) {{");
384 let _ = writeln!(out, " final variantName = parts[1];");
385 let _ = writeln!(
386 out,
387 " // Convert camelCase variant names to snake_case for serde compatibility."
388 );
389 let _ = writeln!(out, " // E.g. 'toolCalls' -> 'tool_calls', 'stop' -> 'stop'.");
390 let _ = writeln!(out, " return _camelToSnake(variantName);");
391 let _ = writeln!(out, " }}");
392 let _ = writeln!(out, " }}");
393 let _ = writeln!(out, " return str;");
394 let _ = writeln!(out, "}}");
395 let _ = writeln!(out);
396
397 let _ = writeln!(out, "String _camelToSnake(String camel) {{");
399 let _ = writeln!(out, " final buffer = StringBuffer();");
400 let _ = writeln!(out, " for (int i = 0; i < camel.length; i++) {{");
401 let _ = writeln!(out, " final char = camel[i];");
402 let _ = writeln!(out, " if (char.contains(RegExp(r'[A-Z]'))) {{");
403 let _ = writeln!(out, " if (i > 0) buffer.write('_');");
404 let _ = writeln!(out, " buffer.write(char.toLowerCase());");
405 let _ = writeln!(out, " }} else {{");
406 let _ = writeln!(out, " buffer.write(char);");
407 let _ = writeln!(out, " }}");
408 let _ = writeln!(out, " }}");
409 let _ = writeln!(out, " return buffer.toString();");
410 let _ = writeln!(out, "}}");
411 let _ = writeln!(out);
412
413 let _ = writeln!(out, "void main() {{");
414
415 let _ = writeln!(out, " setUpAll(() async {{");
422 let _ = writeln!(out, " await RustLib.init();");
423 if needs_chdir {
424 let test_docs_path = e2e_config.test_documents_relative_from(0);
425 let _ = writeln!(
426 out,
427 " final _testDocs = Platform.environment['FIXTURES_DIR'] ?? '{test_docs_path}';"
428 );
429 let _ = writeln!(out, " final _dir = Directory(_testDocs);");
430 let _ = writeln!(out, " if (_dir.existsSync()) Directory.current = _dir;");
431 }
432 let _ = writeln!(out, " }});");
433 let _ = writeln!(out);
434
435 if has_http_fixtures {
437 let _ = writeln!(out, " tearDownAll(() => _httpClient.close());");
438 let _ = writeln!(out);
439 }
440
441 for fixture in fixtures {
442 render_test_case(&mut out, fixture, e2e_config, lang, bridge_class);
443 }
444
445 let _ = writeln!(out, "}}");
446 out
447}
448
449fn render_test_case(out: &mut String, fixture: &Fixture, e2e_config: &E2eConfig, lang: &str, bridge_class: &str) {
450 if let Some(http) = &fixture.http {
452 render_http_test_case(out, fixture, http);
453 return;
454 }
455
456 let call_config = e2e_config.resolve_call_for_fixture(
458 fixture.call.as_deref(),
459 &fixture.id,
460 &fixture.resolved_category(),
461 &fixture.tags,
462 &fixture.input,
463 );
464 let call_field_resolver = FieldResolver::new(
466 e2e_config.effective_fields(call_config),
467 e2e_config.effective_fields_optional(call_config),
468 e2e_config.effective_result_fields(call_config),
469 e2e_config.effective_fields_array(call_config),
470 e2e_config.effective_fields_method_calls(call_config),
471 );
472 let field_resolver = &call_field_resolver;
473 let enum_fields_base = e2e_config.effective_fields_enum(call_config);
474
475 let effective_enum_fields: std::collections::HashSet<String> = {
480 let dart_overrides = call_config.overrides.get("dart");
481 if let Some(overrides) = dart_overrides {
482 let mut merged = enum_fields_base.clone();
483 merged.extend(overrides.enum_fields.keys().cloned());
484 merged
485 } else {
486 enum_fields_base.clone()
487 }
488 };
489 let enum_fields = &effective_enum_fields;
490 let call_overrides = call_config.overrides.get(lang);
491 let mut function_name = call_overrides
492 .and_then(|o| o.function.as_ref())
493 .cloned()
494 .unwrap_or_else(|| call_config.function.clone());
495 function_name = function_name
497 .split('_')
498 .enumerate()
499 .map(|(i, part)| {
500 if i == 0 {
501 part.to_string()
502 } else {
503 let mut chars = part.chars();
504 match chars.next() {
505 None => String::new(),
506 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
507 }
508 }
509 })
510 .collect::<Vec<_>>()
511 .join("");
512 let result_var = &call_config.result_var;
513 let description = escape_dart(&fixture.description);
514 let fixture_id = &fixture.id;
515 let _is_async = call_overrides.and_then(|o| o.r#async).unwrap_or(call_config.r#async);
518
519 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
520 let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
521 let result_is_simple = call_overrides.is_some_and(|o| o.result_is_simple) || call_config.result_is_simple;
526
527 let options_type: Option<&str> = call_overrides.and_then(|o| o.options_type.as_deref());
534 let options_via: &str = call_overrides
535 .and_then(|o| o.options_via.as_deref())
536 .unwrap_or("kwargs");
537
538 let file_path_for_mime: Option<&str> = call_config
546 .args
547 .iter()
548 .find(|a| a.arg_type == "file_path")
549 .and_then(|a| resolve_field(&fixture.input, &a.field).as_str());
550
551 let has_file_path_arg = call_config.args.iter().any(|a| a.arg_type == "file_path");
558 let caller_supplied_override = call_overrides.and_then(|o| o.function.as_ref()).is_some();
561 if has_file_path_arg && !caller_supplied_override {
562 function_name = match function_name.as_str() {
563 "extractFile" => "extractBytes".to_string(),
564 "extractFileSync" => "extractBytesSync".to_string(),
565 other => other.to_string(),
566 };
567 }
568
569 let mut setup_lines: Vec<String> = Vec::new();
572 let mut args = Vec::new();
573
574 for arg_def in &call_config.args {
575 match arg_def.arg_type.as_str() {
576 "mock_url" => {
577 let name = arg_def.name.clone();
578 if fixture.has_host_root_route() {
579 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
580 setup_lines.push(format!(
581 r#"final {name} = Platform.environment["{env_key}"] ?? (Platform.environment["MOCK_SERVER_URL"]! + "/fixtures/{fixture_id}");"#
582 ));
583 } else {
584 setup_lines.push(format!(
585 r#"final {name} = "${{Platform.environment["MOCK_SERVER_URL"] ?? "http://localhost:8080"}}/fixtures/{fixture_id}";"#
586 ));
587 }
588 args.push(name);
589 continue;
590 }
591 "handle" => {
592 let name = arg_def.name.clone();
593 let field = arg_def.field.strip_prefix("input.").unwrap_or(&arg_def.field);
594 let config_value = fixture.input.get(field).cloned().unwrap_or(serde_json::Value::Null);
595 let create_fn = {
597 let mut chars = name.chars();
598 let pascal = match chars.next() {
599 None => String::new(),
600 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
601 };
602 format!("create{pascal}")
603 };
604 if config_value.is_null()
605 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
606 {
607 setup_lines.push(format!("final {name} = await {bridge_class}.{create_fn}();"));
608 } else {
609 let json_str = serde_json::to_string(&config_value).unwrap_or_default();
610 let config_var = format!("{name}Config");
611 setup_lines.push(format!(
616 "final {config_var} = await createCrawlConfigFromJson(json: r'{json_str}');"
617 ));
618 setup_lines.push(format!(
620 "final {name} = await {bridge_class}.{create_fn}(config: {config_var});"
621 ));
622 }
623 args.push(name);
624 continue;
625 }
626 _ => {}
627 }
628
629 let arg_value = resolve_field(&fixture.input, &arg_def.field);
630 match arg_def.arg_type.as_str() {
631 "bytes" | "file_path" => {
632 if let serde_json::Value::String(file_path) = arg_value {
637 args.push(format!("File('{}').readAsBytesSync()", file_path));
638 }
639 }
640 "string" => {
641 let dart_param_name = snake_to_camel(&arg_def.name);
648 match arg_value {
649 serde_json::Value::String(s) => {
650 let literal = format!("'{}'", escape_dart(s));
651 args.push(format!("{dart_param_name}: {literal}"));
652 }
653 serde_json::Value::Null
654 if arg_def.optional
655 && arg_def.name == "mime_type" =>
658 {
659 let inferred = file_path_for_mime
660 .and_then(mime_from_extension)
661 .unwrap_or("application/octet-stream");
662 args.push(format!("{dart_param_name}: '{inferred}'"));
663 }
664 _ => {}
666 }
667 }
668 "json_object" => {
669 if let Some(elem_type) = &arg_def.element_type {
671 if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && arg_value.is_array() {
672 let dart_items = emit_dart_batch_item_array(arg_value, elem_type);
673 args.push(dart_items);
674 } else if elem_type == "String" && arg_value.is_array() {
675 let items: Vec<String> = arg_value
682 .as_array()
683 .unwrap()
684 .iter()
685 .filter_map(|v| v.as_str())
686 .map(|s| format!("'{}'", escape_dart(s)))
687 .collect();
688 args.push(format!("<String>[{}]", items.join(", ")));
689 }
690 } else if options_via == "from_json" {
691 if let Some(opts_type) = options_type {
701 if !arg_value.is_null() {
702 let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
703 let escaped_json = escape_dart(&json_str);
706 let var_name = format!("_{}", arg_def.name);
707 let dart_fn = type_name_to_create_from_json_dart(opts_type);
708 setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
709 args.push(format!("req: {var_name}"));
712 }
713 }
714 } else if arg_def.name == "config" {
715 if let serde_json::Value::Object(map) = &arg_value {
716 if !map.is_empty() {
717 let explicit_options =
726 options_type.is_some_and(|t| t != "ExtractionConfig" && t != "FileExtractionConfig");
727 let has_non_scalar = map.values().any(|v| {
728 matches!(
729 v,
730 serde_json::Value::String(_)
731 | serde_json::Value::Object(_)
732 | serde_json::Value::Array(_)
733 )
734 });
735 if explicit_options || has_non_scalar {
736 let opts_type = options_type.unwrap_or("ExtractionConfig");
737 let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
738 let escaped_json = escape_dart(&json_str);
739 let var_name = format!("_{}", arg_def.name);
740 let dart_fn = type_name_to_create_from_json_dart(opts_type);
741 setup_lines
742 .push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
743 args.push(var_name);
744 } else {
745 args.push(emit_extraction_config_dart(map));
751 }
752 }
753 }
754 } else if arg_value.is_array() {
756 let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
759 let var_name = arg_def.name.clone();
760 setup_lines.push(format!(
761 "final {var_name} = (jsonDecode(r'{json_str}') as List<dynamic>).cast<String>();"
762 ));
763 args.push(var_name);
764 } else if let serde_json::Value::Object(map) = &arg_value {
765 if !map.is_empty() {
779 if let Some(opts_type) = options_type {
780 let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
781 let escaped_json = escape_dart(&json_str);
782 let dart_param_name = snake_to_camel(&arg_def.name);
783 let var_name = format!("_{}", arg_def.name);
784 let dart_fn = type_name_to_create_from_json_dart(opts_type);
785 if fixture.visitor.is_some() {
786 setup_lines.push(format!(
787 "final {var_name} = await {dart_fn}WithVisitor(json: '{escaped_json}', visitor: _visitor);"
788 ));
789 } else {
790 setup_lines
791 .push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
792 }
793 if arg_def.optional {
794 args.push(format!("{dart_param_name}: {var_name}"));
795 } else {
796 args.push(var_name);
797 }
798 }
799 }
800 }
801 }
802 _ => {}
803 }
804 }
805
806 if let Some(visitor_spec) = &fixture.visitor {
821 let mut visitor_setup: Vec<String> = Vec::new();
822 let _ = super::dart_visitors::build_dart_visitor(&mut visitor_setup, visitor_spec);
823 for line in visitor_setup.into_iter().rev() {
826 setup_lines.insert(0, line);
827 }
828
829 let already_has_options = args.iter().any(|a| a.starts_with("options:") || a == "_options");
833 if !already_has_options {
834 if let Some(opts_type) = options_type {
835 let dart_fn = type_name_to_create_from_json_dart(opts_type);
836 setup_lines.push(format!(
837 "final _options = await {dart_fn}WithVisitor(json: '{{}}', visitor: _visitor);"
838 ));
839 args.push("options: _options".to_string());
840 }
841 }
842 }
843
844 let client_factory: Option<&str> = call_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
848 e2e_config
849 .call
850 .overrides
851 .get(lang)
852 .and_then(|o| o.client_factory.as_deref())
853 });
854
855 let client_factory_camel: Option<String> = client_factory.map(|f| {
857 f.split('_')
858 .enumerate()
859 .map(|(i, part)| {
860 if i == 0 {
861 part.to_string()
862 } else {
863 let mut chars = part.chars();
864 match chars.next() {
865 None => String::new(),
866 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
867 }
868 }
869 })
870 .collect::<Vec<_>>()
871 .join("")
872 });
873
874 let _ = writeln!(out, " test('{description}', () async {{");
878
879 let args_str = args.join(", ");
880 let receiver_class = call_overrides
881 .and_then(|o| o.class.as_ref())
882 .cloned()
883 .unwrap_or_else(|| bridge_class.to_string());
884
885 let (receiver, extra_setup): (String, Option<String>) = if let Some(factory) = &client_factory_camel {
889 let has_mock_url = call_config.args.iter().any(|a| a.arg_type == "mock_url");
890 let mock_url_setup = if !has_mock_url {
891 if fixture.has_host_root_route() {
893 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
894 Some(format!(
895 "final _mockUrl = Platform.environment[\"{env_key}\"] ?? (Platform.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\");"
896 ))
897 } else {
898 Some(format!(
899 r#"final _mockUrl = "${{Platform.environment["MOCK_SERVER_URL"] ?? "http://localhost:8080"}}/fixtures/{fixture_id}";"#
900 ))
901 }
902 } else {
903 None
904 };
905 let url_expr = if has_mock_url {
906 call_config
909 .args
910 .iter()
911 .find(|a| a.arg_type == "mock_url")
912 .map(|a| a.name.clone())
913 .unwrap_or_else(|| "_mockUrl".to_string())
914 } else {
915 "_mockUrl".to_string()
916 };
917 let create_line = format!("final _client = await {receiver_class}.{factory}('test-key', baseUrl: {url_expr});");
918 let full_setup = if let Some(url_line) = mock_url_setup {
919 Some(format!("{url_line}\n {create_line}"))
920 } else {
921 Some(create_line)
922 };
923 ("_client".to_string(), full_setup)
924 } else {
925 (receiver_class.clone(), None)
926 };
927
928 if expects_error && (!setup_lines.is_empty() || extra_setup.is_some()) {
929 let _ = writeln!(out, " await expectLater(() async {{");
933 for line in &setup_lines {
934 let _ = writeln!(out, " {line}");
935 }
936 if let Some(extra) = &extra_setup {
937 for line in extra.lines() {
938 let _ = writeln!(out, " {line}");
939 }
940 }
941 if is_streaming {
942 let _ = writeln!(out, " return {receiver}.{function_name}({args_str}).toList();");
943 } else {
944 let _ = writeln!(out, " return {receiver}.{function_name}({args_str});");
945 }
946 let _ = writeln!(out, " }}(), throwsA(anything));");
947 } else if expects_error {
948 if let Some(extra) = &extra_setup {
950 for line in extra.lines() {
951 let _ = writeln!(out, " {line}");
952 }
953 }
954 if is_streaming {
955 let _ = writeln!(
956 out,
957 " await expectLater({receiver}.{function_name}({args_str}).toList(), throwsA(anything));"
958 );
959 } else {
960 let _ = writeln!(
961 out,
962 " await expectLater({receiver}.{function_name}({args_str}), throwsA(anything));"
963 );
964 }
965 } else {
966 for line in &setup_lines {
967 let _ = writeln!(out, " {line}");
968 }
969 if let Some(extra) = &extra_setup {
970 for line in extra.lines() {
971 let _ = writeln!(out, " {line}");
972 }
973 }
974 if is_streaming {
975 let _ = writeln!(
976 out,
977 " final {result_var} = await {receiver}.{function_name}({args_str}).toList();"
978 );
979 } else {
980 let _ = writeln!(
981 out,
982 " final {result_var} = await {receiver}.{function_name}({args_str});"
983 );
984 }
985 for assertion in &fixture.assertions {
986 if is_streaming {
987 render_streaming_assertion_dart(out, assertion, result_var);
988 } else {
989 render_assertion_dart(
990 out,
991 assertion,
992 result_var,
993 result_is_simple,
994 field_resolver,
995 enum_fields,
996 );
997 }
998 }
999 }
1000
1001 let _ = writeln!(out, " }});");
1002 let _ = writeln!(out);
1003}
1004
1005fn dart_length_expr(field_accessor: &str, field: Option<&str>, field_resolver: &FieldResolver) -> String {
1013 let is_optional = field
1014 .map(|f| {
1015 let resolved = field_resolver.resolve(f);
1016 field_resolver.is_optional(f) || field_resolver.is_optional(resolved)
1017 })
1018 .unwrap_or(false);
1019 if is_optional {
1020 format!("{field_accessor}?.length ?? 0")
1021 } else {
1022 format!("{field_accessor}.length")
1023 }
1024}
1025
1026fn dart_format_value(val: &serde_json::Value) -> String {
1027 match val {
1028 serde_json::Value::String(s) => format!("'{}'", escape_dart(s)),
1029 serde_json::Value::Bool(b) => b.to_string(),
1030 serde_json::Value::Number(n) => n.to_string(),
1031 serde_json::Value::Null => "null".to_string(),
1032 other => format!("'{}'", escape_dart(&other.to_string())),
1033 }
1034}
1035
1036fn render_assertion_dart(
1047 out: &mut String,
1048 assertion: &Assertion,
1049 result_var: &str,
1050 result_is_simple: bool,
1051 field_resolver: &FieldResolver,
1052 enum_fields: &std::collections::HashSet<String>,
1053) {
1054 if !result_is_simple {
1058 if let Some(f) = assertion.field.as_deref() {
1059 let head = f.split("[].").next().unwrap_or(f);
1062 if !head.is_empty() && !field_resolver.is_valid_for_result(head) {
1063 let _ = writeln!(out, " // skipped: field '{f}' not available on dart result type");
1064 return;
1065 }
1066 }
1067 }
1068
1069 if let Some(f) = assertion.field.as_deref() {
1075 if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
1076 let _ = writeln!(
1077 out,
1078 " // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Dart)"
1079 );
1080 return;
1081 }
1082 }
1083
1084 if let Some(f) = assertion.field.as_deref() {
1086 if let Some(dot) = f.find("[].") {
1087 let resolved_full = field_resolver.resolve(f);
1092 let (array_part, elem_part) = match resolved_full.find("[].") {
1093 Some(rdot) => (&resolved_full[..rdot], &resolved_full[rdot + 3..]),
1094 None => (&f[..dot], &f[dot + 3..]),
1097 };
1098 let array_accessor = if array_part.is_empty() {
1099 result_var.to_string()
1100 } else {
1101 field_resolver.accessor(array_part, "dart", result_var)
1102 };
1103 let elem_accessor = field_to_dart_accessor(elem_part);
1104 match assertion.assertion_type.as_str() {
1105 "contains" => {
1106 if let Some(expected) = &assertion.value {
1107 let dart_val = dart_format_value(expected);
1108 let _ = writeln!(
1109 out,
1110 " expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isTrue);"
1111 );
1112 }
1113 }
1114 "contains_all" => {
1115 if let Some(values) = &assertion.values {
1116 for val in values {
1117 let dart_val = dart_format_value(val);
1118 let _ = writeln!(
1119 out,
1120 " expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isTrue);"
1121 );
1122 }
1123 }
1124 }
1125 "not_contains" => {
1126 if let Some(expected) = &assertion.value {
1127 let dart_val = dart_format_value(expected);
1128 let _ = writeln!(
1129 out,
1130 " expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isFalse);"
1131 );
1132 } else if let Some(values) = &assertion.values {
1133 for val in values {
1134 let dart_val = dart_format_value(val);
1135 let _ = writeln!(
1136 out,
1137 " expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isFalse);"
1138 );
1139 }
1140 }
1141 }
1142 "not_empty" => {
1143 let _ = writeln!(
1144 out,
1145 " expect({array_accessor}.any((e) => e.{elem_accessor}.toString().isNotEmpty), isTrue);"
1146 );
1147 }
1148 other => {
1149 let _ = writeln!(
1150 out,
1151 " // skipped: unsupported traversal assertion '{other}' on '{f}'"
1152 );
1153 }
1154 }
1155 return;
1156 }
1157 }
1158
1159 let field_accessor = if result_is_simple {
1160 result_var.to_string()
1164 } else {
1165 match assertion.field.as_deref() {
1166 Some(f) if !f.is_empty() => field_resolver.accessor(f, "dart", result_var),
1171 _ => result_var.to_string(),
1172 }
1173 };
1174
1175 let format_value = |val: &serde_json::Value| -> String { dart_format_value(val) };
1176
1177 match assertion.assertion_type.as_str() {
1178 "equals" | "field_equals" => {
1179 if let Some(expected) = &assertion.value {
1180 let dart_val = format_value(expected);
1181 let is_enum_field = assertion
1184 .field
1185 .as_deref()
1186 .map(|f| {
1187 let resolved = field_resolver.resolve(f);
1188 enum_fields.contains(f) || enum_fields.contains(resolved)
1189 })
1190 .unwrap_or(false);
1191
1192 if expected.is_string() {
1196 if is_enum_field {
1197 let _ = writeln!(
1200 out,
1201 " expect(_alefE2eText({field_accessor}).trim(), equals({dart_val}.toString().trim()));"
1202 );
1203 } else {
1204 let safe_accessor = if result_is_simple && assertion.field.is_none() {
1207 format!("({field_accessor} ?? '').toString().trim()")
1208 } else {
1209 format!("{field_accessor}.toString().trim()")
1210 };
1211 let _ = writeln!(
1212 out,
1213 " expect({safe_accessor}, equals({dart_val}.toString().trim()));"
1214 );
1215 }
1216 } else {
1217 let _ = writeln!(out, " expect({field_accessor}, equals({dart_val}));");
1218 }
1219 } else {
1220 let _ = writeln!(
1221 out,
1222 " // skipped: '{}' assertion missing value",
1223 assertion.assertion_type
1224 );
1225 }
1226 }
1227 "not_equals" => {
1228 if let Some(expected) = &assertion.value {
1229 let dart_val = format_value(expected);
1230 let is_enum_field = assertion
1232 .field
1233 .as_deref()
1234 .map(|f| {
1235 let resolved = field_resolver.resolve(f);
1236 enum_fields.contains(f) || enum_fields.contains(resolved)
1237 })
1238 .unwrap_or(false);
1239
1240 if expected.is_string() {
1241 if is_enum_field {
1242 let _ = writeln!(
1243 out,
1244 " expect(_alefE2eText({field_accessor}).trim(), isNot(equals({dart_val}.toString().trim())));"
1245 );
1246 } else {
1247 let safe_accessor = if result_is_simple && assertion.field.is_none() {
1250 format!("({field_accessor} ?? '').toString().trim()")
1251 } else {
1252 format!("{field_accessor}.toString().trim()")
1253 };
1254 let _ = writeln!(
1255 out,
1256 " expect({safe_accessor}, isNot(equals({dart_val}.toString().trim())));"
1257 );
1258 }
1259 } else {
1260 let _ = writeln!(out, " expect({field_accessor}, isNot(equals({dart_val})));");
1261 }
1262 }
1263 }
1264 "contains" => {
1265 if let Some(expected) = &assertion.value {
1266 let dart_val = format_value(expected);
1267 let _ = writeln!(out, " expect({field_accessor}, contains({dart_val}));");
1268 } else {
1269 let _ = writeln!(out, " // skipped: 'contains' assertion missing value");
1270 }
1271 }
1272 "contains_all" => {
1273 if let Some(values) = &assertion.values {
1274 for val in values {
1275 let dart_val = format_value(val);
1276 let _ = writeln!(out, " expect({field_accessor}, contains({dart_val}));");
1277 }
1278 }
1279 }
1280 "contains_any" => {
1281 if let Some(values) = &assertion.values {
1282 let checks: Vec<String> = values
1283 .iter()
1284 .map(|v| {
1285 let dart_val = format_value(v);
1286 format!("{field_accessor}.contains({dart_val})")
1287 })
1288 .collect();
1289 let joined = checks.join(" || ");
1290 let _ = writeln!(out, " expect({joined}, isTrue);");
1291 }
1292 }
1293 "not_contains" => {
1294 if let Some(expected) = &assertion.value {
1295 let dart_val = format_value(expected);
1296 let _ = writeln!(out, " expect({field_accessor}, isNot(contains({dart_val})));");
1297 } else if let Some(values) = &assertion.values {
1298 for val in values {
1299 let dart_val = format_value(val);
1300 let _ = writeln!(out, " expect({field_accessor}, isNot(contains({dart_val})));");
1301 }
1302 }
1303 }
1304 "not_empty" => {
1305 let is_collection = assertion.field.as_deref().is_some_and(|f| {
1310 let resolved = field_resolver.resolve(f);
1311 field_resolver.is_array(f) || field_resolver.is_array(resolved)
1312 });
1313 if is_collection {
1314 let _ = writeln!(out, " expect({field_accessor}, isNotEmpty);");
1315 } else {
1316 let _ = writeln!(out, " expect({field_accessor}, isNotNull);");
1317 }
1318 }
1319 "is_empty" => {
1320 let _ = writeln!(out, " expect({field_accessor}, anyOf(isNull, isEmpty));");
1324 }
1325 "starts_with" => {
1326 if let Some(expected) = &assertion.value {
1327 let dart_val = format_value(expected);
1328 let _ = writeln!(out, " expect({field_accessor}, startsWith({dart_val}));");
1329 }
1330 }
1331 "ends_with" => {
1332 if let Some(expected) = &assertion.value {
1333 let dart_val = format_value(expected);
1334 let _ = writeln!(out, " expect({field_accessor}, endsWith({dart_val}));");
1335 }
1336 }
1337 "min_length" => {
1338 if let Some(val) = &assertion.value {
1339 if let Some(n) = val.as_u64() {
1340 let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1341 let _ = writeln!(out, " expect({length_expr}, greaterThanOrEqualTo({n}));");
1342 }
1343 }
1344 }
1345 "max_length" => {
1346 if let Some(val) = &assertion.value {
1347 if let Some(n) = val.as_u64() {
1348 let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1349 let _ = writeln!(out, " expect({length_expr}, lessThanOrEqualTo({n}));");
1350 }
1351 }
1352 }
1353 "count_equals" => {
1354 if let Some(val) = &assertion.value {
1355 if let Some(n) = val.as_u64() {
1356 let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1357 let _ = writeln!(out, " expect({length_expr}, equals({n}));");
1358 }
1359 }
1360 }
1361 "count_min" => {
1362 if let Some(val) = &assertion.value {
1363 if let Some(n) = val.as_u64() {
1364 let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1365 let _ = writeln!(out, " expect({length_expr}, greaterThanOrEqualTo({n}));");
1366 }
1367 }
1368 }
1369 "matches_regex" => {
1370 if let Some(expected) = &assertion.value {
1371 let dart_val = format_value(expected);
1372 let _ = writeln!(out, " expect({field_accessor}, matches(RegExp({dart_val})));");
1373 }
1374 }
1375 "is_true" => {
1376 let _ = writeln!(out, " expect({field_accessor}, isTrue);");
1377 }
1378 "is_false" => {
1379 let _ = writeln!(out, " expect({field_accessor}, isFalse);");
1380 }
1381 "greater_than" => {
1382 if let Some(val) = &assertion.value {
1383 let dart_val = format_value(val);
1384 let _ = writeln!(out, " expect({field_accessor}, greaterThan({dart_val}));");
1385 }
1386 }
1387 "less_than" => {
1388 if let Some(val) = &assertion.value {
1389 let dart_val = format_value(val);
1390 let _ = writeln!(out, " expect({field_accessor}, lessThan({dart_val}));");
1391 }
1392 }
1393 "greater_than_or_equal" => {
1394 if let Some(val) = &assertion.value {
1395 let dart_val = format_value(val);
1396 let _ = writeln!(out, " expect({field_accessor}, greaterThanOrEqualTo({dart_val}));");
1397 }
1398 }
1399 "less_than_or_equal" => {
1400 if let Some(val) = &assertion.value {
1401 let dart_val = format_value(val);
1402 let _ = writeln!(out, " expect({field_accessor}, lessThanOrEqualTo({dart_val}));");
1403 }
1404 }
1405 "not_null" => {
1406 let _ = writeln!(out, " expect({field_accessor}, isNotNull);");
1407 }
1408 "not_error" => {
1409 }
1416 "error" => {
1417 }
1419 "method_result" => {
1420 if let Some(method) = &assertion.method {
1421 let dart_method = method.to_lower_camel_case();
1422 let check = assertion.check.as_deref().unwrap_or("not_null");
1423 let method_call = format!("{field_accessor}.{dart_method}()");
1424 match check {
1425 "equals" => {
1426 if let Some(expected) = &assertion.value {
1427 let dart_val = format_value(expected);
1428 let _ = writeln!(out, " expect({method_call}, equals({dart_val}));");
1429 }
1430 }
1431 "is_true" => {
1432 let _ = writeln!(out, " expect({method_call}, isTrue);");
1433 }
1434 "is_false" => {
1435 let _ = writeln!(out, " expect({method_call}, isFalse);");
1436 }
1437 "greater_than_or_equal" => {
1438 if let Some(val) = &assertion.value {
1439 let dart_val = format_value(val);
1440 let _ = writeln!(out, " expect({method_call}, greaterThanOrEqualTo({dart_val}));");
1441 }
1442 }
1443 "count_min" => {
1444 if let Some(val) = &assertion.value {
1445 if let Some(n) = val.as_u64() {
1446 let _ = writeln!(out, " expect({method_call}.length, greaterThanOrEqualTo({n}));");
1447 }
1448 }
1449 }
1450 _ => {
1451 let _ = writeln!(out, " expect({method_call}, isNotNull);");
1452 }
1453 }
1454 }
1455 }
1456 other => {
1457 let _ = writeln!(out, " // skipped: unknown assertion type '{other}'");
1458 }
1459 }
1460}
1461
1462fn render_streaming_assertion_dart(out: &mut String, assertion: &Assertion, result_var: &str) {
1473 match assertion.assertion_type.as_str() {
1474 "not_error" => {
1475 let _ = writeln!(out, " expect({result_var}, isNotNull);");
1479 }
1480 "count_min" if assertion.field.as_deref() == Some("chunks") => {
1481 if let Some(serde_json::Value::Number(n)) = &assertion.value {
1482 let _ = writeln!(out, " expect({result_var}.length, greaterThanOrEqualTo({n}));");
1483 }
1484 }
1485 "equals" if assertion.field.as_deref() == Some("stream_content") => {
1486 if let Some(serde_json::Value::String(expected)) = &assertion.value {
1487 let escaped = escape_dart(expected);
1488 let _ = writeln!(
1489 out,
1490 " final _content = {result_var}.map((c) => c.choices.firstOrNull?.delta.content ?? '').join();"
1491 );
1492 let _ = writeln!(out, " expect(_content, equals('{escaped}'));");
1493 }
1494 }
1495 other => {
1496 let _ = writeln!(out, " // skipped streaming assertion: '{other}'");
1497 }
1498 }
1499}
1500
1501fn snake_to_camel(s: &str) -> String {
1503 let mut result = String::with_capacity(s.len());
1504 let mut next_upper = false;
1505 for ch in s.chars() {
1506 if ch == '_' {
1507 next_upper = true;
1508 } else if next_upper {
1509 result.extend(ch.to_uppercase());
1510 next_upper = false;
1511 } else {
1512 result.push(ch);
1513 }
1514 }
1515 result
1516}
1517
1518fn field_to_dart_accessor(path: &str) -> String {
1531 let mut result = String::with_capacity(path.len());
1532 for (i, segment) in path.split('.').enumerate() {
1533 if i > 0 {
1534 result.push('.');
1535 }
1536 if let Some(bracket_pos) = segment.find('[') {
1542 let name = &segment[..bracket_pos];
1543 let bracket = &segment[bracket_pos..];
1544 result.push_str(&name.to_lower_camel_case());
1545 result.push('!');
1546 result.push_str(bracket);
1547 } else {
1548 result.push_str(&segment.to_lower_camel_case());
1549 }
1550 }
1551 result
1552}
1553
1554fn emit_extraction_config_dart(overrides: &serde_json::Map<String, serde_json::Value>) -> String {
1560 let mut field_overrides: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1562 for (key, val) in overrides {
1563 let camel = snake_to_camel(key);
1564 let dart_val = match val {
1565 serde_json::Value::Bool(b) => {
1566 if *b {
1567 "true".to_string()
1568 } else {
1569 "false".to_string()
1570 }
1571 }
1572 serde_json::Value::Number(n) => n.to_string(),
1573 serde_json::Value::String(s) => format!("'{s}'"),
1574 _ => continue, };
1576 field_overrides.insert(camel, dart_val);
1577 }
1578
1579 let use_cache = field_overrides.remove("useCache").unwrap_or_else(|| "true".to_string());
1580 let enable_quality_processing = field_overrides
1581 .remove("enableQualityProcessing")
1582 .unwrap_or_else(|| "true".to_string());
1583 let force_ocr = field_overrides
1584 .remove("forceOcr")
1585 .unwrap_or_else(|| "false".to_string());
1586 let disable_ocr = field_overrides
1587 .remove("disableOcr")
1588 .unwrap_or_else(|| "false".to_string());
1589 let include_document_structure = field_overrides
1590 .remove("includeDocumentStructure")
1591 .unwrap_or_else(|| "false".to_string());
1592 let use_layout_for_markdown = field_overrides
1593 .remove("useLayoutForMarkdown")
1594 .unwrap_or_else(|| "false".to_string());
1595 let max_archive_depth = field_overrides
1596 .remove("maxArchiveDepth")
1597 .unwrap_or_else(|| "3".to_string());
1598
1599 format!(
1600 "ExtractionConfig(useCache: {use_cache}, enableQualityProcessing: {enable_quality_processing}, forceOcr: {force_ocr}, disableOcr: {disable_ocr}, resultFormat: ResultFormat.unified, outputFormat: OutputFormat.plain(), includeDocumentStructure: {include_document_structure}, useLayoutForMarkdown: {use_layout_for_markdown}, maxArchiveDepth: {max_archive_depth})"
1601 )
1602}
1603
1604struct DartTestClientRenderer {
1620 in_skip: Cell<bool>,
1623 is_redirect: Cell<bool>,
1626}
1627
1628impl DartTestClientRenderer {
1629 fn new(is_redirect: bool) -> Self {
1630 Self {
1631 in_skip: Cell::new(false),
1632 is_redirect: Cell::new(is_redirect),
1633 }
1634 }
1635}
1636
1637impl client::TestClientRenderer for DartTestClientRenderer {
1638 fn language_name(&self) -> &'static str {
1639 "dart"
1640 }
1641
1642 fn render_test_open(&self, out: &mut String, _fn_name: &str, description: &str, skip_reason: Option<&str>) {
1651 let escaped_desc = escape_dart(description);
1652 if let Some(reason) = skip_reason {
1653 let escaped_reason = escape_dart(reason);
1654 let _ = writeln!(out, " test('{escaped_desc}', () {{");
1655 let _ = writeln!(out, " markTestSkipped('{escaped_reason}');");
1656 let _ = writeln!(out, " }});");
1657 let _ = writeln!(out);
1658 self.in_skip.set(true);
1659 } else {
1660 let _ = writeln!(
1661 out,
1662 " test('{escaped_desc}', () => _serialized(() => _withRetry(() async {{"
1663 );
1664 self.in_skip.set(false);
1665 }
1666 }
1667
1668 fn render_test_close(&self, out: &mut String) {
1673 if self.in_skip.get() {
1674 return;
1676 }
1677 let _ = writeln!(out, " }})));");
1678 let _ = writeln!(out);
1679 }
1680
1681 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
1691 const DART_RESTRICTED_HEADERS: &[&str] = &["content-length", "host", "transfer-encoding"];
1693
1694 let method = ctx.method.to_uppercase();
1695 let escaped_method = escape_dart(&method);
1696
1697 let fixture_path = escape_dart(ctx.path);
1699
1700 let has_explicit_content_type = ctx.headers.keys().any(|k| k.to_lowercase() == "content-type");
1702 let effective_content_type = if has_explicit_content_type {
1703 ctx.headers
1704 .iter()
1705 .find(|(k, _)| k.to_lowercase() == "content-type")
1706 .map(|(_, v)| v.as_str())
1707 .unwrap_or("application/json")
1708 } else if ctx.body.is_some() {
1709 ctx.content_type.unwrap_or("application/json")
1710 } else {
1711 ""
1712 };
1713
1714 let _ = writeln!(
1715 out,
1716 " final baseUrl = Platform.environment['MOCK_SERVER_URL'] ?? 'http://localhost:8080';"
1717 );
1718 let _ = writeln!(out, " final uri = Uri.parse('$baseUrl{fixture_path}');");
1719 let _ = writeln!(
1720 out,
1721 " final ioReq = await _httpClient.openUrl('{escaped_method}', uri);"
1722 );
1723
1724 if self.is_redirect.get() {
1727 let _ = writeln!(out, " ioReq.followRedirects = false;");
1728 }
1729
1730 if !effective_content_type.is_empty() {
1732 let escaped_ct = escape_dart(effective_content_type);
1733 let _ = writeln!(out, " ioReq.headers.set('content-type', '{escaped_ct}');");
1734 }
1735
1736 let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
1738 header_pairs.sort_by_key(|(k, _)| k.as_str());
1739 for (name, value) in &header_pairs {
1740 if DART_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
1741 continue;
1742 }
1743 if name.to_lowercase() == "content-type" {
1744 continue; }
1746 let escaped_name = escape_dart(&name.to_lowercase());
1747 let escaped_value = escape_dart(value);
1748 let _ = writeln!(out, " ioReq.headers.set('{escaped_name}', '{escaped_value}');");
1749 }
1750
1751 if !ctx.cookies.is_empty() {
1753 let mut cookie_pairs: Vec<(&String, &String)> = ctx.cookies.iter().collect();
1754 cookie_pairs.sort_by_key(|(k, _)| k.as_str());
1755 let cookie_str: Vec<String> = cookie_pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
1756 let cookie_header = escape_dart(&cookie_str.join("; "));
1757 let _ = writeln!(out, " ioReq.headers.set('cookie', '{cookie_header}');");
1758 }
1759
1760 if let Some(body) = ctx.body {
1762 let json_str = serde_json::to_string(body).unwrap_or_default();
1763 let escaped = escape_dart(&json_str);
1764 let _ = writeln!(out, " final bodyBytes = utf8.encode('{escaped}');");
1765 let _ = writeln!(out, " ioReq.add(bodyBytes);");
1766 }
1767
1768 let _ = writeln!(out, " final ioResp = await ioReq.close();");
1769 if !self.is_redirect.get() {
1773 let _ = writeln!(out, " final bodyStr = await ioResp.transform(utf8.decoder).join();");
1774 };
1775 }
1776
1777 fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
1778 let _ = writeln!(
1779 out,
1780 " expect(ioResp.statusCode, equals({status}), reason: 'status code mismatch');"
1781 );
1782 }
1783
1784 fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
1787 let escaped_name = escape_dart(&name.to_lowercase());
1788 match expected {
1789 "<<present>>" => {
1790 let _ = writeln!(
1791 out,
1792 " expect(ioResp.headers.value('{escaped_name}'), isNotNull, reason: 'header {escaped_name} should be present');"
1793 );
1794 }
1795 "<<absent>>" => {
1796 let _ = writeln!(
1797 out,
1798 " expect(ioResp.headers.value('{escaped_name}'), isNull, reason: 'header {escaped_name} should be absent');"
1799 );
1800 }
1801 "<<uuid>>" => {
1802 let _ = writeln!(
1803 out,
1804 " expect(ioResp.headers.value('{escaped_name}'), matches(RegExp(r'^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$')), reason: 'header {escaped_name} should be a UUID');"
1805 );
1806 }
1807 exact => {
1808 let escaped_value = escape_dart(exact);
1809 let _ = writeln!(
1810 out,
1811 " expect(ioResp.headers.value('{escaped_name}'), contains('{escaped_value}'), reason: 'header {escaped_name} mismatch');"
1812 );
1813 }
1814 }
1815 }
1816
1817 fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
1822 match expected {
1823 serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
1824 let json_str = serde_json::to_string(expected).unwrap_or_default();
1825 let escaped = escape_dart(&json_str);
1826 let _ = writeln!(out, " final bodyJson = jsonDecode(bodyStr);");
1827 let _ = writeln!(out, " final expectedJson = jsonDecode('{escaped}');");
1828 let _ = writeln!(
1829 out,
1830 " expect(bodyJson, equals(expectedJson), reason: 'body mismatch');"
1831 );
1832 }
1833 serde_json::Value::String(s) => {
1834 let escaped = escape_dart(s);
1835 let _ = writeln!(
1836 out,
1837 " expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
1838 );
1839 }
1840 other => {
1841 let escaped = escape_dart(&other.to_string());
1842 let _ = writeln!(
1843 out,
1844 " expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
1845 );
1846 }
1847 }
1848 }
1849
1850 fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
1853 let _ = writeln!(
1854 out,
1855 " final partialJson = jsonDecode(bodyStr) as Map<String, dynamic>;"
1856 );
1857 if let Some(obj) = expected.as_object() {
1858 for (idx, (key, val)) in obj.iter().enumerate() {
1859 let escaped_key = escape_dart(key);
1860 let json_val = serde_json::to_string(val).unwrap_or_default();
1861 let escaped_val = escape_dart(&json_val);
1862 let _ = writeln!(out, " final _expectedField{idx} = jsonDecode('{escaped_val}');");
1865 let _ = writeln!(
1866 out,
1867 " expect(partialJson['{escaped_key}'], equals(_expectedField{idx}), reason: 'partial body field \\'{escaped_key}\\' mismatch');"
1868 );
1869 }
1870 }
1871 }
1872
1873 fn render_assert_validation_errors(
1875 &self,
1876 out: &mut String,
1877 _response_var: &str,
1878 errors: &[ValidationErrorExpectation],
1879 ) {
1880 let _ = writeln!(out, " final errBody = jsonDecode(bodyStr) as Map<String, dynamic>;");
1881 let _ = writeln!(out, " final errList = (errBody['errors'] ?? []) as List<dynamic>;");
1882 for ve in errors {
1883 let loc_dart: Vec<String> = ve.loc.iter().map(|s| format!("'{}'", escape_dart(s))).collect();
1884 let loc_str = loc_dart.join(", ");
1885 let escaped_msg = escape_dart(&ve.msg);
1886 let _ = writeln!(
1887 out,
1888 " expect(errList.any((e) => e is Map && (e['loc'] as List?)?.join(',') == [{loc_str}].join(',') && (e['msg'] as String? ?? '').contains('{escaped_msg}')), isTrue, reason: 'validation error not found: {escaped_msg}');"
1889 );
1890 }
1891 }
1892}
1893
1894fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
1901 if http.expected_response.status_code == 101 {
1903 let description = escape_dart(&fixture.description);
1904 let _ = writeln!(out, " test('{description}', () {{");
1905 let _ = writeln!(
1906 out,
1907 " markTestSkipped('Skipped: Dart HttpClient cannot handle 101 Switching Protocols responses');"
1908 );
1909 let _ = writeln!(out, " }});");
1910 let _ = writeln!(out);
1911 return;
1912 }
1913
1914 let is_redirect = http.expected_response.status_code / 100 == 3;
1918 client::http_call::render_http_test(out, &DartTestClientRenderer::new(is_redirect), fixture);
1919}
1920
1921fn mime_from_extension(path: &str) -> Option<&'static str> {
1926 let ext = path.rsplit('.').next()?;
1927 match ext.to_lowercase().as_str() {
1928 "docx" => Some("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
1929 "xlsx" => Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
1930 "pptx" => Some("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
1931 "pdf" => Some("application/pdf"),
1932 "txt" | "text" => Some("text/plain"),
1933 "html" | "htm" => Some("text/html"),
1934 "json" => Some("application/json"),
1935 "xml" => Some("application/xml"),
1936 "csv" => Some("text/csv"),
1937 "md" | "markdown" => Some("text/markdown"),
1938 "png" => Some("image/png"),
1939 "jpg" | "jpeg" => Some("image/jpeg"),
1940 "gif" => Some("image/gif"),
1941 "zip" => Some("application/zip"),
1942 "odt" => Some("application/vnd.oasis.opendocument.text"),
1943 "ods" => Some("application/vnd.oasis.opendocument.spreadsheet"),
1944 "odp" => Some("application/vnd.oasis.opendocument.presentation"),
1945 "rtf" => Some("application/rtf"),
1946 "epub" => Some("application/epub+zip"),
1947 "msg" => Some("application/vnd.ms-outlook"),
1948 "eml" => Some("message/rfc822"),
1949 _ => None,
1950 }
1951}
1952
1953fn emit_dart_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1960 let items: Vec<String> = arr
1961 .as_array()
1962 .map(|a| a.as_slice())
1963 .unwrap_or_default()
1964 .iter()
1965 .filter_map(|item| {
1966 let obj = item.as_object()?;
1967 match elem_type {
1968 "BatchBytesItem" => {
1969 let content_bytes = obj
1970 .get("content")
1971 .and_then(|v| v.as_array())
1972 .map(|arr| {
1973 let nums: Vec<String> =
1974 arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1975 format!("Uint8List.fromList([{}])", nums.join(", "))
1976 })
1977 .unwrap_or_else(|| "Uint8List(0)".to_string());
1978 let mime_type = obj
1979 .get("mime_type")
1980 .and_then(|v| v.as_str())
1981 .unwrap_or("application/octet-stream");
1982 Some(format!(
1983 "BatchBytesItem(content: {content_bytes}, mimeType: '{}')",
1984 escape_dart(mime_type)
1985 ))
1986 }
1987 "BatchFileItem" => {
1988 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1989 Some(format!("BatchFileItem(path: '{}')", escape_dart(path)))
1990 }
1991 _ => None,
1992 }
1993 })
1994 .collect();
1995 format!("[{}]", items.join(", "))
1996}
1997
1998pub(super) fn escape_dart(s: &str) -> String {
2000 s.replace('\\', "\\\\")
2001 .replace('\'', "\\'")
2002 .replace('\n', "\\n")
2003 .replace('\r', "\\r")
2004 .replace('\t', "\\t")
2005 .replace('$', "\\$")
2006}
2007
2008fn type_name_to_create_from_json_dart(type_name: &str) -> String {
2016 let mut snake = String::with_capacity(type_name.len() + 8);
2018 for (i, ch) in type_name.char_indices() {
2019 if ch.is_uppercase() {
2020 if i > 0 {
2021 snake.push('_');
2022 }
2023 snake.extend(ch.to_lowercase());
2024 } else {
2025 snake.push(ch);
2026 }
2027 }
2028 let rust_fn = format!("create_{snake}_from_json");
2031 rust_fn
2033 .split('_')
2034 .enumerate()
2035 .map(|(i, part)| {
2036 if i == 0 {
2037 part.to_string()
2038 } else {
2039 let mut chars = part.chars();
2040 match chars.next() {
2041 None => String::new(),
2042 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
2043 }
2044 }
2045 })
2046 .collect::<Vec<_>>()
2047 .join("")
2048}