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    ) -> Result<Vec<GeneratedFile>> {
36        let lang = self.language_name();
37        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
38
39        let mut files = Vec::new();
40
41        // Resolve package config.
42        let dart_pkg = e2e_config.resolve_package("dart");
43        let pkg_name = dart_pkg
44            .as_ref()
45            .and_then(|p| p.name.as_ref())
46            .cloned()
47            .unwrap_or_else(|| config.dart_pubspec_name());
48        let pkg_path = dart_pkg
49            .as_ref()
50            .and_then(|p| p.path.as_ref())
51            .cloned()
52            .unwrap_or_else(|| "../../packages/dart".to_string());
53        let pkg_version = dart_pkg
54            .as_ref()
55            .and_then(|p| p.version.as_ref())
56            .cloned()
57            .or_else(|| config.resolved_version())
58            .unwrap_or_else(|| "0.1.0".to_string());
59
60        // Generate pubspec.yaml with http dependency for HTTP client tests.
61        files.push(GeneratedFile {
62            path: output_base.join("pubspec.yaml"),
63            content: render_pubspec(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
64            generated_header: false,
65        });
66
67        // Generate dart_test.yaml to limit parallelism — the mock server uses keep-alive
68        // connections and gets overwhelmed when test files run in parallel.
69        files.push(GeneratedFile {
70            path: output_base.join("dart_test.yaml"),
71            content: concat!(
72                "# Generated by alef — DO NOT EDIT.\n",
73                "# Run test files sequentially to avoid overwhelming the mock server with\n",
74                "# concurrent keep-alive connections.\n",
75                "concurrency: 1\n",
76            )
77            .to_string(),
78            generated_header: false,
79        });
80
81        let test_base = output_base.join("test");
82
83        // One test file per fixture group.
84        let bridge_class = config.dart_bridge_class_name();
85
86        // FRB places its generated dart code under `lib/src/{module_name}_bridge_generated/`,
87        // where `module_name` is the snake_cased crate name (e.g. `html_to_markdown_rs`).
88        // This is independent of the pubspec `name` (which may be a short alias like `h2m`).
89        let frb_module_name = config.name.replace('-', "_");
90
91        // Methods declared as `stub_methods` in `[crates.dart]` cannot be bridged through
92        // FRB and have `unimplemented!()` bodies on the Rust side. Emitting e2e tests for
93        // these fixtures would result in `PanicException` at run-time. Filter them out
94        // here so the dart e2e suite mirrors the actual runtime surface of the binding.
95        let dart_stub_methods: std::collections::HashSet<String> = config
96            .dart
97            .as_ref()
98            .map(|d| d.stub_methods.iter().cloned().collect())
99            .unwrap_or_default();
100
101        for group in groups {
102            let active: Vec<&Fixture> = group
103                .fixtures
104                .iter()
105                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
106                .filter(|f| {
107                    let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
108                    let resolved_function = call_config
109                        .overrides
110                        .get(lang)
111                        .and_then(|o| o.function.as_ref())
112                        .cloned()
113                        .unwrap_or_else(|| call_config.function.clone());
114                    !dart_stub_methods.contains(&resolved_function)
115                })
116                .collect();
117
118            if active.is_empty() {
119                continue;
120            }
121
122            let filename = format!("{}_test.dart", sanitize_filename(&group.category));
123            let content = render_test_file(
124                &group.category,
125                &active,
126                e2e_config,
127                lang,
128                &pkg_name,
129                &frb_module_name,
130                &bridge_class,
131            );
132            files.push(GeneratedFile {
133                path: test_base.join(filename),
134                content,
135                generated_header: true,
136            });
137        }
138
139        Ok(files)
140    }
141
142    fn language_name(&self) -> &'static str {
143        "dart"
144    }
145}
146
147// ---------------------------------------------------------------------------
148// Rendering
149// ---------------------------------------------------------------------------
150
151fn render_pubspec(
152    pkg_name: &str,
153    pkg_path: &str,
154    pkg_version: &str,
155    dep_mode: crate::config::DependencyMode,
156) -> String {
157    let test_ver = pub_dev::TEST_PACKAGE;
158    let http_ver = pub_dev::HTTP_PACKAGE;
159
160    let dep_block = match dep_mode {
161        crate::config::DependencyMode::Registry => {
162            format!("  {pkg_name}: ^{pkg_version}")
163        }
164        crate::config::DependencyMode::Local => {
165            format!("  {pkg_name}:\n    path: {pkg_path}")
166        }
167    };
168
169    let sdk = alef_core::template_versions::toolchain::DART_SDK_CONSTRAINT;
170    format!(
171        r#"name: e2e_dart
172version: 0.1.0
173publish_to: none
174
175environment:
176  sdk: "{sdk}"
177
178dependencies:
179{dep_block}
180
181dev_dependencies:
182  test: {test_ver}
183  http: {http_ver}
184"#
185    )
186}
187
188fn render_test_file(
189    category: &str,
190    fixtures: &[&Fixture],
191    e2e_config: &E2eConfig,
192    lang: &str,
193    pkg_name: &str,
194    frb_module_name: &str,
195    bridge_class: &str,
196) -> String {
197    let mut out = String::new();
198    out.push_str(&hash::header(CommentStyle::DoubleSlash));
199
200    // Build the field resolver from the e2e config so assertion rendering can validate
201    // fixture field paths against the configured result type — assertions on fields that
202    // don't exist on the result type are emitted as `// skipped:` comments rather than
203    // compile-time errors. Mirrors the Python/Go/Java/TypeScript codegen pattern.
204    let field_resolver = FieldResolver::new(
205        &e2e_config.fields,
206        &e2e_config.fields_optional,
207        &e2e_config.result_fields,
208        &e2e_config.fields_array,
209        &e2e_config.fields_method_calls,
210    );
211
212    // Check if any fixture needs the http package (HTTP server tests).
213    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
214
215    // Check if any fixture needs Uint8List.fromList (batch item byte arrays).
216    let has_batch_byte_items = fixtures.iter().any(|f| {
217        let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &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 = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
231        call_config
232            .args
233            .iter()
234            .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
235    });
236
237    // Detect whether any non-HTTP fixture uses a json_object arg that resolves to a JSON array —
238    // those are materialized via `jsonDecode` at test-run time and cast to `List<String>`.
239    // Handle args themselves no longer require `jsonDecode` since they construct the config via
240    // the FRB-generated `createCrawlConfigFromJson(json:)` helper which accepts the JSON string
241    // directly. The variable name is kept as `has_handle_args` for downstream stability.
242    let has_handle_args = fixtures.iter().any(|f| {
243        if f.is_http_test() {
244            return false;
245        }
246        let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
247        call_config
248            .args
249            .iter()
250            .any(|a| a.arg_type == "json_object" && super::resolve_field(&f.input, &a.field).is_array())
251    });
252
253    let _ = writeln!(out, "import 'package:test/test.dart';");
254    // `dart:io` provides HttpClient/SocketException (HTTP fixtures) and Platform/Directory
255    // (file-path/bytes fixtures requiring chdir). Skip the import when neither set is in
256    // play — unconditional emission triggers `unused_import` warnings.
257    if has_http_fixtures || needs_chdir {
258        let _ = writeln!(out, "import 'dart:io';");
259    }
260    if has_batch_byte_items {
261        let _ = writeln!(out, "import 'dart:typed_data';");
262    }
263    let _ = writeln!(out, "import 'package:{pkg_name}/{pkg_name}.dart';");
264    // RustLib is the flutter_rust_bridge entrypoint; must be initialized before any FRB call.
265    // FRB places its generated dart sources under `lib/src/{module_name}_bridge_generated/`,
266    // where `module_name` is the snake_cased crate name (independent of the pubspec `name`,
267    // which may be a short alias like `h2m`). `RustLib` lives in `frb_generated.dart` and
268    // is not re-exported by the FRB barrel `lib.dart`, so we import it directly.
269    let _ = writeln!(
270        out,
271        "import 'package:{pkg_name}/src/{frb_module_name}_bridge_generated/frb_generated.dart' show RustLib;"
272    );
273    if has_http_fixtures {
274        let _ = writeln!(out, "import 'dart:async';");
275    }
276    // dart:convert provides jsonDecode for handle-arg engine construction and HTTP response parsing.
277    if has_http_fixtures || has_handle_args {
278        let _ = writeln!(out, "import 'dart:convert';");
279    }
280    let _ = writeln!(out);
281
282    // Emit file-level HTTP client and serialization mutex.
283    //
284    // The shared HttpClient reuses keep-alive connections to minimize TCP overhead.
285    // The mutex (_lock) ensures requests are serialized within the file so the
286    // connection pool is not exercised concurrently by dart:test's async runner.
287    //
288    // _withRetry wraps the entire request closure with one automatic retry on
289    // transient connection errors (keep-alive connections can be silently closed
290    // by the server just as the client tries to reuse them).
291    if has_http_fixtures {
292        let _ = writeln!(out, "HttpClient _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
293        let _ = writeln!(out);
294        let _ = writeln!(out, "var _lock = Future<void>.value();");
295        let _ = writeln!(out);
296        let _ = writeln!(out, "Future<T> _serialized<T>(Future<T> Function() fn) async {{");
297        let _ = writeln!(out, "  final current = _lock;");
298        let _ = writeln!(out, "  final next = Completer<void>();");
299        let _ = writeln!(out, "  _lock = next.future;");
300        let _ = writeln!(out, "  try {{");
301        let _ = writeln!(out, "    await current;");
302        let _ = writeln!(out, "    return await fn();");
303        let _ = writeln!(out, "  }} finally {{");
304        let _ = writeln!(out, "    next.complete();");
305        let _ = writeln!(out, "  }}");
306        let _ = writeln!(out, "}}");
307        let _ = writeln!(out);
308        // The `fn` here should be the full request closure — on socket failure we
309        // recreate the HttpClient (drops old pooled connections) and retry once.
310        let _ = writeln!(out, "Future<T> _withRetry<T>(Future<T> Function() fn) async {{");
311        let _ = writeln!(out, "  try {{");
312        let _ = writeln!(out, "    return await fn();");
313        let _ = writeln!(out, "  }} on SocketException {{");
314        let _ = writeln!(out, "    _httpClient.close(force: true);");
315        let _ = writeln!(out, "    _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
316        let _ = writeln!(out, "    return fn();");
317        let _ = writeln!(out, "  }} on HttpException {{");
318        let _ = writeln!(out, "    _httpClient.close(force: true);");
319        let _ = writeln!(out, "    _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
320        let _ = writeln!(out, "    return fn();");
321        let _ = writeln!(out, "  }}");
322        let _ = writeln!(out, "}}");
323        let _ = writeln!(out);
324    }
325
326    let _ = writeln!(out, "// E2e tests for category: {category}");
327    let _ = writeln!(out, "void main() {{");
328
329    // Emit setUpAll to initialize the flutter_rust_bridge before any test runs and,
330    // when fixtures load files by path, chdir to test_documents so that relative
331    // paths like "docx/fake.docx" resolve correctly.
332    //
333    // The test_documents directory lives two levels above e2e/dart/ (at the repo root).
334    // The FIXTURES_DIR environment variable can override this for CI environments.
335    let _ = writeln!(out, "  setUpAll(() async {{");
336    let _ = writeln!(out, "    await RustLib.init();");
337    if needs_chdir {
338        let test_docs_path = e2e_config.test_documents_relative_from(0);
339        let _ = writeln!(
340            out,
341            "    final _testDocs = Platform.environment['FIXTURES_DIR'] ?? '{test_docs_path}';"
342        );
343        let _ = writeln!(out, "    final _dir = Directory(_testDocs);");
344        let _ = writeln!(out, "    if (_dir.existsSync()) Directory.current = _dir;");
345    }
346    let _ = writeln!(out, "  }});");
347    let _ = writeln!(out);
348
349    // Close the shared client after all tests in this file complete.
350    if has_http_fixtures {
351        let _ = writeln!(out, "  tearDownAll(() => _httpClient.close());");
352        let _ = writeln!(out);
353    }
354
355    for fixture in fixtures {
356        render_test_case(&mut out, fixture, e2e_config, lang, bridge_class, &field_resolver);
357    }
358
359    let _ = writeln!(out, "}}");
360    out
361}
362
363fn render_test_case(
364    out: &mut String,
365    fixture: &Fixture,
366    e2e_config: &E2eConfig,
367    lang: &str,
368    bridge_class: &str,
369    field_resolver: &FieldResolver,
370) {
371    // HTTP fixtures: hit the mock server.
372    if let Some(http) = &fixture.http {
373        render_http_test_case(out, fixture, http);
374        return;
375    }
376
377    // Non-HTTP fixtures: render a call-based test using the resolved call config.
378    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
379    let call_overrides = call_config.overrides.get(lang);
380    let mut function_name = call_overrides
381        .and_then(|o| o.function.as_ref())
382        .cloned()
383        .unwrap_or_else(|| call_config.function.clone());
384    // Convert snake_case function names to camelCase for Dart conventions.
385    function_name = function_name
386        .split('_')
387        .enumerate()
388        .map(|(i, part)| {
389            if i == 0 {
390                part.to_string()
391            } else {
392                let mut chars = part.chars();
393                match chars.next() {
394                    None => String::new(),
395                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
396                }
397            }
398        })
399        .collect::<Vec<_>>()
400        .join("");
401    let result_var = &call_config.result_var;
402    let description = escape_dart(&fixture.description);
403    let fixture_id = &fixture.id;
404    // `is_async` retained for future use (e.g. non-FRB backends); unused with FRB since
405    // all wrappers return Future<T>.
406    let _is_async = call_overrides.and_then(|o| o.r#async).unwrap_or(call_config.r#async);
407
408    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
409    let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
410    // `result_is_simple = true` means the dart return is a scalar/bytes value
411    // (e.g. `Uint8List` for speech/file_content), not a struct. Field-based
412    // assertions like `audio.not_empty` collapse to whole-result checks so we
413    // don't emit `result.audio` against a `Uint8List` receiver.
414    let result_is_simple = call_overrides.is_some_and(|o| o.result_is_simple) || call_config.result_is_simple;
415
416    // Resolve options_type and options_via from per-fixture → per-call → default.
417    // These drive how `json_object` args are constructed:
418    //   options_via = "from_json" — call `createTypeNameFromJson(json: r'...')` bridge
419    //                               helper and pass the result as a named parameter `req:`.
420    //   All other values (or absent) — existing behaviour (batch arrays, config objects,
421    //   generic JSON arrays, or nothing).
422    let options_type: Option<&str> = call_overrides.and_then(|o| o.options_type.as_deref());
423    let options_via: &str = call_overrides
424        .and_then(|o| o.options_via.as_deref())
425        .unwrap_or("kwargs");
426
427    // Build argument list from fixture.input and call_config.args.
428    // Use `resolve_field` (respects the `field` path like "input.data") rather than
429    // looking up by `arg_def.name` directly — the name and the field key may differ.
430    //
431    // For `extract_file_sync` / `extract_file` fixtures that omit `mime_type`,
432    // derive the MIME from the path extension so `extractBytesSync`/`extractBytes`
433    // can be called (both require an explicit MIME type).
434    let file_path_for_mime: Option<&str> = call_config
435        .args
436        .iter()
437        .find(|a| a.arg_type == "file_path")
438        .and_then(|a| resolve_field(&fixture.input, &a.field).as_str());
439
440    // Detect whether this call converts a file_path arg to bytes at test-run time.
441    // Dart cannot pass OS-level file paths through the FRB bridge — the idiomatic API
442    // is always bytes. When a file_path arg is present (and no caller-supplied dart
443    // function override has already been applied), remap the function name:
444    //   extractFile      → extractBytes
445    //   extractFileSync  → extractBytesSync
446    let has_file_path_arg = call_config.args.iter().any(|a| a.arg_type == "file_path");
447    // Apply the remap only when no per-fixture dart override has already specified the
448    // function — if the fixture author set a dart-specific function name we trust it.
449    let caller_supplied_override = call_overrides.and_then(|o| o.function.as_ref()).is_some();
450    if has_file_path_arg && !caller_supplied_override {
451        function_name = match function_name.as_str() {
452            "extractFile" => "extractBytes".to_string(),
453            "extractFileSync" => "extractBytesSync".to_string(),
454            other => other.to_string(),
455        };
456    }
457
458    // setup_lines holds per-test statements that must precede the main call:
459    // engine construction (handle args) and URL building (mock_url args).
460    let mut setup_lines: Vec<String> = Vec::new();
461    let mut args = Vec::new();
462
463    for arg_def in &call_config.args {
464        match arg_def.arg_type.as_str() {
465            "mock_url" => {
466                let name = arg_def.name.clone();
467                if fixture.has_host_root_route() {
468                    let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
469                    setup_lines.push(format!(
470                        r#"final {name} = Platform.environment["{env_key}"] ?? (Platform.environment["MOCK_SERVER_URL"]! + "/fixtures/{fixture_id}");"#
471                    ));
472                } else {
473                    setup_lines.push(format!(
474                        r#"final {name} = "${{Platform.environment["MOCK_SERVER_URL"] ?? "http://localhost:8080"}}/fixtures/{fixture_id}";"#
475                    ));
476                }
477                args.push(name);
478                continue;
479            }
480            "handle" => {
481                let name = arg_def.name.clone();
482                let field = arg_def.field.strip_prefix("input.").unwrap_or(&arg_def.field);
483                let config_value = fixture.input.get(field).cloned().unwrap_or(serde_json::Value::Null);
484                // Derive the create-function name: "engine" → "createEngine".
485                let create_fn = {
486                    let mut chars = name.chars();
487                    let pascal = match chars.next() {
488                        None => String::new(),
489                        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
490                    };
491                    format!("create{pascal}")
492                };
493                if config_value.is_null()
494                    || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
495                {
496                    setup_lines.push(format!("final {name} = await {bridge_class}.{create_fn}();"));
497                } else {
498                    let json_str = serde_json::to_string(&config_value).unwrap_or_default();
499                    let config_var = format!("{name}Config");
500                    // FRB-generated free function: `createCrawlConfigFromJson(json: '...')` — async,
501                    // deserializes the JSON into the mirror struct via the Rust `create_<type>_from_json`
502                    // helper emitted by the dart backend. This avoids relying on a Dart-side `fromJson`
503                    // constructor (FRB classes don't expose one).
504                    setup_lines.push(format!(
505                        "final {config_var} = await createCrawlConfigFromJson(json: r'{json_str}');"
506                    ));
507                    // Facade exposes `createEngine` with a named `config:` parameter — call it that way.
508                    setup_lines.push(format!(
509                        "final {name} = await {bridge_class}.{create_fn}(config: {config_var});"
510                    ));
511                }
512                args.push(name);
513                continue;
514            }
515            _ => {}
516        }
517
518        let arg_value = resolve_field(&fixture.input, &arg_def.field);
519        match arg_def.arg_type.as_str() {
520            "bytes" | "file_path" => {
521                // `bytes`: value is a file path string; load file contents at test-run time.
522                // `file_path`: also loaded as bytes for dart — extractBytes/extractBytesSync is
523                // the idiomatic Dart API since the Dart runtime cannot pass OS-level file paths
524                // through the FFI bridge.
525                if let serde_json::Value::String(file_path) = arg_value {
526                    args.push(format!("File('{}').readAsBytesSync()", file_path));
527                }
528            }
529            "string" => {
530                // The dart wrapper (`KreuzbergBridge`) emits required params as POSITIONAL
531                // and optional params as named (`{...}` block). Match that convention here:
532                // required string args are positional literals, optional string args are
533                // emitted as `paramName: 'value'` named arguments.
534                //
535                // Special case: when dart remaps `extractFile*` → `extractBytes*`
536                // (because dart cannot pass OS file paths through the FFI bridge), the
537                // underlying wrapper signature requires `mime_type` positionally even
538                // though the source IR marks it as optional for `extractFile*`. Force
539                // mime_type to positional in that case. The remap may have been performed
540                // either implicitly by this codegen (no caller override) or explicitly by
541                // a per-call dart override that sets `function = "extract_bytes"`. Detect
542                // by inspecting the resolved Dart function name — `extractBytes` always
543                // requires `mimeType` as a positional argument in the Dart wrapper.
544                let dart_param_name = snake_to_camel(&arg_def.name);
545                let mime_required_due_to_remap = has_file_path_arg
546                    && arg_def.name == "mime_type"
547                    && (function_name == "extractBytes" || function_name == "extractBytesSync");
548                let is_optional = arg_def.optional && !mime_required_due_to_remap;
549                match arg_value {
550                    serde_json::Value::String(s) => {
551                        let literal = format!("'{}'", escape_dart(s));
552                        if is_optional {
553                            args.push(format!("{dart_param_name}: {literal}"));
554                        } else {
555                            args.push(literal);
556                        }
557                    }
558                    serde_json::Value::Null
559                        if arg_def.optional
560                        // Optional string absent from fixture — try to infer MIME from path
561                        // when the arg name looks like a MIME-type parameter.
562                        && arg_def.name == "mime_type" =>
563                    {
564                        let inferred = file_path_for_mime
565                            .and_then(mime_from_extension)
566                            .unwrap_or("application/octet-stream");
567                        if is_optional {
568                            args.push(format!("{dart_param_name}: '{inferred}'"));
569                        } else {
570                            args.push(format!("'{inferred}'"));
571                        }
572                    }
573                    // Other optional strings with null value are omitted.
574                    _ => {}
575                }
576            }
577            "json_object" => {
578                // Handle batch item arrays (BatchBytesItem / BatchFileItem).
579                if let Some(elem_type) = &arg_def.element_type {
580                    if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && arg_value.is_array() {
581                        let dart_items = emit_dart_batch_item_array(arg_value, elem_type);
582                        args.push(dart_items);
583                    } else if elem_type == "String" && arg_value.is_array() {
584                        // Scalar string array (e.g. `texts: ["a", "b"]` for embed_texts).
585                        // The `KreuzbergBridge` facade declares these parameters as required
586                        // positional (e.g. `embedTexts(List<String> texts, EmbeddingConfig config)`),
587                        // so the list literal must be passed positionally — matching the
588                        // facade contract rather than the underlying FRB bridge's named-arg
589                        // convention.
590                        let items: Vec<String> = arg_value
591                            .as_array()
592                            .unwrap()
593                            .iter()
594                            .filter_map(|v| v.as_str())
595                            .map(|s| format!("'{}'", escape_dart(s)))
596                            .collect();
597                        args.push(format!("<String>[{}]", items.join(", ")));
598                    }
599                } else if options_via == "from_json" {
600                    // `from_json` path: construct a typed mirror-struct via the generated
601                    // `create<TypeName>FromJson(json: '...')` bridge helper, then pass it
602                    // as the named FRB parameter `req: _var`.
603                    //
604                    // The helper is generated by `emit_from_json_fn` in the dart bridge-crate
605                    // generator and made available as a top-level function via the exported
606                    // `liter_llm_bridge_generated/lib.dart`. The parameter name used in the
607                    // bridge method call is always `req:` for single-request-object methods
608                    // (derived from the Rust IR param name).
609                    if let Some(opts_type) = options_type {
610                        if !arg_value.is_null() {
611                            let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
612                            // Escape for Dart single-quoted string literal (handles embedded quotes,
613                            // backslashes, and interpolation markers).
614                            let escaped_json = escape_dart(&json_str);
615                            let var_name = format!("_{}", arg_def.name);
616                            let dart_fn = type_name_to_create_from_json_dart(opts_type);
617                            setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
618                            // FRB bridge method param name is `req` for all single-request methods.
619                            // Use `req:` as the named argument label.
620                            args.push(format!("req: {var_name}"));
621                        }
622                    }
623                } else if arg_def.name == "config" {
624                    if let serde_json::Value::Object(map) = &arg_value {
625                        if !map.is_empty() {
626                            // When the call override specifies a non-default `options_type`
627                            // (e.g. `EmbeddingConfig` for `embed_texts`), or the override map
628                            // contains a non-scalar field that the literal `ExtractionConfig`
629                            // constructor cannot express (e.g. `output_format: "markdown"` is
630                            // a tagged enum, not a plain string), fall back to the
631                            // FRB-generated `create<Type>FromJson(json: '...')` helper which
632                            // round-trips the JSON through serde and so preserves enum tags,
633                            // nested configs, and string-valued enum variants verbatim.
634                            let explicit_options =
635                                options_type.is_some_and(|t| t != "ExtractionConfig" && t != "FileExtractionConfig");
636                            let has_non_scalar = map.values().any(|v| {
637                                matches!(
638                                    v,
639                                    serde_json::Value::String(_)
640                                        | serde_json::Value::Object(_)
641                                        | serde_json::Value::Array(_)
642                                )
643                            });
644                            if explicit_options || has_non_scalar {
645                                let opts_type = options_type.unwrap_or("ExtractionConfig");
646                                let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
647                                let escaped_json = escape_dart(&json_str);
648                                let var_name = format!("_{}", arg_def.name);
649                                let dart_fn = type_name_to_create_from_json_dart(opts_type);
650                                setup_lines
651                                    .push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
652                                args.push(var_name);
653                            } else {
654                                // Fixture provides scalar-only overrides — build an
655                                // `ExtractionConfig` constructor literal with defaults,
656                                // overriding only the bool/int fields present in the
657                                // fixture JSON. Handles configs such as
658                                // {force_ocr:true, disable_ocr:true} that toggle error paths.
659                                args.push(emit_extraction_config_dart(map));
660                            }
661                        }
662                    }
663                    // If config is null/absent, the wrapper supplies the default ExtractionConfig.
664                } else if arg_value.is_array() {
665                    // Generic JSON array (e.g. batch_urls: ["/page1", "/page2"]).
666                    // Decode via jsonDecode and cast to List<String> at test-run time.
667                    let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
668                    let var_name = arg_def.name.clone();
669                    setup_lines.push(format!(
670                        "final {var_name} = (jsonDecode(r'{json_str}') as List<dynamic>).cast<String>();"
671                    ));
672                    args.push(var_name);
673                } else if let serde_json::Value::Object(map) = &arg_value {
674                    // Generic options-style json_object arg (e.g. h2m's
675                    // `options: ConversionOptions` on `convert(html, options)`). When the
676                    // fixture provides input.options and the call config declares an
677                    // `options_type`, build the mirror struct via the FRB-generated
678                    // `create<OptionsType>FromJson(json: '...')` helper. Use the arg's
679                    // original name (e.g. `options`) as the named parameter label.
680                    if !map.is_empty() {
681                        if let Some(opts_type) = options_type {
682                            let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
683                            let escaped_json = escape_dart(&json_str);
684                            let dart_param_name = snake_to_camel(&arg_def.name);
685                            let var_name = format!("_{}", arg_def.name);
686                            let dart_fn = type_name_to_create_from_json_dart(opts_type);
687                            setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
688                            if arg_def.optional {
689                                args.push(format!("{dart_param_name}: {var_name}"));
690                            } else {
691                                args.push(var_name);
692                            }
693                        }
694                    }
695                }
696            }
697            _ => {}
698        }
699    }
700
701    // Fixture-driven visitor handle. When `fixture.visitor` is set we build
702    // a `_visitor` via `createHtmlVisitorDartImpl(...)` and pass it as the
703    // `visitor:` named parameter to convert. The dart binding currently lacks
704    // three pieces required to make this work end-to-end:
705    //   - `VisitResult` is `#[frb-ignore]`d, so the freezed factory variants
706    //     (`VisitResult.continue_()`, `VisitResult.custom(...)`, …) are not
707    //     emitted on the dart side.
708    //   - The `BoxFn...` callback parameters are opaque `RustOpaque` classes
709    //     with no public constructor — closures cannot be passed inline.
710    //   - There is no path from `HtmlVisitorDartImpl` to `VisitorHandle`, and
711    //     `H2mBridge.convert` / the free `convert` function do not accept a
712    //     `visitor:` argument.
713    //
714    // Until those binding pieces land, visitor fixtures emit a skip stub via
715    // `dart_visitors::build_dart_visitor` (exercised once in unit tests for
716    // snapshot coverage) plus a `test(...,  skip: 'pending dart-binding visitor wiring')`
717    // declaration so the file still compiles and the rest of the suite runs.
718    if let Some(visitor_spec) = &fixture.visitor {
719        // Touch the visitor builder so the generated-code helper stays
720        // covered by per-fixture codegen exercise. The block is discarded;
721        // we do not append it to `setup_lines` because the emitted closures
722        // reference VisitResult symbols that are not yet exposed by the dart
723        // binding.
724        let mut _scratch: Vec<String> = Vec::new();
725        let _ = super::dart_visitors::build_dart_visitor(&mut _scratch, visitor_spec);
726        let skip_reason = "pending dart-binding visitor wiring (alef issue)";
727        let _ = writeln!(out, "  test('{description}', () async {{}}, skip: '{skip_reason}');");
728        let _ = writeln!(out);
729        return;
730    }
731
732    // Resolve client_factory: when set, tests create a client instance and call
733    // methods on it rather than using static bridge-class calls. This mirrors the
734    // go/python/zig pattern for stateful clients (e.g. liter-llm).
735    let client_factory: Option<&str> = call_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
736        e2e_config
737            .call
738            .overrides
739            .get(lang)
740            .and_then(|o| o.client_factory.as_deref())
741    });
742
743    // Convert factory name to camelCase (same rule as function_name above).
744    let client_factory_camel: Option<String> = client_factory.map(|f| {
745        f.split('_')
746            .enumerate()
747            .map(|(i, part)| {
748                if i == 0 {
749                    part.to_string()
750                } else {
751                    let mut chars = part.chars();
752                    match chars.next() {
753                        None => String::new(),
754                        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
755                    }
756                }
757            })
758            .collect::<Vec<_>>()
759            .join("")
760    });
761
762    // All bridge methods return Future<T> because FRB v2 wraps every Rust
763    // function as async in Dart — even "sync" Rust functions. Always emit an async
764    // test body and await the call so the test framework waits for the future.
765    let _ = writeln!(out, "  test('{description}', () async {{");
766
767    let args_str = args.join(", ");
768    let receiver_class = call_overrides
769        .and_then(|o| o.class.as_ref())
770        .cloned()
771        .unwrap_or_else(|| bridge_class.to_string());
772
773    // When client_factory is set, determine the mock URL and emit client instantiation.
774    // The mock URL derivation follows the same has_host_root_route / plain-fixture split
775    // used by the mock_url arg handler above.
776    let (receiver, extra_setup): (String, Option<String>) = if let Some(factory) = &client_factory_camel {
777        let has_mock_url = call_config.args.iter().any(|a| a.arg_type == "mock_url");
778        let mock_url_setup = if !has_mock_url {
779            // No explicit mock_url arg — derive the URL inline.
780            if fixture.has_host_root_route() {
781                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
782                Some(format!(
783                    "final _mockUrl = Platform.environment[\"{env_key}\"] ?? (Platform.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\");"
784                ))
785            } else {
786                Some(format!(
787                    r#"final _mockUrl = "${{Platform.environment["MOCK_SERVER_URL"] ?? "http://localhost:8080"}}/fixtures/{fixture_id}";"#
788                ))
789            }
790        } else {
791            None
792        };
793        let url_expr = if has_mock_url {
794            // A mock_url arg was emitted into setup_lines already — reuse the variable name
795            // from the first mock_url arg definition so we don't duplicate the URL.
796            call_config
797                .args
798                .iter()
799                .find(|a| a.arg_type == "mock_url")
800                .map(|a| a.name.clone())
801                .unwrap_or_else(|| "_mockUrl".to_string())
802        } else {
803            "_mockUrl".to_string()
804        };
805        let create_line = format!("final _client = await {receiver_class}.{factory}('test-key', baseUrl: {url_expr});");
806        let full_setup = if let Some(url_line) = mock_url_setup {
807            Some(format!("{url_line}\n    {create_line}"))
808        } else {
809            Some(create_line)
810        };
811        ("_client".to_string(), full_setup)
812    } else {
813        (receiver_class.clone(), None)
814    };
815
816    if expects_error && (!setup_lines.is_empty() || extra_setup.is_some()) {
817        // Wrap setup + call in an async lambda so any exception at any step is caught.
818        // flutter_rust_bridge 2.x decodes Rust errors as raw String values (not Exception
819        // subtypes), so throwsException will not match. Use throwsA(anything) instead.
820        let _ = writeln!(out, "    await expectLater(() async {{");
821        for line in &setup_lines {
822            let _ = writeln!(out, "      {line}");
823        }
824        if let Some(extra) = &extra_setup {
825            for line in extra.lines() {
826                let _ = writeln!(out, "      {line}");
827            }
828        }
829        if is_streaming {
830            let _ = writeln!(out, "      return {receiver}.{function_name}({args_str}).toList();");
831        } else {
832            let _ = writeln!(out, "      return {receiver}.{function_name}({args_str});");
833        }
834        let _ = writeln!(out, "    }}(), throwsA(anything));");
835    } else if expects_error {
836        // No setup lines, direct call — same throwsA(anything) rationale as above.
837        if let Some(extra) = &extra_setup {
838            for line in extra.lines() {
839                let _ = writeln!(out, "    {line}");
840            }
841        }
842        if is_streaming {
843            let _ = writeln!(
844                out,
845                "    await expectLater({receiver}.{function_name}({args_str}).toList(), throwsA(anything));"
846            );
847        } else {
848            let _ = writeln!(
849                out,
850                "    await expectLater({receiver}.{function_name}({args_str}), throwsA(anything));"
851            );
852        }
853    } else {
854        for line in &setup_lines {
855            let _ = writeln!(out, "    {line}");
856        }
857        if let Some(extra) = &extra_setup {
858            for line in extra.lines() {
859                let _ = writeln!(out, "    {line}");
860            }
861        }
862        if is_streaming {
863            let _ = writeln!(
864                out,
865                "    final {result_var} = await {receiver}.{function_name}({args_str}).toList();"
866            );
867        } else {
868            let _ = writeln!(
869                out,
870                "    final {result_var} = await {receiver}.{function_name}({args_str});"
871            );
872        }
873        for assertion in &fixture.assertions {
874            if is_streaming {
875                render_streaming_assertion_dart(out, assertion, result_var);
876            } else {
877                render_assertion_dart(out, assertion, result_var, result_is_simple, field_resolver);
878            }
879        }
880    }
881
882    let _ = writeln!(out, "  }});");
883    let _ = writeln!(out);
884}
885
886/// Render `.length` / `?.length ?? 0` against a Dart field accessor.
887///
888/// Count-style assertions (`count_equals`, `count_min`, `min_length`, `max_length`)
889/// operate on collection-typed fields. FRB v2 maps `Option<Vec<T>>` to `List<T>?`
890/// (nullable) but `Vec<T>` to `List<T>` (non-null). Emitting `?.length ?? 0`
891/// against a non-null receiver triggers `invalid_null_aware_operator`. Inspect
892/// the IR via `FieldResolver::is_optional` and choose the safe form per field.
893fn dart_length_expr(field_accessor: &str, field: Option<&str>, field_resolver: &FieldResolver) -> String {
894    let is_optional = field
895        .map(|f| {
896            let resolved = field_resolver.resolve(f);
897            field_resolver.is_optional(f) || field_resolver.is_optional(resolved)
898        })
899        .unwrap_or(false);
900    if is_optional {
901        format!("{field_accessor}?.length ?? 0")
902    } else {
903        format!("{field_accessor}.length")
904    }
905}
906
907fn dart_format_value(val: &serde_json::Value) -> String {
908    match val {
909        serde_json::Value::String(s) => format!("'{}'", escape_dart(s)),
910        serde_json::Value::Bool(b) => b.to_string(),
911        serde_json::Value::Number(n) => n.to_string(),
912        serde_json::Value::Null => "null".to_string(),
913        other => format!("'{}'", escape_dart(&other.to_string())),
914    }
915}
916
917/// Render a single fixture assertion as a Dart `package:test` `expect(...)` call.
918///
919/// Field paths are converted per-segment to camelCase (FRB v2 convention) using
920/// [`field_to_dart_accessor`].  All 24 fixture assertion types are handled.
921///
922/// Assertions on fixture fields that are not in the configured `result_fields` set
923/// are emitted as a `// skipped:` comment instead — the Dart binding may model a
924/// different result shape than the fixture asserts on (e.g. flat `ScrapeResult` vs.
925/// nested `result.browser.*`), and emitting unresolvable getters would break the
926/// whole file at compile time.
927fn render_assertion_dart(
928    out: &mut String,
929    assertion: &Assertion,
930    result_var: &str,
931    result_is_simple: bool,
932    field_resolver: &FieldResolver,
933) {
934    // Skip assertions on fields that don't exist on the dart result type. This must run
935    // BEFORE the array-traversal and standard accessor paths since both emit code that
936    // references the field — an unknown field path produces an `isn't defined` error.
937    if !result_is_simple {
938        if let Some(f) = assertion.field.as_deref() {
939            // Use the head segment (before any `[].`) for validation since `is_valid_for_result`
940            // only checks the first path component.
941            let head = f.split("[].").next().unwrap_or(f);
942            if !head.is_empty() && !field_resolver.is_valid_for_result(head) {
943                let _ = writeln!(out, "    // skipped: field '{f}' not available on dart result type");
944                return;
945            }
946        }
947    }
948
949    // Skip assertions that traverse a tagged-union variant boundary. FRB exposes
950    // tagged unions like `FormatMetadata` as sealed classes whose variants are
951    // accessed via pattern matching (`switch (m) { case FormatMetadata_Excel ... }`)
952    // — there is no `.excel?` getter, so the fixture path cannot be expressed as
953    // a simple chained accessor without language-specific pattern-matching codegen.
954    if let Some(f) = assertion.field.as_deref() {
955        if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
956            let _ = writeln!(
957                out,
958                "    // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Dart)"
959            );
960            return;
961        }
962    }
963
964    // Handle array traversal (e.g. "links[].link_type" → any() expression).
965    if let Some(f) = assertion.field.as_deref() {
966        if let Some(dot) = f.find("[].") {
967            // Apply the alias mapping to the full `xxx[].yyy` path first so renamed
968            // sub-fields (e.g. `assets[].category` → `assets[].asset_category`) resolve
969            // correctly. Split *after* resolving so both the array head and the element
970            // path reflect any alias rewrites.
971            let resolved_full = field_resolver.resolve(f);
972            let (array_part, elem_part) = match resolved_full.find("[].") {
973                Some(rdot) => (&resolved_full[..rdot], &resolved_full[rdot + 3..]),
974                // Resolver mapped the path away from `[].` form — fall back to the original
975                // split, since downstream code expects the array/elem structure.
976                None => (&f[..dot], &f[dot + 3..]),
977            };
978            let array_accessor = if array_part.is_empty() {
979                result_var.to_string()
980            } else {
981                field_resolver.accessor(array_part, "dart", result_var)
982            };
983            let elem_accessor = field_to_dart_accessor(elem_part);
984            match assertion.assertion_type.as_str() {
985                "contains" => {
986                    if let Some(expected) = &assertion.value {
987                        let dart_val = dart_format_value(expected);
988                        let _ = writeln!(
989                            out,
990                            "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isTrue);"
991                        );
992                    }
993                }
994                "contains_all" => {
995                    if let Some(values) = &assertion.values {
996                        for val in values {
997                            let dart_val = dart_format_value(val);
998                            let _ = writeln!(
999                                out,
1000                                "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isTrue);"
1001                            );
1002                        }
1003                    }
1004                }
1005                "not_contains" => {
1006                    if let Some(expected) = &assertion.value {
1007                        let dart_val = dart_format_value(expected);
1008                        let _ = writeln!(
1009                            out,
1010                            "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isFalse);"
1011                        );
1012                    } else if let Some(values) = &assertion.values {
1013                        for val in values {
1014                            let dart_val = dart_format_value(val);
1015                            let _ = writeln!(
1016                                out,
1017                                "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isFalse);"
1018                            );
1019                        }
1020                    }
1021                }
1022                "not_empty" => {
1023                    let _ = writeln!(
1024                        out,
1025                        "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().isNotEmpty), isTrue);"
1026                    );
1027                }
1028                other => {
1029                    let _ = writeln!(
1030                        out,
1031                        "    // skipped: unsupported traversal assertion '{other}' on '{f}'"
1032                    );
1033                }
1034            }
1035            return;
1036        }
1037    }
1038
1039    let field_accessor = if result_is_simple {
1040        // Whole-result assertion path: the dart return is a scalar (e.g. a
1041        // `Uint8List` for speech/file_content), so any `field` on the
1042        // assertion resolves to the whole value rather than a sub-accessor.
1043        result_var.to_string()
1044    } else {
1045        match assertion.field.as_deref() {
1046            // Use the shared accessor builder (`FieldResolver::accessor`) — it applies the
1047            // alias mapping (e.g. `robots.is_allowed` → `is_allowed`), expands array
1048            // segments to `[0]` lookups, and injects `!` after optional intermediates so
1049            // chained access compiles under sound null safety.
1050            Some(f) if !f.is_empty() => field_resolver.accessor(f, "dart", result_var),
1051            _ => result_var.to_string(),
1052        }
1053    };
1054
1055    let format_value = |val: &serde_json::Value| -> String { dart_format_value(val) };
1056
1057    match assertion.assertion_type.as_str() {
1058        "equals" | "field_equals" => {
1059            if let Some(expected) = &assertion.value {
1060                let dart_val = format_value(expected);
1061                // Match the rust codegen's behaviour: trim both sides for string equality
1062                // so trailing-newline differences between h2m's emitted markdown and the
1063                // fixture's expected value don't produce false positives.
1064                if expected.is_string() {
1065                    let _ = writeln!(
1066                        out,
1067                        "    expect({field_accessor}.toString().trim(), equals({dart_val}.toString().trim()));"
1068                    );
1069                } else {
1070                    let _ = writeln!(out, "    expect({field_accessor}, equals({dart_val}));");
1071                }
1072            } else {
1073                let _ = writeln!(
1074                    out,
1075                    "    // skipped: '{}' assertion missing value",
1076                    assertion.assertion_type
1077                );
1078            }
1079        }
1080        "not_equals" => {
1081            if let Some(expected) = &assertion.value {
1082                let dart_val = format_value(expected);
1083                if expected.is_string() {
1084                    let _ = writeln!(
1085                        out,
1086                        "    expect({field_accessor}.toString().trim(), isNot(equals({dart_val}.toString().trim())));"
1087                    );
1088                } else {
1089                    let _ = writeln!(out, "    expect({field_accessor}, isNot(equals({dart_val})));");
1090                }
1091            }
1092        }
1093        "contains" => {
1094            if let Some(expected) = &assertion.value {
1095                let dart_val = format_value(expected);
1096                let _ = writeln!(out, "    expect({field_accessor}, contains({dart_val}));");
1097            } else {
1098                let _ = writeln!(out, "    // skipped: 'contains' assertion missing value");
1099            }
1100        }
1101        "contains_all" => {
1102            if let Some(values) = &assertion.values {
1103                for val in values {
1104                    let dart_val = format_value(val);
1105                    let _ = writeln!(out, "    expect({field_accessor}, contains({dart_val}));");
1106                }
1107            }
1108        }
1109        "contains_any" => {
1110            if let Some(values) = &assertion.values {
1111                let checks: Vec<String> = values
1112                    .iter()
1113                    .map(|v| {
1114                        let dart_val = format_value(v);
1115                        format!("{field_accessor}.contains({dart_val})")
1116                    })
1117                    .collect();
1118                let joined = checks.join(" || ");
1119                let _ = writeln!(out, "    expect({joined}, isTrue);");
1120            }
1121        }
1122        "not_contains" => {
1123            if let Some(expected) = &assertion.value {
1124                let dart_val = format_value(expected);
1125                let _ = writeln!(out, "    expect({field_accessor}, isNot(contains({dart_val})));");
1126            } else if let Some(values) = &assertion.values {
1127                for val in values {
1128                    let dart_val = format_value(val);
1129                    let _ = writeln!(out, "    expect({field_accessor}, isNot(contains({dart_val})));");
1130                }
1131            }
1132        }
1133        "not_empty" => {
1134            // `isNotEmpty` only applies to types with a `.isEmpty` getter (collections,
1135            // strings, maps). For struct-shaped fields (e.g. `document: DocumentStructure`)
1136            // we instead assert the value is non-null — those types have no notion of
1137            // "empty" and the fixture intent is "the field is present".
1138            let is_collection = assertion.field.as_deref().is_some_and(|f| {
1139                let resolved = field_resolver.resolve(f);
1140                field_resolver.is_array(f) || field_resolver.is_array(resolved)
1141            });
1142            if is_collection {
1143                let _ = writeln!(out, "    expect({field_accessor}, isNotEmpty);");
1144            } else {
1145                let _ = writeln!(out, "    expect({field_accessor}, isNotNull);");
1146            }
1147        }
1148        "is_empty" => {
1149            // FRB models `Option<String>` / `Option<Vec<T>>` as nullable in Dart. The `isEmpty`
1150            // matcher throws `NoSuchMethodError` on `null`. Accept `null` as semantically
1151            // empty by combining `isNull` with `isEmpty` via `anyOf`.
1152            let _ = writeln!(out, "    expect({field_accessor}, anyOf(isNull, isEmpty));");
1153        }
1154        "starts_with" => {
1155            if let Some(expected) = &assertion.value {
1156                let dart_val = format_value(expected);
1157                let _ = writeln!(out, "    expect({field_accessor}, startsWith({dart_val}));");
1158            }
1159        }
1160        "ends_with" => {
1161            if let Some(expected) = &assertion.value {
1162                let dart_val = format_value(expected);
1163                let _ = writeln!(out, "    expect({field_accessor}, endsWith({dart_val}));");
1164            }
1165        }
1166        "min_length" => {
1167            if let Some(val) = &assertion.value {
1168                if let Some(n) = val.as_u64() {
1169                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1170                    let _ = writeln!(out, "    expect({length_expr}, greaterThanOrEqualTo({n}));");
1171                }
1172            }
1173        }
1174        "max_length" => {
1175            if let Some(val) = &assertion.value {
1176                if let Some(n) = val.as_u64() {
1177                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1178                    let _ = writeln!(out, "    expect({length_expr}, lessThanOrEqualTo({n}));");
1179                }
1180            }
1181        }
1182        "count_equals" => {
1183            if let Some(val) = &assertion.value {
1184                if let Some(n) = val.as_u64() {
1185                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1186                    let _ = writeln!(out, "    expect({length_expr}, equals({n}));");
1187                }
1188            }
1189        }
1190        "count_min" => {
1191            if let Some(val) = &assertion.value {
1192                if let Some(n) = val.as_u64() {
1193                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1194                    let _ = writeln!(out, "    expect({length_expr}, greaterThanOrEqualTo({n}));");
1195                }
1196            }
1197        }
1198        "matches_regex" => {
1199            if let Some(expected) = &assertion.value {
1200                let dart_val = format_value(expected);
1201                let _ = writeln!(out, "    expect({field_accessor}, matches(RegExp({dart_val})));");
1202            }
1203        }
1204        "is_true" => {
1205            let _ = writeln!(out, "    expect({field_accessor}, isTrue);");
1206        }
1207        "is_false" => {
1208            let _ = writeln!(out, "    expect({field_accessor}, isFalse);");
1209        }
1210        "greater_than" => {
1211            if let Some(val) = &assertion.value {
1212                let dart_val = format_value(val);
1213                let _ = writeln!(out, "    expect({field_accessor}, greaterThan({dart_val}));");
1214            }
1215        }
1216        "less_than" => {
1217            if let Some(val) = &assertion.value {
1218                let dart_val = format_value(val);
1219                let _ = writeln!(out, "    expect({field_accessor}, lessThan({dart_val}));");
1220            }
1221        }
1222        "greater_than_or_equal" => {
1223            if let Some(val) = &assertion.value {
1224                let dart_val = format_value(val);
1225                let _ = writeln!(out, "    expect({field_accessor}, greaterThanOrEqualTo({dart_val}));");
1226            }
1227        }
1228        "less_than_or_equal" => {
1229            if let Some(val) = &assertion.value {
1230                let dart_val = format_value(val);
1231                let _ = writeln!(out, "    expect({field_accessor}, lessThanOrEqualTo({dart_val}));");
1232            }
1233        }
1234        "not_null" => {
1235            let _ = writeln!(out, "    expect({field_accessor}, isNotNull);");
1236        }
1237        "not_error" => {
1238            // No-op: a thrown error from `await` would have failed the test already.
1239        }
1240        "error" => {
1241            // Handled at the test method level via throwsA(anything).
1242        }
1243        "method_result" => {
1244            if let Some(method) = &assertion.method {
1245                let dart_method = method.to_lower_camel_case();
1246                let check = assertion.check.as_deref().unwrap_or("not_null");
1247                let method_call = format!("{field_accessor}.{dart_method}()");
1248                match check {
1249                    "equals" => {
1250                        if let Some(expected) = &assertion.value {
1251                            let dart_val = format_value(expected);
1252                            let _ = writeln!(out, "    expect({method_call}, equals({dart_val}));");
1253                        }
1254                    }
1255                    "is_true" => {
1256                        let _ = writeln!(out, "    expect({method_call}, isTrue);");
1257                    }
1258                    "is_false" => {
1259                        let _ = writeln!(out, "    expect({method_call}, isFalse);");
1260                    }
1261                    "greater_than_or_equal" => {
1262                        if let Some(val) = &assertion.value {
1263                            let dart_val = format_value(val);
1264                            let _ = writeln!(out, "    expect({method_call}, greaterThanOrEqualTo({dart_val}));");
1265                        }
1266                    }
1267                    "count_min" => {
1268                        if let Some(val) = &assertion.value {
1269                            if let Some(n) = val.as_u64() {
1270                                let _ = writeln!(out, "    expect({method_call}.length, greaterThanOrEqualTo({n}));");
1271                            }
1272                        }
1273                    }
1274                    _ => {
1275                        let _ = writeln!(out, "    expect({method_call}, isNotNull);");
1276                    }
1277                }
1278            }
1279        }
1280        other => {
1281            let _ = writeln!(out, "    // skipped: unknown assertion type '{other}'");
1282        }
1283    }
1284}
1285
1286/// Render a single fixture assertion for a streaming result.
1287///
1288/// `result_var` is the `List<T>` collected via `.toList()` on the stream.
1289/// Supports:
1290/// - `not_error`: no-op (a thrown error would already fail the test).
1291/// - `count_min` with `field = "chunks"`: assert `result_var.length >= value`.
1292/// - `equals` with `field = "stream_content"`: concatenate `delta.content` and compare.
1293///
1294/// Other assertion types are emitted as comments.
1295fn render_streaming_assertion_dart(out: &mut String, assertion: &Assertion, result_var: &str) {
1296    match assertion.assertion_type.as_str() {
1297        "not_error" => {
1298            // No-op: a thrown error from `.toList()` would have failed the test already.
1299        }
1300        "count_min" if assertion.field.as_deref() == Some("chunks") => {
1301            if let Some(serde_json::Value::Number(n)) = &assertion.value {
1302                let _ = writeln!(out, "    expect({result_var}.length, greaterThanOrEqualTo({n}));");
1303            }
1304        }
1305        "equals" if assertion.field.as_deref() == Some("stream_content") => {
1306            if let Some(serde_json::Value::String(expected)) = &assertion.value {
1307                let escaped = escape_dart(expected);
1308                let _ = writeln!(
1309                    out,
1310                    "    final _content = {result_var}.map((c) => c.choices.firstOrNull?.delta.content ?? '').join();"
1311                );
1312                let _ = writeln!(out, "    expect(_content, equals('{escaped}'));");
1313            }
1314        }
1315        other => {
1316            let _ = writeln!(out, "    // skipped streaming assertion: '{other}'");
1317        }
1318    }
1319}
1320
1321/// Converts a snake_case JSON key to Dart camelCase.
1322fn snake_to_camel(s: &str) -> String {
1323    let mut result = String::with_capacity(s.len());
1324    let mut next_upper = false;
1325    for ch in s.chars() {
1326        if ch == '_' {
1327            next_upper = true;
1328        } else if next_upper {
1329            result.extend(ch.to_uppercase());
1330            next_upper = false;
1331        } else {
1332            result.push(ch);
1333        }
1334    }
1335    result
1336}
1337
1338/// Convert a dot-separated fixture field path to a Dart accessor expression.
1339///
1340/// Each segment is converted to camelCase (FRB v2 convention); array-index brackets
1341/// (e.g. `choices[0]`) and map-key brackets (e.g. `tags[name]`) are preserved.
1342/// This replaces the former single-pass `snake_to_camel` call which incorrectly
1343/// treated the entire path string as one identifier.
1344///
1345/// Examples:
1346/// - `"choices"` → `"choices"`
1347/// - `"choices[0].message.content"` → `"choices[0].message.content"`
1348/// - `"metadata.document_title"` → `"metadata.documentTitle"`
1349/// - `"model_id"` → `"modelId"`
1350fn field_to_dart_accessor(path: &str) -> String {
1351    let mut result = String::with_capacity(path.len());
1352    for (i, segment) in path.split('.').enumerate() {
1353        if i > 0 {
1354            result.push('.');
1355        }
1356        // Separate a trailing `[...]` bracket from the field name so we only
1357        // camelCase the identifier part, not the bracket content. The owning
1358        // collection may be `List<T>?` when the underlying Rust field is
1359        // `Option<Vec<T>>`; force-unwrap with `!` so the `[N]` lookup and any
1360        // subsequent member access compile under sound null safety.
1361        if let Some(bracket_pos) = segment.find('[') {
1362            let name = &segment[..bracket_pos];
1363            let bracket = &segment[bracket_pos..];
1364            result.push_str(&name.to_lower_camel_case());
1365            result.push('!');
1366            result.push_str(bracket);
1367        } else {
1368            result.push_str(&segment.to_lower_camel_case());
1369        }
1370    }
1371    result
1372}
1373
1374/// Emits a Dart `ExtractionConfig(...)` constructor with default values, overriding
1375/// fields present in `overrides` (from fixture JSON, snake_case keys).
1376///
1377/// Only simple scalar overrides (bool, int) are supported. Complex nested types
1378/// (ocr, chunking, etc.) are left at their defaults (null).
1379fn emit_extraction_config_dart(overrides: &serde_json::Map<String, serde_json::Value>) -> String {
1380    // Collect scalar overrides; convert keys to camelCase.
1381    let mut field_overrides: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1382    for (key, val) in overrides {
1383        let camel = snake_to_camel(key);
1384        let dart_val = match val {
1385            serde_json::Value::Bool(b) => {
1386                if *b {
1387                    "true".to_string()
1388                } else {
1389                    "false".to_string()
1390                }
1391            }
1392            serde_json::Value::Number(n) => n.to_string(),
1393            serde_json::Value::String(s) => format!("'{s}'"),
1394            _ => continue, // skip complex nested objects
1395        };
1396        field_overrides.insert(camel, dart_val);
1397    }
1398
1399    let use_cache = field_overrides.remove("useCache").unwrap_or_else(|| "true".to_string());
1400    let enable_quality_processing = field_overrides
1401        .remove("enableQualityProcessing")
1402        .unwrap_or_else(|| "true".to_string());
1403    let force_ocr = field_overrides
1404        .remove("forceOcr")
1405        .unwrap_or_else(|| "false".to_string());
1406    let disable_ocr = field_overrides
1407        .remove("disableOcr")
1408        .unwrap_or_else(|| "false".to_string());
1409    let include_document_structure = field_overrides
1410        .remove("includeDocumentStructure")
1411        .unwrap_or_else(|| "false".to_string());
1412    let use_layout_for_markdown = field_overrides
1413        .remove("useLayoutForMarkdown")
1414        .unwrap_or_else(|| "false".to_string());
1415    let max_archive_depth = field_overrides
1416        .remove("maxArchiveDepth")
1417        .unwrap_or_else(|| "3".to_string());
1418
1419    format!(
1420        "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})"
1421    )
1422}
1423
1424// ---------------------------------------------------------------------------
1425// HTTP server test rendering — DartTestClientRenderer impl + thin driver wrapper
1426// ---------------------------------------------------------------------------
1427
1428/// Renderer that emits `package:test` `test(...)` blocks using `dart:io HttpClient`
1429/// against the mock server (`Platform.environment['MOCK_SERVER_URL']`).
1430///
1431/// Skipped tests are emitted as self-contained stubs (complete test block with
1432/// `markTestSkipped`) entirely inside `render_test_open`. `render_test_close` uses
1433/// `in_skip` to emit the right closing token: nothing extra for skip stubs (already
1434/// closed) vs. `})));` for regular tests.
1435///
1436/// `is_redirect` must be set to `true` before invoking the shared driver for 3xx
1437/// fixtures so that `render_call` can inject `ioReq.followRedirects = false` after
1438/// the `openUrl` call.
1439struct DartTestClientRenderer {
1440    /// Set to `true` when `render_test_open` is called with a skip reason so that
1441    /// `render_test_close` can match the opening shape.
1442    in_skip: Cell<bool>,
1443    /// Pre-set to `true` by the thin wrapper when the fixture expects a 3xx response.
1444    /// `render_call` injects `ioReq.followRedirects = false` when this is `true`.
1445    is_redirect: Cell<bool>,
1446}
1447
1448impl DartTestClientRenderer {
1449    fn new(is_redirect: bool) -> Self {
1450        Self {
1451            in_skip: Cell::new(false),
1452            is_redirect: Cell::new(is_redirect),
1453        }
1454    }
1455}
1456
1457impl client::TestClientRenderer for DartTestClientRenderer {
1458    fn language_name(&self) -> &'static str {
1459        "dart"
1460    }
1461
1462    /// Emit the test opening.
1463    ///
1464    /// For skipped fixtures: emit the entire self-contained stub (open + body +
1465    /// close + blank line) and set `in_skip = true` so `render_test_close` is a
1466    /// no-op.
1467    ///
1468    /// For active fixtures: emit `test('desc', () => _serialized(() => _withRetry(() async {`
1469    /// leaving the block open for the assertion primitives.
1470    fn render_test_open(&self, out: &mut String, _fn_name: &str, description: &str, skip_reason: Option<&str>) {
1471        let escaped_desc = escape_dart(description);
1472        if let Some(reason) = skip_reason {
1473            let escaped_reason = escape_dart(reason);
1474            let _ = writeln!(out, "  test('{escaped_desc}', () {{");
1475            let _ = writeln!(out, "    markTestSkipped('{escaped_reason}');");
1476            let _ = writeln!(out, "  }});");
1477            let _ = writeln!(out);
1478            self.in_skip.set(true);
1479        } else {
1480            let _ = writeln!(
1481                out,
1482                "  test('{escaped_desc}', () => _serialized(() => _withRetry(() async {{"
1483            );
1484            self.in_skip.set(false);
1485        }
1486    }
1487
1488    /// Emit the test closing token.
1489    ///
1490    /// No-op for skip stubs (the stub was fully closed in `render_test_open`).
1491    /// Emits `})));` followed by a blank line for regular tests.
1492    fn render_test_close(&self, out: &mut String) {
1493        if self.in_skip.get() {
1494            // Stub was already closed in render_test_open.
1495            return;
1496        }
1497        let _ = writeln!(out, "  }})));");
1498        let _ = writeln!(out);
1499    }
1500
1501    /// Emit the full `dart:io HttpClient` request scaffolding.
1502    ///
1503    /// Emits:
1504    /// - URL construction from `MOCK_SERVER_URL`.
1505    /// - `_httpClient.openUrl(method, uri)`.
1506    /// - `followRedirects = false` when `is_redirect` is pre-set on the renderer.
1507    /// - Content-Type header, request headers, cookies, optional body bytes.
1508    /// - `ioReq.close()` → `ioResp`.
1509    /// - Response-body drain into `bodyStr` (skipped for redirect responses).
1510    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
1511        // dart:io restricted headers (handled automatically by the HTTP stack).
1512        const DART_RESTRICTED_HEADERS: &[&str] = &["content-length", "host", "transfer-encoding"];
1513
1514        let method = ctx.method.to_uppercase();
1515        let escaped_method = escape_dart(&method);
1516
1517        // Fixture path is `/fixtures/<id>` — extract the id portion for URL construction.
1518        let fixture_path = escape_dart(ctx.path);
1519
1520        // Determine effective content-type.
1521        let has_explicit_content_type = ctx.headers.keys().any(|k| k.to_lowercase() == "content-type");
1522        let effective_content_type = if has_explicit_content_type {
1523            ctx.headers
1524                .iter()
1525                .find(|(k, _)| k.to_lowercase() == "content-type")
1526                .map(|(_, v)| v.as_str())
1527                .unwrap_or("application/json")
1528        } else if ctx.body.is_some() {
1529            ctx.content_type.unwrap_or("application/json")
1530        } else {
1531            ""
1532        };
1533
1534        let _ = writeln!(
1535            out,
1536            "    final baseUrl = Platform.environment['MOCK_SERVER_URL'] ?? 'http://localhost:8080';"
1537        );
1538        let _ = writeln!(out, "    final uri = Uri.parse('$baseUrl{fixture_path}');");
1539        let _ = writeln!(
1540            out,
1541            "    final ioReq = await _httpClient.openUrl('{escaped_method}', uri);"
1542        );
1543
1544        // Disable automatic redirect following for 3xx fixtures so the test can
1545        // assert on the redirect status code itself.
1546        if self.is_redirect.get() {
1547            let _ = writeln!(out, "    ioReq.followRedirects = false;");
1548        }
1549
1550        // Set content-type header.
1551        if !effective_content_type.is_empty() {
1552            let escaped_ct = escape_dart(effective_content_type);
1553            let _ = writeln!(out, "    ioReq.headers.set('content-type', '{escaped_ct}');");
1554        }
1555
1556        // Set request headers (skip dart:io restricted headers and content-type, already handled).
1557        let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
1558        header_pairs.sort_by_key(|(k, _)| k.as_str());
1559        for (name, value) in &header_pairs {
1560            if DART_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
1561                continue;
1562            }
1563            if name.to_lowercase() == "content-type" {
1564                continue; // Already handled above.
1565            }
1566            let escaped_name = escape_dart(&name.to_lowercase());
1567            let escaped_value = escape_dart(value);
1568            let _ = writeln!(out, "    ioReq.headers.set('{escaped_name}', '{escaped_value}');");
1569        }
1570
1571        // Add cookies.
1572        if !ctx.cookies.is_empty() {
1573            let mut cookie_pairs: Vec<(&String, &String)> = ctx.cookies.iter().collect();
1574            cookie_pairs.sort_by_key(|(k, _)| k.as_str());
1575            let cookie_str: Vec<String> = cookie_pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
1576            let cookie_header = escape_dart(&cookie_str.join("; "));
1577            let _ = writeln!(out, "    ioReq.headers.set('cookie', '{cookie_header}');");
1578        }
1579
1580        // Write body bytes if present (bypass charset-based encoding issues).
1581        if let Some(body) = ctx.body {
1582            let json_str = serde_json::to_string(body).unwrap_or_default();
1583            let escaped = escape_dart(&json_str);
1584            let _ = writeln!(out, "    final bodyBytes = utf8.encode('{escaped}');");
1585            let _ = writeln!(out, "    ioReq.add(bodyBytes);");
1586        }
1587
1588        let _ = writeln!(out, "    final ioResp = await ioReq.close();");
1589        // Drain the response body to bind `bodyStr` for assertion primitives and to
1590        // allow the server to cleanly close the connection (prevents RST packets).
1591        // Redirect responses have no body to drain — skip to avoid a potential hang.
1592        if !self.is_redirect.get() {
1593            let _ = writeln!(out, "    final bodyStr = await ioResp.transform(utf8.decoder).join();");
1594        };
1595    }
1596
1597    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
1598        let _ = writeln!(
1599            out,
1600            "    expect(ioResp.statusCode, equals({status}), reason: 'status code mismatch');"
1601        );
1602    }
1603
1604    /// Emit a single header assertion, handling special tokens `<<present>>`,
1605    /// `<<absent>>`, and `<<uuid>>`.
1606    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
1607        let escaped_name = escape_dart(&name.to_lowercase());
1608        match expected {
1609            "<<present>>" => {
1610                let _ = writeln!(
1611                    out,
1612                    "    expect(ioResp.headers.value('{escaped_name}'), isNotNull, reason: 'header {escaped_name} should be present');"
1613                );
1614            }
1615            "<<absent>>" => {
1616                let _ = writeln!(
1617                    out,
1618                    "    expect(ioResp.headers.value('{escaped_name}'), isNull, reason: 'header {escaped_name} should be absent');"
1619                );
1620            }
1621            "<<uuid>>" => {
1622                let _ = writeln!(
1623                    out,
1624                    "    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');"
1625                );
1626            }
1627            exact => {
1628                let escaped_value = escape_dart(exact);
1629                let _ = writeln!(
1630                    out,
1631                    "    expect(ioResp.headers.value('{escaped_name}'), contains('{escaped_value}'), reason: 'header {escaped_name} mismatch');"
1632                );
1633            }
1634        }
1635    }
1636
1637    /// Emit an exact-equality body assertion.
1638    ///
1639    /// String bodies are compared as decoded text; structured JSON bodies are
1640    /// compared via `jsonDecode`.
1641    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
1642        match expected {
1643            serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
1644                let json_str = serde_json::to_string(expected).unwrap_or_default();
1645                let escaped = escape_dart(&json_str);
1646                let _ = writeln!(out, "    final bodyJson = jsonDecode(bodyStr);");
1647                let _ = writeln!(out, "    final expectedJson = jsonDecode('{escaped}');");
1648                let _ = writeln!(
1649                    out,
1650                    "    expect(bodyJson, equals(expectedJson), reason: 'body mismatch');"
1651                );
1652            }
1653            serde_json::Value::String(s) => {
1654                let escaped = escape_dart(s);
1655                let _ = writeln!(
1656                    out,
1657                    "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
1658                );
1659            }
1660            other => {
1661                let escaped = escape_dart(&other.to_string());
1662                let _ = writeln!(
1663                    out,
1664                    "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
1665                );
1666            }
1667        }
1668    }
1669
1670    /// Emit partial-body assertions — every key in `expected` must match the
1671    /// corresponding field in the parsed JSON response.
1672    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
1673        let _ = writeln!(
1674            out,
1675            "    final partialJson = jsonDecode(bodyStr) as Map<String, dynamic>;"
1676        );
1677        if let Some(obj) = expected.as_object() {
1678            for (idx, (key, val)) in obj.iter().enumerate() {
1679                let escaped_key = escape_dart(key);
1680                let json_val = serde_json::to_string(val).unwrap_or_default();
1681                let escaped_val = escape_dart(&json_val);
1682                // Use an index-based variable name so keys with special characters
1683                // don't produce invalid Dart identifiers.
1684                let _ = writeln!(out, "    final _expectedField{idx} = jsonDecode('{escaped_val}');");
1685                let _ = writeln!(
1686                    out,
1687                    "    expect(partialJson['{escaped_key}'], equals(_expectedField{idx}), reason: 'partial body field \\'{escaped_key}\\' mismatch');"
1688                );
1689            }
1690        }
1691    }
1692
1693    /// Emit validation-error assertions for 422 responses.
1694    fn render_assert_validation_errors(
1695        &self,
1696        out: &mut String,
1697        _response_var: &str,
1698        errors: &[ValidationErrorExpectation],
1699    ) {
1700        let _ = writeln!(out, "    final errBody = jsonDecode(bodyStr) as Map<String, dynamic>;");
1701        let _ = writeln!(out, "    final errList = (errBody['errors'] ?? []) as List<dynamic>;");
1702        for ve in errors {
1703            let loc_dart: Vec<String> = ve.loc.iter().map(|s| format!("'{}'", escape_dart(s))).collect();
1704            let loc_str = loc_dart.join(", ");
1705            let escaped_msg = escape_dart(&ve.msg);
1706            let _ = writeln!(
1707                out,
1708                "    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}');"
1709            );
1710        }
1711    }
1712}
1713
1714/// Render a `package:test` `test(...)` block for an HTTP server fixture.
1715///
1716/// Delegates to the shared [`client::http_call::render_http_test`] driver via
1717/// [`DartTestClientRenderer`]. HTTP 101 (WebSocket upgrade) fixtures are emitted
1718/// as skip stubs before reaching the driver because `dart:io HttpClient` cannot
1719/// handle protocol-switch responses.
1720fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
1721    // HTTP 101 (WebSocket upgrade) — dart:io HttpClient cannot handle upgrade responses.
1722    if http.expected_response.status_code == 101 {
1723        let description = escape_dart(&fixture.description);
1724        let _ = writeln!(out, "  test('{description}', () {{");
1725        let _ = writeln!(
1726            out,
1727            "    markTestSkipped('Skipped: Dart HttpClient cannot handle 101 Switching Protocols responses');"
1728        );
1729        let _ = writeln!(out, "  }});");
1730        let _ = writeln!(out);
1731        return;
1732    }
1733
1734    // Pre-set `is_redirect` on the renderer so `render_call` can inject
1735    // `ioReq.followRedirects = false` for 3xx fixtures. The shared driver has no
1736    // concept of expected status code so we thread it through renderer state.
1737    let is_redirect = http.expected_response.status_code / 100 == 3;
1738    client::http_call::render_http_test(out, &DartTestClientRenderer::new(is_redirect), fixture);
1739}
1740
1741/// Infer a MIME type from a file path extension.
1742///
1743/// Returns `None` when the extension is unknown so the caller can supply a fallback.
1744/// Used in dart e2e tests when a fixture omits `mime_type` but uses a `file_path` arg.
1745fn mime_from_extension(path: &str) -> Option<&'static str> {
1746    let ext = path.rsplit('.').next()?;
1747    match ext.to_lowercase().as_str() {
1748        "docx" => Some("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
1749        "xlsx" => Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
1750        "pptx" => Some("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
1751        "pdf" => Some("application/pdf"),
1752        "txt" | "text" => Some("text/plain"),
1753        "html" | "htm" => Some("text/html"),
1754        "json" => Some("application/json"),
1755        "xml" => Some("application/xml"),
1756        "csv" => Some("text/csv"),
1757        "md" | "markdown" => Some("text/markdown"),
1758        "png" => Some("image/png"),
1759        "jpg" | "jpeg" => Some("image/jpeg"),
1760        "gif" => Some("image/gif"),
1761        "zip" => Some("application/zip"),
1762        "odt" => Some("application/vnd.oasis.opendocument.text"),
1763        "ods" => Some("application/vnd.oasis.opendocument.spreadsheet"),
1764        "odp" => Some("application/vnd.oasis.opendocument.presentation"),
1765        "rtf" => Some("application/rtf"),
1766        "epub" => Some("application/epub+zip"),
1767        "msg" => Some("application/vnd.ms-outlook"),
1768        "eml" => Some("message/rfc822"),
1769        _ => None,
1770    }
1771}
1772
1773/// Emit Dart constructors for a batch item array (`BatchBytesItem` or `BatchFileItem`).
1774///
1775/// Returns a Dart list literal like:
1776/// ```dart
1777/// [BatchBytesItem(content: Uint8List.fromList([72, 101, ...]), mimeType: 'text/plain')]
1778/// ```
1779fn emit_dart_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1780    let items: Vec<String> = arr
1781        .as_array()
1782        .map(|a| a.as_slice())
1783        .unwrap_or_default()
1784        .iter()
1785        .filter_map(|item| {
1786            let obj = item.as_object()?;
1787            match elem_type {
1788                "BatchBytesItem" => {
1789                    let content_bytes = obj
1790                        .get("content")
1791                        .and_then(|v| v.as_array())
1792                        .map(|arr| {
1793                            let nums: Vec<String> =
1794                                arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1795                            format!("Uint8List.fromList([{}])", nums.join(", "))
1796                        })
1797                        .unwrap_or_else(|| "Uint8List(0)".to_string());
1798                    let mime_type = obj
1799                        .get("mime_type")
1800                        .and_then(|v| v.as_str())
1801                        .unwrap_or("application/octet-stream");
1802                    Some(format!(
1803                        "BatchBytesItem(content: {content_bytes}, mimeType: '{}')",
1804                        escape_dart(mime_type)
1805                    ))
1806                }
1807                "BatchFileItem" => {
1808                    let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1809                    Some(format!("BatchFileItem(path: '{}')", escape_dart(path)))
1810                }
1811                _ => None,
1812            }
1813        })
1814        .collect();
1815    format!("[{}]", items.join(", "))
1816}
1817
1818/// Escape a string for embedding in a Dart single-quoted string literal.
1819pub(super) fn escape_dart(s: &str) -> String {
1820    s.replace('\\', "\\\\")
1821        .replace('\'', "\\'")
1822        .replace('\n', "\\n")
1823        .replace('\r', "\\r")
1824        .replace('\t', "\\t")
1825        .replace('$', "\\$")
1826}
1827
1828/// Derive the Dart top-level helper function name for constructing a mirror type from JSON.
1829///
1830/// The alef dart bridge-crate generator emits a Rust free function
1831/// `create_<snake_type>_from_json(json: String)` for each non-opaque mirror struct.
1832/// FRB generates the corresponding Dart function as `createTypeNameFromJson` (camelCase).
1833///
1834/// Example: `"ChatCompletionRequest"` → `"createChatCompletionRequestFromJson"`.
1835fn type_name_to_create_from_json_dart(type_name: &str) -> String {
1836    // Convert PascalCase type name to snake_case.
1837    let mut snake = String::with_capacity(type_name.len() + 8);
1838    for (i, ch) in type_name.char_indices() {
1839        if ch.is_uppercase() {
1840            if i > 0 {
1841                snake.push('_');
1842            }
1843            snake.extend(ch.to_lowercase());
1844        } else {
1845            snake.push(ch);
1846        }
1847    }
1848    // snake is now e.g. "chat_completion_request"
1849    // Full Rust function name: "create_chat_completion_request_from_json"
1850    let rust_fn = format!("create_{snake}_from_json");
1851    // Convert to Dart camelCase: "createChatCompletionRequestFromJson"
1852    rust_fn
1853        .split('_')
1854        .enumerate()
1855        .map(|(i, part)| {
1856            if i == 0 {
1857                part.to_string()
1858            } else {
1859                let mut chars = part.chars();
1860                match chars.next() {
1861                    None => String::new(),
1862                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1863                }
1864            }
1865        })
1866        .collect::<Vec<_>>()
1867        .join("")
1868}