Skip to main content

alef_e2e/codegen/
dart.rs

1//! Dart e2e test generator using package:test and package:http.
2//!
3//! Generates `e2e/dart/test/<category>_test.dart` files from JSON fixtures.
4//! HTTP fixtures hit the mock server at `MOCK_SERVER_URL/fixtures/<id>`.
5//! Non-HTTP fixtures without a dart-specific call override emit a skip stub.
6
7use 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
25/// Dart e2e code generator.
26pub 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        // Resolve package config.
43        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        // Generate pubspec.yaml with http dependency for HTTP client tests.
62        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        // Generate dart_test.yaml to limit parallelism — the mock server uses keep-alive
69        // connections and gets overwhelmed when test files run in parallel.
70        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        // One test file per fixture group.
85        let bridge_class = config.dart_bridge_class_name();
86
87        // FRB places its generated dart code under `lib/src/{module_name}_bridge_generated/`,
88        // where `module_name` is the snake_cased crate name (e.g. `html_to_markdown_rs`).
89        // This is independent of the pubspec `name` (which may be a short alias like `h2m`).
90        let frb_module_name = config.name.replace('-', "_");
91
92        // Methods declared as `stub_methods` in `[crates.dart]` cannot be bridged through
93        // FRB and have `unimplemented!()` bodies on the Rust side. Emitting e2e tests for
94        // these fixtures would result in `PanicException` at run-time. Filter them out
95        // here so the dart e2e suite mirrors the actual runtime surface of the binding.
96        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
154// ---------------------------------------------------------------------------
155// Rendering
156// ---------------------------------------------------------------------------
157
158fn 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    // Suppress unused_local_variable: `final result = await api.method(...)` is
207    // emitted for every test case; tests that only check for absence of errors
208    // do not consume `result`, triggering this dart-analyze warning.
209    out.push_str("// ignore_for_file: unused_local_variable\n\n");
210
211    // Check if any fixture needs the http package (HTTP server tests).
212    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
213
214    // Check if any fixture needs Uint8List.fromList (batch item byte arrays).
215    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    // Detect whether any fixture uses file_path or bytes args — if so, setUpAll must chdir
224    // to the test_documents directory so that relative paths like "docx/fake.docx" resolve.
225    // Mirrors the Ruby/Python conftest and Swift setUp patterns.
226    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    // Detect whether any non-HTTP fixture uses a json_object arg that resolves to a JSON array —
239    // those are materialized via `jsonDecode` at test-run time and cast to `List<String>`.
240    // Handle args themselves no longer require `jsonDecode` since they construct the config via
241    // the FRB-generated `createCrawlConfigFromJson(json:)` helper which accepts the JSON string
242    // directly. The variable name is kept as `has_handle_args` for downstream stability.
243    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    // Non-HTTP fixtures that build a mock-server URL still reference `Platform.environment`
256    // (from `dart:io`). This applies to `mock_url` args and to fixtures routed through a
257    // `client_factory` (per-call override or per-language override) that derives `_mockUrl`
258    // inline. Without this, the generated tests fail to compile with
259    // `Error: Undefined name 'Platform'`.
260    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    // `dart:io` provides HttpClient/SocketException (HTTP fixtures), Platform/Directory
290    // (file-path/bytes fixtures requiring chdir), and Platform.environment (mock-url
291    // fixtures). Skip the import when none of these are in play — unconditional emission
292    // triggers `unused_import` warnings.
293    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    // RustLib is the flutter_rust_bridge entrypoint; must be initialized before any FRB call.
301    // FRB places its generated dart sources under `lib/src/{module_name}_bridge_generated/`,
302    // where `module_name` is the snake_cased crate name (independent of the pubspec `name`,
303    // which may be a short alias like `h2m`). `RustLib` lives in `frb_generated.dart` and
304    // is not re-exported by the FRB barrel `lib.dart`, so we import it directly.
305    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    // dart:convert provides jsonDecode for handle-arg engine construction and HTTP response parsing.
313    if has_http_fixtures || has_handle_args {
314        let _ = writeln!(out, "import 'dart:convert';");
315    }
316    let _ = writeln!(out);
317
318    // Emit file-level HTTP client and serialization mutex.
319    //
320    // The shared HttpClient reuses keep-alive connections to minimize TCP overhead.
321    // The mutex (_lock) ensures requests are serialized within the file so the
322    // connection pool is not exercised concurrently by dart:test's async runner.
323    //
324    // _withRetry wraps the entire request closure with one automatic retry on
325    // transient connection errors (keep-alive connections can be silently closed
326    // by the server just as the client tries to reuse them).
327    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        // The `fn` here should be the full request closure — on socket failure we
345        // recreate the HttpClient (drops old pooled connections) and retry once.
346        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    // Emit a helper function to normalize enum values to their serde wire format.
366    // Dart enums' .toString() returns "EnumName.variant" but fixtures use serde wire format
367    // (e.g. "stop" for FinishReason.stop, "tool_calls" for FinishReason.toolCalls).
368    // This helper handles enum-to-wire conversion by calling .name (which gives the Dart
369    // variant name like "toolCalls") and converting back to snake_case for multi-word variants.
370    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    // Helper to convert camelCase to snake_case.
398    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    // Emit setUpAll to initialize the flutter_rust_bridge before any test runs and,
416    // when fixtures load files by path, chdir to test_documents so that relative
417    // paths like "docx/fake.docx" resolve correctly.
418    //
419    // The test_documents directory lives two levels above e2e/dart/ (at the repo root).
420    // The FIXTURES_DIR environment variable can override this for CI environments.
421    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    // Close the shared client after all tests in this file complete.
436    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    // HTTP fixtures: hit the mock server.
451    if let Some(http) = &fixture.http {
452        render_http_test_case(out, fixture, http);
453        return;
454    }
455
456    // Non-HTTP fixtures: render a call-based test using the resolved call config.
457    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    // Build per-call field resolver using the effective field sets for this call.
465    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    // Merge per-language enum_fields from the Dart override into the effective enum set so that
476    // fields like "status" (BatchStatus on BatchObject) are treated as enum-typed
477    // even when they are not globally listed in fields_enum (they are context-
478    // dependent — BatchStatus on BatchObject but plain String on ResponseObject).
479    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    // Convert snake_case function names to camelCase for Dart conventions.
496    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    // `is_async` retained for future use (e.g. non-FRB backends); unused with FRB since
516    // all wrappers return Future<T>.
517    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    // `result_is_simple = true` means the dart return is a scalar/bytes value
522    // (e.g. `Uint8List` for speech/file_content), not a struct. Field-based
523    // assertions like `audio.not_empty` collapse to whole-result checks so we
524    // don't emit `result.audio` against a `Uint8List` receiver.
525    let result_is_simple = call_overrides.is_some_and(|o| o.result_is_simple) || call_config.result_is_simple;
526
527    // Resolve options_type and options_via from per-fixture → per-call → default.
528    // These drive how `json_object` args are constructed:
529    //   options_via = "from_json" — call `createTypeNameFromJson(json: r'...')` bridge
530    //                               helper and pass the result as a named parameter `req:`.
531    //   All other values (or absent) — existing behaviour (batch arrays, config objects,
532    //   generic JSON arrays, or nothing).
533    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    // Build argument list from fixture.input and call_config.args.
539    // Use `resolve_field` (respects the `field` path like "input.data") rather than
540    // looking up by `arg_def.name` directly — the name and the field key may differ.
541    //
542    // For `extract_file_sync` / `extract_file` fixtures that omit `mime_type`,
543    // derive the MIME from the path extension so `extractBytesSync`/`extractBytes`
544    // can be called (both require an explicit MIME type).
545    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    // Detect whether this call converts a file_path arg to bytes at test-run time.
552    // Dart cannot pass OS-level file paths through the FRB bridge — the idiomatic API
553    // is always bytes. When a file_path arg is present (and no caller-supplied dart
554    // function override has already been applied), remap the function name:
555    //   extractFile      → extractBytes
556    //   extractFileSync  → extractBytesSync
557    let has_file_path_arg = call_config.args.iter().any(|a| a.arg_type == "file_path");
558    // Apply the remap only when no per-fixture dart override has already specified the
559    // function — if the fixture author set a dart-specific function name we trust it.
560    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    // setup_lines holds per-test statements that must precede the main call:
570    // engine construction (handle args) and URL building (mock_url args).
571    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                // Derive the create-function name: "engine" → "createEngine".
596                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                    // FRB-generated free function: `createCrawlConfigFromJson(json: '...')` — async,
612                    // deserializes the JSON into the mirror struct via the Rust `create_<type>_from_json`
613                    // helper emitted by the dart backend. This avoids relying on a Dart-side `fromJson`
614                    // constructor (FRB classes don't expose one).
615                    setup_lines.push(format!(
616                        "final {config_var} = await createCrawlConfigFromJson(json: r'{json_str}');"
617                    ));
618                    // Facade exposes `createEngine` with a named `config:` parameter — call it that way.
619                    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                // `bytes`: value is a file path string; load file contents at test-run time.
633                // `file_path`: also loaded as bytes for dart — extractBytes/extractBytesSync is
634                // the idiomatic Dart API since the Dart runtime cannot pass OS-level file paths
635                // through the FFI bridge.
636                if let serde_json::Value::String(file_path) = arg_value {
637                    args.push(format!("File('{}').readAsBytesSync()", file_path));
638                }
639            }
640            "string" => {
641                // FRB-generated Dart methods take named parameters across the board
642                // (e.g. `retrieveResponse({required String responseId})`), and even
643                // required parameters appear as named in the v2 ABI. Always emit the
644                // call site with `name: value` so generated tests compile against the
645                // FRB-emitted binding. Repos with hand-written positional wrappers
646                // should declare their alternative signature via a per-call override.
647                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                        // Optional string absent from fixture — try to infer MIME from path
656                        // when the arg name looks like a MIME-type parameter.
657                        && 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                    // Other optional strings with null value are omitted.
665                    _ => {}
666                }
667            }
668            "json_object" => {
669                // Handle batch item arrays (BatchBytesItem / BatchFileItem).
670                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                        // Scalar string array (e.g. `texts: ["a", "b"]` for embed_texts).
676                        // The `KreuzbergBridge` facade declares these parameters as required
677                        // positional (e.g. `embedTexts(List<String> texts, EmbeddingConfig config)`),
678                        // so the list literal must be passed positionally — matching the
679                        // facade contract rather than the underlying FRB bridge's named-arg
680                        // convention.
681                        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                    // `from_json` path: construct a typed mirror-struct via the generated
692                    // `create<TypeName>FromJson(json: '...')` bridge helper, then pass it
693                    // as the named FRB parameter `req: _var`.
694                    //
695                    // The helper is generated by `emit_from_json_fn` in the dart bridge-crate
696                    // generator and made available as a top-level function via the exported
697                    // `liter_llm_bridge_generated/lib.dart`. The parameter name used in the
698                    // bridge method call is always `req:` for single-request-object methods
699                    // (derived from the Rust IR param name).
700                    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                            // Escape for Dart single-quoted string literal (handles embedded quotes,
704                            // backslashes, and interpolation markers).
705                            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                            // FRB bridge method param name is `req` for all single-request methods.
710                            // Use `req:` as the named argument label.
711                            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                            // When the call override specifies a non-default `options_type`
718                            // (e.g. `EmbeddingConfig` for `embed_texts`), or the override map
719                            // contains a non-scalar field that the literal `ExtractionConfig`
720                            // constructor cannot express (e.g. `output_format: "markdown"` is
721                            // a tagged enum, not a plain string), fall back to the
722                            // FRB-generated `create<Type>FromJson(json: '...')` helper which
723                            // round-trips the JSON through serde and so preserves enum tags,
724                            // nested configs, and string-valued enum variants verbatim.
725                            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                                // Fixture provides scalar-only overrides — build an
746                                // `ExtractionConfig` constructor literal with defaults,
747                                // overriding only the bool/int fields present in the
748                                // fixture JSON. Handles configs such as
749                                // {force_ocr:true, disable_ocr:true} that toggle error paths.
750                                args.push(emit_extraction_config_dart(map));
751                            }
752                        }
753                    }
754                    // If config is null/absent, the wrapper supplies the default ExtractionConfig.
755                } else if arg_value.is_array() {
756                    // Generic JSON array (e.g. batch_urls: ["/page1", "/page2"]).
757                    // Decode via jsonDecode and cast to List<String> at test-run time.
758                    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                    // Generic options-style json_object arg (e.g. h2m's
766                    // `options: ConversionOptions` on `convert(html, options)`). When the
767                    // fixture provides input.options and the call config declares an
768                    // `options_type`, build the mirror struct via the FRB-generated
769                    // `create<OptionsType>FromJson(json: '...')` helper. Use the arg's
770                    // original name (e.g. `options`) as the named parameter label.
771                    //
772                    // When the fixture also carries a visitor spec, swap to the
773                    // `create<OptionsType>FromJsonWithVisitor(json, visitor)` helper
774                    // (emitted by `alef-backend-dart` for trait bridges with `type_alias`
775                    // + `options_field` binding). The `_visitor` variable is materialised
776                    // in the visitor block below — its setup line is inserted ahead of
777                    // this options call by `build_dart_visitor`.
778                    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    // Fixture-driven visitor handle. When `fixture.visitor` is set we build a
807    // `_visitor` via the `createHtmlVisitor(...)` factory (emitted by
808    // `alef-backend-dart`'s trait-bridge generator in the `type_alias` mode)
809    // and thread it into the options blob via the
810    // `create<OptionsType>FromJsonWithVisitor(json, visitor)` helper (handled
811    // a few lines above in the json_object arg branch).
812    //
813    // The visitor setup line is INSERTED at the front of `setup_lines` so
814    // `_visitor` is defined before any `_options` line that references it.
815    // Fixtures without an `options` json_object in input still need an options
816    // blob to carry the visitor through to convert — we synthesise an empty-
817    // options call to `createConversionOptionsFromJsonWithVisitor(json: '{}',
818    // visitor: _visitor)` here when no `options` arg was emitted in the loop
819    // above.
820    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        // Prepend the visitor block so `_visitor` is in scope by the time the
824        // options call (which may reference it) runs.
825        for line in visitor_setup.into_iter().rev() {
826            setup_lines.insert(0, line);
827        }
828
829        // If no `options` arg was emitted by the loop above (the fixture has no
830        // input.options block), build an empty options-with-visitor and add it as
831        // an `options:` named arg so the visitor reaches the convert call.
832        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    // Resolve client_factory: when set, tests create a client instance and call
845    // methods on it rather than using static bridge-class calls. This mirrors the
846    // go/python/zig pattern for stateful clients (e.g. liter-llm).
847    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    // Convert factory name to camelCase (same rule as function_name above).
856    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    // All bridge methods return Future<T> because FRB v2 wraps every Rust
875    // function as async in Dart — even "sync" Rust functions. Always emit an async
876    // test body and await the call so the test framework waits for the future.
877    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    // When client_factory is set, determine the mock URL and emit client instantiation.
886    // The mock URL derivation follows the same has_host_root_route / plain-fixture split
887    // used by the mock_url arg handler above.
888    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            // No explicit mock_url arg — derive the URL inline.
892            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            // A mock_url arg was emitted into setup_lines already — reuse the variable name
907            // from the first mock_url arg definition so we don't duplicate the URL.
908            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        // Wrap setup + call in an async lambda so any exception at any step is caught.
930        // flutter_rust_bridge 2.x decodes Rust errors as raw String values (not Exception
931        // subtypes), so throwsException will not match. Use throwsA(anything) instead.
932        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        // No setup lines, direct call — same throwsA(anything) rationale as above.
949        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
1005/// Render `.length` / `?.length ?? 0` against a Dart field accessor.
1006///
1007/// Count-style assertions (`count_equals`, `count_min`, `min_length`, `max_length`)
1008/// operate on collection-typed fields. FRB v2 maps `Option<Vec<T>>` to `List<T>?`
1009/// (nullable) but `Vec<T>` to `List<T>` (non-null). Emitting `?.length ?? 0`
1010/// against a non-null receiver triggers `invalid_null_aware_operator`. Inspect
1011/// the IR via `FieldResolver::is_optional` and choose the safe form per field.
1012fn 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
1036/// Render a single fixture assertion as a Dart `package:test` `expect(...)` call.
1037///
1038/// Field paths are converted per-segment to camelCase (FRB v2 convention) using
1039/// [`field_to_dart_accessor`].  All 24 fixture assertion types are handled.
1040///
1041/// Assertions on fixture fields that are not in the configured `result_fields` set
1042/// are emitted as a `// skipped:` comment instead — the Dart binding may model a
1043/// different result shape than the fixture asserts on (e.g. flat `ScrapeResult` vs.
1044/// nested `result.browser.*`), and emitting unresolvable getters would break the
1045/// whole file at compile time.
1046fn 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    // Skip assertions on fields that don't exist on the dart result type. This must run
1055    // BEFORE the array-traversal and standard accessor paths since both emit code that
1056    // references the field — an unknown field path produces an `isn't defined` error.
1057    if !result_is_simple {
1058        if let Some(f) = assertion.field.as_deref() {
1059            // Use the head segment (before any `[].`) for validation since `is_valid_for_result`
1060            // only checks the first path component.
1061            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    // Skip assertions that traverse a tagged-union variant boundary. FRB exposes
1070    // tagged unions like `FormatMetadata` as sealed classes whose variants are
1071    // accessed via pattern matching (`switch (m) { case FormatMetadata_Excel ... }`)
1072    // — there is no `.excel?` getter, so the fixture path cannot be expressed as
1073    // a simple chained accessor without language-specific pattern-matching codegen.
1074    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    // Handle array traversal (e.g. "links[].link_type" → any() expression).
1085    if let Some(f) = assertion.field.as_deref() {
1086        if let Some(dot) = f.find("[].") {
1087            // Apply the alias mapping to the full `xxx[].yyy` path first so renamed
1088            // sub-fields (e.g. `assets[].category` → `assets[].asset_category`) resolve
1089            // correctly. Split *after* resolving so both the array head and the element
1090            // path reflect any alias rewrites.
1091            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                // Resolver mapped the path away from `[].` form — fall back to the original
1095                // split, since downstream code expects the array/elem structure.
1096                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        // Whole-result assertion path: the dart return is a scalar (e.g. a
1161        // `Uint8List` for speech/file_content), so any `field` on the
1162        // assertion resolves to the whole value rather than a sub-accessor.
1163        result_var.to_string()
1164    } else {
1165        match assertion.field.as_deref() {
1166            // Use the shared accessor builder (`FieldResolver::accessor`) — it applies the
1167            // alias mapping (e.g. `robots.is_allowed` → `is_allowed`), expands array
1168            // segments to `[0]` lookups, and injects `!` after optional intermediates so
1169            // chained access compiles under sound null safety.
1170            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                // Check if this field is an enum field. Enum fields need _alefE2eText for serde
1182                // wire format conversion (e.g. FinishReason.toolCalls → "tool_calls").
1183                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                // Match the rust codegen's behaviour: trim both sides for string equality
1193                // so trailing-newline differences between h2m's emitted markdown and the
1194                // fixture's expected value don't produce false positives.
1195                if expected.is_string() {
1196                    if is_enum_field {
1197                        // For enum fields, use _alefE2eText to normalize the enum value to its
1198                        // serde wire format before comparison.
1199                        let _ = writeln!(
1200                            out,
1201                            "    expect(_alefE2eText({field_accessor}).trim(), equals({dart_val}.toString().trim()));"
1202                        );
1203                    } else {
1204                        // When result_is_simple is true and the field_accessor is nullable (e.g. String?),
1205                        // use null-coalescing operator (?? '') to handle null gracefully.
1206                        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                // Check if this field is an enum field.
1231                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                        // When result_is_simple is true and the field_accessor is nullable (e.g. String?),
1248                        // use null-coalescing operator (?? '') to handle null gracefully.
1249                        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            // `isNotEmpty` only applies to types with a `.isEmpty` getter (collections,
1306            // strings, maps). For struct-shaped fields (e.g. `document: DocumentStructure`)
1307            // we instead assert the value is non-null — those types have no notion of
1308            // "empty" and the fixture intent is "the field is present".
1309            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            // FRB models `Option<String>` / `Option<Vec<T>>` as nullable in Dart. The `isEmpty`
1321            // matcher throws `NoSuchMethodError` on `null`. Accept `null` as semantically
1322            // empty by combining `isNull` with `isEmpty` via `anyOf`.
1323            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            // The `await` already guarantees no thrown error reaches this point — if
1410            // the call throws, the test fails before reaching here. Don't emit
1411            // `expect(result, isNotNull)`: for void-returning trait-bridge fns
1412            // (clear_*) Dart rejects `expect(<void>, ...)` with "expression has type
1413            // 'void' and can't be used". The implicit exception handling proves
1414            // success.
1415        }
1416        "error" => {
1417            // Handled at the test method level via throwsA(anything).
1418        }
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
1462/// Render a single fixture assertion for a streaming result.
1463///
1464/// `result_var` is the `List<T>` collected via `.toList()` on the stream.
1465/// Supports:
1466/// - `not_error`: `expect(result, isNotNull)` (a thrown error would already fail
1467///   the test; the explicit expect keeps the test body non-empty).
1468/// - `count_min` with `field = "chunks"`: assert `result_var.length >= value`.
1469/// - `equals` with `field = "stream_content"`: concatenate `delta.content` and compare.
1470///
1471/// Other assertion types are emitted as comments.
1472fn render_streaming_assertion_dart(out: &mut String, assertion: &Assertion, result_var: &str) {
1473    match assertion.assertion_type.as_str() {
1474        "not_error" => {
1475            // `.toList()` would have thrown to fail the test on error; emit an
1476            // explicit `expect` so the test body isn't empty and the collected
1477            // stream variable is consumed.
1478            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
1501/// Converts a snake_case JSON key to Dart camelCase.
1502fn 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
1518/// Convert a dot-separated fixture field path to a Dart accessor expression.
1519///
1520/// Each segment is converted to camelCase (FRB v2 convention); array-index brackets
1521/// (e.g. `choices[0]`) and map-key brackets (e.g. `tags[name]`) are preserved.
1522/// This replaces the former single-pass `snake_to_camel` call which incorrectly
1523/// treated the entire path string as one identifier.
1524///
1525/// Examples:
1526/// - `"choices"` → `"choices"`
1527/// - `"choices[0].message.content"` → `"choices[0].message.content"`
1528/// - `"metadata.document_title"` → `"metadata.documentTitle"`
1529/// - `"model_id"` → `"modelId"`
1530fn 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        // Separate a trailing `[...]` bracket from the field name so we only
1537        // camelCase the identifier part, not the bracket content. The owning
1538        // collection may be `List<T>?` when the underlying Rust field is
1539        // `Option<Vec<T>>`; force-unwrap with `!` so the `[N]` lookup and any
1540        // subsequent member access compile under sound null safety.
1541        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
1554/// Emits a Dart `ExtractionConfig(...)` constructor with default values, overriding
1555/// fields present in `overrides` (from fixture JSON, snake_case keys).
1556///
1557/// Only simple scalar overrides (bool, int) are supported. Complex nested types
1558/// (ocr, chunking, etc.) are left at their defaults (null).
1559fn emit_extraction_config_dart(overrides: &serde_json::Map<String, serde_json::Value>) -> String {
1560    // Collect scalar overrides; convert keys to camelCase.
1561    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, // skip complex nested objects
1575        };
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
1604// ---------------------------------------------------------------------------
1605// HTTP server test rendering — DartTestClientRenderer impl + thin driver wrapper
1606// ---------------------------------------------------------------------------
1607
1608/// Renderer that emits `package:test` `test(...)` blocks using `dart:io HttpClient`
1609/// against the mock server (`Platform.environment['MOCK_SERVER_URL']`).
1610///
1611/// Skipped tests are emitted as self-contained stubs (complete test block with
1612/// `markTestSkipped`) entirely inside `render_test_open`. `render_test_close` uses
1613/// `in_skip` to emit the right closing token: nothing extra for skip stubs (already
1614/// closed) vs. `})));` for regular tests.
1615///
1616/// `is_redirect` must be set to `true` before invoking the shared driver for 3xx
1617/// fixtures so that `render_call` can inject `ioReq.followRedirects = false` after
1618/// the `openUrl` call.
1619struct DartTestClientRenderer {
1620    /// Set to `true` when `render_test_open` is called with a skip reason so that
1621    /// `render_test_close` can match the opening shape.
1622    in_skip: Cell<bool>,
1623    /// Pre-set to `true` by the thin wrapper when the fixture expects a 3xx response.
1624    /// `render_call` injects `ioReq.followRedirects = false` when this is `true`.
1625    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    /// Emit the test opening.
1643    ///
1644    /// For skipped fixtures: emit the entire self-contained stub (open + body +
1645    /// close + blank line) and set `in_skip = true` so `render_test_close` is a
1646    /// no-op.
1647    ///
1648    /// For active fixtures: emit `test('desc', () => _serialized(() => _withRetry(() async {`
1649    /// leaving the block open for the assertion primitives.
1650    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    /// Emit the test closing token.
1669    ///
1670    /// No-op for skip stubs (the stub was fully closed in `render_test_open`).
1671    /// Emits `})));` followed by a blank line for regular tests.
1672    fn render_test_close(&self, out: &mut String) {
1673        if self.in_skip.get() {
1674            // Stub was already closed in render_test_open.
1675            return;
1676        }
1677        let _ = writeln!(out, "  }})));");
1678        let _ = writeln!(out);
1679    }
1680
1681    /// Emit the full `dart:io HttpClient` request scaffolding.
1682    ///
1683    /// Emits:
1684    /// - URL construction from `MOCK_SERVER_URL`.
1685    /// - `_httpClient.openUrl(method, uri)`.
1686    /// - `followRedirects = false` when `is_redirect` is pre-set on the renderer.
1687    /// - Content-Type header, request headers, cookies, optional body bytes.
1688    /// - `ioReq.close()` → `ioResp`.
1689    /// - Response-body drain into `bodyStr` (skipped for redirect responses).
1690    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
1691        // dart:io restricted headers (handled automatically by the HTTP stack).
1692        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        // Fixture path is `/fixtures/<id>` — extract the id portion for URL construction.
1698        let fixture_path = escape_dart(ctx.path);
1699
1700        // Determine effective content-type.
1701        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        // Disable automatic redirect following for 3xx fixtures so the test can
1725        // assert on the redirect status code itself.
1726        if self.is_redirect.get() {
1727            let _ = writeln!(out, "    ioReq.followRedirects = false;");
1728        }
1729
1730        // Set content-type header.
1731        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        // Set request headers (skip dart:io restricted headers and content-type, already handled).
1737        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; // Already handled above.
1745            }
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        // Add cookies.
1752        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        // Write body bytes if present (bypass charset-based encoding issues).
1761        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        // Drain the response body to bind `bodyStr` for assertion primitives and to
1770        // allow the server to cleanly close the connection (prevents RST packets).
1771        // Redirect responses have no body to drain — skip to avoid a potential hang.
1772        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    /// Emit a single header assertion, handling special tokens `<<present>>`,
1785    /// `<<absent>>`, and `<<uuid>>`.
1786    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    /// Emit an exact-equality body assertion.
1818    ///
1819    /// String bodies are compared as decoded text; structured JSON bodies are
1820    /// compared via `jsonDecode`.
1821    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    /// Emit partial-body assertions — every key in `expected` must match the
1851    /// corresponding field in the parsed JSON response.
1852    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                // Use an index-based variable name so keys with special characters
1863                // don't produce invalid Dart identifiers.
1864                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    /// Emit validation-error assertions for 422 responses.
1874    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
1894/// Render a `package:test` `test(...)` block for an HTTP server fixture.
1895///
1896/// Delegates to the shared [`client::http_call::render_http_test`] driver via
1897/// [`DartTestClientRenderer`]. HTTP 101 (WebSocket upgrade) fixtures are emitted
1898/// as skip stubs before reaching the driver because `dart:io HttpClient` cannot
1899/// handle protocol-switch responses.
1900fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
1901    // HTTP 101 (WebSocket upgrade) — dart:io HttpClient cannot handle upgrade responses.
1902    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    // Pre-set `is_redirect` on the renderer so `render_call` can inject
1915    // `ioReq.followRedirects = false` for 3xx fixtures. The shared driver has no
1916    // concept of expected status code so we thread it through renderer state.
1917    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
1921/// Infer a MIME type from a file path extension.
1922///
1923/// Returns `None` when the extension is unknown so the caller can supply a fallback.
1924/// Used in dart e2e tests when a fixture omits `mime_type` but uses a `file_path` arg.
1925fn 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
1953/// Emit Dart constructors for a batch item array (`BatchBytesItem` or `BatchFileItem`).
1954///
1955/// Returns a Dart list literal like:
1956/// ```dart
1957/// [BatchBytesItem(content: Uint8List.fromList([72, 101, ...]), mimeType: 'text/plain')]
1958/// ```
1959fn 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
1998/// Escape a string for embedding in a Dart single-quoted string literal.
1999pub(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
2008/// Derive the Dart top-level helper function name for constructing a mirror type from JSON.
2009///
2010/// The alef dart bridge-crate generator emits a Rust free function
2011/// `create_<snake_type>_from_json(json: String)` for each non-opaque mirror struct.
2012/// FRB generates the corresponding Dart function as `createTypeNameFromJson` (camelCase).
2013///
2014/// Example: `"ChatCompletionRequest"` → `"createChatCompletionRequestFromJson"`.
2015fn type_name_to_create_from_json_dart(type_name: &str) -> String {
2016    // Convert PascalCase type name to snake_case.
2017    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    // snake is now e.g. "chat_completion_request"
2029    // Full Rust function name: "create_chat_completion_request_from_json"
2030    let rust_fn = format!("create_{snake}_from_json");
2031    // Convert to Dart camelCase: "createChatCompletionRequestFromJson"
2032    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}