1use crate::config::E2eConfig;
4use crate::escape::{escape_js, sanitize_filename, sanitize_ident};
5use crate::field_access::FieldResolver;
6use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup};
7use alef_core::backend::GeneratedFile;
8use alef_core::config::AlefConfig;
9use anyhow::Result;
10use heck::ToUpperCamelCase;
11use std::fmt::Write as FmtWrite;
12use std::path::PathBuf;
13
14use super::E2eCodegen;
15
16pub struct TypeScriptCodegen;
18
19impl E2eCodegen for TypeScriptCodegen {
20 fn generate(
21 &self,
22 groups: &[FixtureGroup],
23 e2e_config: &E2eConfig,
24 _alef_config: &AlefConfig,
25 ) -> Result<Vec<GeneratedFile>> {
26 let output_base = PathBuf::from(e2e_config.effective_output()).join(self.language_name());
27 let tests_base = output_base.join("tests");
28
29 let mut files = Vec::new();
30
31 let call = &e2e_config.call;
33 let overrides = call.overrides.get("node");
34 let module_path = overrides
35 .and_then(|o| o.module.as_ref())
36 .cloned()
37 .unwrap_or_else(|| call.module.clone());
38 let function_name = overrides
39 .and_then(|o| o.function.as_ref())
40 .cloned()
41 .unwrap_or_else(|| call.function.clone());
42 let result_var = &call.result_var;
43 let is_async = call.r#async;
44 let client_factory = overrides.and_then(|o| o.client_factory.as_deref());
45
46 let node_pkg = e2e_config.resolve_package("node");
48 let pkg_path = node_pkg
49 .as_ref()
50 .and_then(|p| p.path.as_ref())
51 .cloned()
52 .unwrap_or_else(|| "../../packages/typescript".to_string());
53 let pkg_name = node_pkg
54 .as_ref()
55 .and_then(|p| p.name.as_ref())
56 .cloned()
57 .unwrap_or_else(|| module_path.clone());
58 let pkg_version = node_pkg
59 .as_ref()
60 .and_then(|p| p.version.as_ref())
61 .cloned()
62 .unwrap_or_else(|| "0.1.0".to_string());
63
64 let has_http_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| f.is_http_test());
66
67 files.push(GeneratedFile {
69 path: output_base.join("package.json"),
70 content: render_package_json(
71 &pkg_name,
72 &pkg_path,
73 &pkg_version,
74 e2e_config.dep_mode,
75 has_http_fixtures,
76 ),
77 generated_header: false,
78 });
79
80 files.push(GeneratedFile {
82 path: output_base.join("tsconfig.json"),
83 content: render_tsconfig(),
84 generated_header: false,
85 });
86
87 files.push(GeneratedFile {
89 path: output_base.join("vitest.config.ts"),
90 content: render_vitest_config(client_factory.is_some()),
91 generated_header: true,
92 });
93
94 if client_factory.is_some() {
96 files.push(GeneratedFile {
97 path: output_base.join("globalSetup.ts"),
98 content: render_global_setup(),
99 generated_header: true,
100 });
101 }
102
103 let options_type = overrides.and_then(|o| o.options_type.clone());
105 let field_resolver = FieldResolver::new(
106 &e2e_config.fields,
107 &e2e_config.fields_optional,
108 &e2e_config.result_fields,
109 &e2e_config.fields_array,
110 );
111
112 for group in groups {
114 let active: Vec<&Fixture> = group
115 .fixtures
116 .iter()
117 .filter(|f| f.skip.as_ref().is_none_or(|s| !s.should_skip("node")))
118 .collect();
119
120 if active.is_empty() {
121 continue;
122 }
123
124 let filename = format!("{}.test.ts", sanitize_filename(&group.category));
125 let content = render_test_file(
126 &group.category,
127 &active,
128 &module_path,
129 &pkg_name,
130 &function_name,
131 result_var,
132 is_async,
133 &e2e_config.call.args,
134 options_type.as_deref(),
135 &field_resolver,
136 client_factory,
137 );
138 files.push(GeneratedFile {
139 path: tests_base.join(filename),
140 content,
141 generated_header: true,
142 });
143 }
144
145 Ok(files)
146 }
147
148 fn language_name(&self) -> &'static str {
149 "node"
150 }
151}
152
153fn render_package_json(
154 pkg_name: &str,
155 _pkg_path: &str,
156 pkg_version: &str,
157 dep_mode: crate::config::DependencyMode,
158 has_http_fixtures: bool,
159) -> String {
160 let dep_value = match dep_mode {
161 crate::config::DependencyMode::Registry => pkg_version.to_string(),
162 crate::config::DependencyMode::Local => "workspace:*".to_string(),
163 };
164 let _ = has_http_fixtures; format!(
166 r#"{{
167 "name": "{pkg_name}-e2e-typescript",
168 "version": "0.1.0",
169 "private": true,
170 "type": "module",
171 "scripts": {{
172 "test": "vitest run"
173 }},
174 "devDependencies": {{
175 "{pkg_name}": "{dep_value}",
176 "vitest": "^3.0.0"
177 }}
178}}
179"#
180 )
181}
182
183fn render_tsconfig() -> String {
184 r#"{
185 "compilerOptions": {
186 "target": "ES2022",
187 "module": "ESNext",
188 "moduleResolution": "bundler",
189 "strict": true,
190 "strictNullChecks": false,
191 "esModuleInterop": true,
192 "skipLibCheck": true
193 },
194 "include": ["tests/**/*.ts", "vitest.config.ts"]
195}
196"#
197 .to_string()
198}
199
200fn render_vitest_config(with_global_setup: bool) -> String {
201 if with_global_setup {
202 r#"// This file is auto-generated by alef. DO NOT EDIT.
203import { defineConfig } from 'vitest/config';
204
205export default defineConfig({
206 test: {
207 include: ['tests/**/*.test.ts'],
208 globalSetup: './globalSetup.ts',
209 },
210});
211"#
212 .to_string()
213 } else {
214 r#"// This file is auto-generated by alef. DO NOT EDIT.
215import { defineConfig } from 'vitest/config';
216
217export default defineConfig({
218 test: {
219 include: ['tests/**/*.test.ts'],
220 },
221});
222"#
223 .to_string()
224 }
225}
226
227fn render_global_setup() -> String {
228 r#"// This file is auto-generated by alef. DO NOT EDIT.
229import { spawn } from 'child_process';
230import { resolve } from 'path';
231
232let serverProcess;
233
234export async function setup() {
235 // Mock server binary must be pre-built (e.g. by CI or `cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release`)
236 serverProcess = spawn(
237 resolve(__dirname, '../rust/target/release/mock-server'),
238 [resolve(__dirname, '../../fixtures')],
239 { stdio: ['pipe', 'pipe', 'inherit'] }
240 );
241
242 const url = await new Promise((resolve, reject) => {
243 serverProcess.stdout.on('data', (data) => {
244 const match = data.toString().match(/MOCK_SERVER_URL=(.*)/);
245 if (match) resolve(match[1].trim());
246 });
247 setTimeout(() => reject(new Error('Mock server startup timeout')), 30000);
248 });
249
250 process.env.MOCK_SERVER_URL = url;
251}
252
253export async function teardown() {
254 if (serverProcess) {
255 serverProcess.stdin.end();
256 serverProcess.kill();
257 }
258}
259"#
260 .to_string()
261}
262
263#[allow(clippy::too_many_arguments)]
264fn render_test_file(
265 category: &str,
266 fixtures: &[&Fixture],
267 module_path: &str,
268 pkg_name: &str,
269 function_name: &str,
270 result_var: &str,
271 is_async: bool,
272 args: &[crate::config::ArgMapping],
273 options_type: Option<&str>,
274 field_resolver: &FieldResolver,
275 client_factory: Option<&str>,
276) -> String {
277 let mut out = String::new();
278 let _ = writeln!(out, "// This file is auto-generated by alef. DO NOT EDIT.");
279 let _ = writeln!(out, "import {{ describe, it, expect }} from 'vitest';");
280
281 let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
282 let has_non_http_fixtures = fixtures.iter().any(|f| !f.is_http_test());
283
284 let needs_options_import = options_type.is_some()
286 && fixtures.iter().any(|f| {
287 args.iter().any(|arg| {
288 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
289 let val = if field == "input" {
290 Some(&f.input)
291 } else {
292 f.input.get(field)
293 };
294 arg.arg_type == "json_object" && val.is_some_and(|v| !v.is_null())
295 })
296 });
297
298 let handle_constructors: Vec<String> = args
300 .iter()
301 .filter(|arg| arg.arg_type == "handle")
302 .map(|arg| format!("create{}", arg.name.to_upper_camel_case()))
303 .collect();
304
305 if has_non_http_fixtures {
307 let mut imports: Vec<String> = if let Some(factory) = client_factory {
309 vec![factory.to_string()]
310 } else {
311 vec![function_name.to_string()]
312 };
313 for ctor in &handle_constructors {
314 if !imports.contains(ctor) {
315 imports.push(ctor.clone());
316 }
317 }
318
319 let _ = module_path; if let (true, Some(opts_type)) = (needs_options_import, options_type) {
323 imports.push(format!("type {opts_type}"));
324 let imports_str = imports.join(", ");
325 let _ = writeln!(out, "import {{ {imports_str} }} from '{pkg_name}';");
326 } else {
327 let imports_str = imports.join(", ");
328 let _ = writeln!(out, "import {{ {imports_str} }} from '{pkg_name}';");
329 }
330 }
331
332 let _ = writeln!(out);
333 let _ = writeln!(out, "describe('{category}', () => {{");
334
335 for (i, fixture) in fixtures.iter().enumerate() {
336 if fixture.is_http_test() {
337 render_http_test_case(&mut out, fixture);
338 } else {
339 render_test_case(
340 &mut out,
341 fixture,
342 function_name,
343 result_var,
344 client_factory,
345 is_async,
346 args,
347 options_type,
348 field_resolver,
349 );
350 }
351 if i + 1 < fixtures.len() {
352 let _ = writeln!(out);
353 }
354 }
355
356 let _ = has_http_fixtures;
358
359 let _ = writeln!(out, "}});");
360 out
361}
362
363fn render_http_test_case(out: &mut String, fixture: &Fixture) {
374 let Some(http) = &fixture.http else {
375 return;
376 };
377
378 let test_name = sanitize_ident(&fixture.id);
379 let description = fixture.description.replace('\'', "\\'");
380
381 let method = http.request.method.to_uppercase();
382 let path = &http.request.path;
383
384 let mut init_entries: Vec<String> = Vec::new();
386 init_entries.push(format!("method: '{method}'"));
387
388 if !http.request.headers.is_empty() {
390 let entries: Vec<String> = http
391 .request
392 .headers
393 .iter()
394 .map(|(k, v)| format!(" '{}': '{}'", escape_js(k), escape_js(v)))
395 .collect();
396 init_entries.push(format!("headers: {{\n{},\n }}", entries.join(",\n")));
397 }
398
399 if let Some(body) = &http.request.body {
401 let js_body = json_to_js(body);
402 init_entries.push(format!("body: JSON.stringify({js_body})"));
403 }
404
405 let _ = writeln!(out, " it('{test_name}: {description}', async () => {{");
406
407 let path_expr = if http.request.query_params.is_empty() {
409 format!("'{}'", escape_js(path))
410 } else {
411 let params: Vec<String> = http
412 .request
413 .query_params
414 .iter()
415 .map(|(k, v)| format!("{}={}", escape_js(k), escape_js(&json_value_to_query_string(v))))
416 .collect();
417 let qs = params.join("&");
418 format!("'{}?{}'", escape_js(path), qs)
419 };
420
421 let init_str = init_entries.join(", ");
422 let _ = writeln!(
423 out,
424 " const response = await app.request({path_expr}, {{ {init_str} }});"
425 );
426
427 let status = http.expected_response.status_code;
429 let _ = writeln!(out, " expect(response.status).toBe({status});");
430
431 if let Some(expected_body) = &http.expected_response.body {
433 let js_val = json_to_js(expected_body);
434 let _ = writeln!(out, " const data = await response.json();");
435 let _ = writeln!(out, " expect(data).toEqual({js_val});");
436 } else if let Some(partial) = &http.expected_response.body_partial {
437 let _ = writeln!(out, " const data = await response.json();");
438 if let Some(obj) = partial.as_object() {
439 for (key, val) in obj {
440 let js_key = escape_js(key);
441 let js_val = json_to_js(val);
442 let _ = writeln!(
443 out,
444 " expect((data as Record<string, unknown>)['{js_key}']).toEqual({js_val});"
445 );
446 }
447 }
448 }
449
450 for (header_name, header_value) in &http.expected_response.headers {
452 let lower_name = header_name.to_lowercase();
453 let escaped_name = escape_js(&lower_name);
454 match header_value.as_str() {
455 "<<present>>" => {
456 let _ = writeln!(
457 out,
458 " expect(response.headers.get('{escaped_name}')).not.toBeNull();"
459 );
460 }
461 "<<absent>>" => {
462 let _ = writeln!(out, " expect(response.headers.get('{escaped_name}')).toBeNull();");
463 }
464 "<<uuid>>" => {
465 let _ = writeln!(
466 out,
467 " expect(response.headers.get('{escaped_name}')).toMatch(/^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$/);"
468 );
469 }
470 exact => {
471 let escaped_val = escape_js(exact);
472 let _ = writeln!(
473 out,
474 " expect(response.headers.get('{escaped_name}')).toBe('{escaped_val}');"
475 );
476 }
477 }
478 }
479
480 if let Some(validation_errors) = &http.expected_response.validation_errors {
482 if !validation_errors.is_empty() {
483 let _ = writeln!(
484 out,
485 " const body = await response.json() as {{ detail?: unknown[] }};"
486 );
487 let _ = writeln!(out, " const errors = body.detail ?? [];");
488 for ve in validation_errors {
489 let loc_js: Vec<String> = ve.loc.iter().map(|s| format!("'{}'", escape_js(s))).collect();
490 let loc_str = loc_js.join(", ");
491 let escaped_msg = escape_js(&ve.msg);
492 let _ = writeln!(
493 out,
494 " expect((errors as Array<Record<string, unknown>>).some((e) => JSON.stringify(e['loc']) === JSON.stringify([{loc_str}]) && String(e['msg']).includes('{escaped_msg}'))).toBe(true);"
495 );
496 }
497 }
498 }
499
500 let _ = writeln!(out, " }});");
501}
502
503fn json_value_to_query_string(value: &serde_json::Value) -> String {
505 match value {
506 serde_json::Value::String(s) => s.clone(),
507 serde_json::Value::Bool(b) => b.to_string(),
508 serde_json::Value::Number(n) => n.to_string(),
509 serde_json::Value::Null => String::new(),
510 other => other.to_string(),
511 }
512}
513
514#[allow(clippy::too_many_arguments)]
519fn render_test_case(
520 out: &mut String,
521 fixture: &Fixture,
522 function_name: &str,
523 result_var: &str,
524 client_factory: Option<&str>,
525 is_async: bool,
526 args: &[crate::config::ArgMapping],
527 options_type: Option<&str>,
528 field_resolver: &FieldResolver,
529) {
530 let test_name = sanitize_ident(&fixture.id);
531 let description = fixture.description.replace('\'', "\\'");
532 let async_kw = if is_async { "async " } else { "" };
533 let await_kw = if is_async { "await " } else { "" };
534
535 let (mut setup_lines, args_str) = build_args_and_setup(&fixture.input, args, options_type, &fixture.id);
537
538 let mut visitor_arg = String::new();
540 if let Some(visitor_spec) = &fixture.visitor {
541 visitor_arg = build_typescript_visitor(&mut setup_lines, visitor_spec);
542 }
543
544 let final_args = if visitor_arg.is_empty() {
545 args_str
546 } else if args_str.is_empty() {
547 format!("{{ visitor: {visitor_arg} }}")
548 } else {
549 format!("{args_str}, {{ visitor: {visitor_arg} }}")
550 };
551
552 let call_expr = if client_factory.is_some() {
553 format!("client.{function_name}({final_args})")
554 } else {
555 format!("{function_name}({final_args})")
556 };
557
558 let base_url_expr = format!("`${{process.env.MOCK_SERVER_URL}}/fixtures/{}`", fixture.id);
560
561 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
563
564 if expects_error {
565 let _ = writeln!(out, " it('{test_name}: {description}', async () => {{");
566 if let Some(factory) = client_factory {
567 let _ = writeln!(out, " const client = {factory}('test-key', {base_url_expr});");
568 }
569 let _ = writeln!(out, " await expect(async () => {{");
572 for line in &setup_lines {
573 let _ = writeln!(out, " {line}");
574 }
575 let _ = writeln!(out, " await {call_expr};");
576 let _ = writeln!(out, " }}).rejects.toThrow();");
577 let _ = writeln!(out, " }});");
578 return;
579 }
580
581 let _ = writeln!(out, " it('{test_name}: {description}', {async_kw}() => {{");
582
583 if let Some(factory) = client_factory {
584 let _ = writeln!(out, " const client = {factory}('test-key', {base_url_expr});");
585 }
586
587 for line in &setup_lines {
588 let _ = writeln!(out, " {line}");
589 }
590
591 let has_usable_assertion = fixture.assertions.iter().any(|a| {
593 if a.assertion_type == "not_error" || a.assertion_type == "error" {
594 return false;
595 }
596 match &a.field {
597 Some(f) if !f.is_empty() => field_resolver.is_valid_for_result(f),
598 _ => true,
599 }
600 });
601
602 if has_usable_assertion {
603 let _ = writeln!(out, " const {result_var} = {await_kw}{call_expr};");
604 } else {
605 let _ = writeln!(out, " {await_kw}{call_expr};");
606 }
607
608 for assertion in &fixture.assertions {
610 render_assertion(out, assertion, result_var, field_resolver);
611 }
612
613 let _ = writeln!(out, " }});");
614}
615
616fn build_args_and_setup(
620 input: &serde_json::Value,
621 args: &[crate::config::ArgMapping],
622 options_type: Option<&str>,
623 fixture_id: &str,
624) -> (Vec<String>, String) {
625 if args.is_empty() {
626 return (Vec::new(), json_to_js(input));
628 }
629
630 let mut setup_lines: Vec<String> = Vec::new();
631 let mut parts: Vec<String> = Vec::new();
632
633 for arg in args {
634 if arg.arg_type == "mock_url" {
635 setup_lines.push(format!(
636 "const {} = `${{process.env.MOCK_SERVER_URL}}/fixtures/{fixture_id}`;",
637 arg.name,
638 ));
639 parts.push(arg.name.clone());
640 continue;
641 }
642
643 if arg.arg_type == "handle" {
644 let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
646 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
647 let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
648 if config_value.is_null()
649 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
650 {
651 setup_lines.push(format!("const {} = {constructor_name}(null);", arg.name));
652 } else {
653 let literal = json_to_js_camel(config_value);
656 setup_lines.push(format!("const {name}Config = {literal};", name = arg.name,));
657 setup_lines.push(format!(
658 "const {} = {constructor_name}({name}Config);",
659 arg.name,
660 name = arg.name,
661 ));
662 }
663 parts.push(arg.name.clone());
664 continue;
665 }
666
667 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
668 let val = if field == "input" {
670 Some(input)
671 } else {
672 input.get(field)
673 };
674 match val {
675 None | Some(serde_json::Value::Null) if arg.optional => {
676 continue;
678 }
679 None | Some(serde_json::Value::Null) => {
680 let default_val = match arg.arg_type.as_str() {
682 "string" => "\"\"".to_string(),
683 "int" | "integer" => "0".to_string(),
684 "float" | "number" => "0.0".to_string(),
685 "bool" | "boolean" => "false".to_string(),
686 _ => "null".to_string(),
687 };
688 parts.push(default_val);
689 }
690 Some(v) => {
691 if arg.arg_type == "json_object" {
693 if let Some(opts_type) = options_type {
694 parts.push(format!("{} as {opts_type}", json_to_js(v)));
695 continue;
696 }
697 }
698 parts.push(json_to_js(v));
699 }
700 }
701 }
702
703 (setup_lines, parts.join(", "))
704}
705
706fn render_assertion(out: &mut String, assertion: &Assertion, result_var: &str, field_resolver: &FieldResolver) {
707 if let Some(f) = &assertion.field {
709 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
710 let _ = writeln!(out, " // skipped: field '{f}' not available on result type");
711 return;
712 }
713 }
714
715 let field_expr = match &assertion.field {
716 Some(f) if !f.is_empty() => field_resolver.accessor(f, "typescript", result_var),
717 _ => result_var.to_string(),
718 };
719
720 match assertion.assertion_type.as_str() {
721 "equals" => {
722 if let Some(expected) = &assertion.value {
723 let js_val = json_to_js(expected);
724 if expected.is_string() {
727 let resolved = assertion.field.as_deref().unwrap_or("");
728 if !resolved.is_empty() && field_resolver.is_optional(field_resolver.resolve(resolved)) {
729 let _ = writeln!(out, " expect(({field_expr} ?? \"\").trim()).toBe({js_val});");
730 } else {
731 let _ = writeln!(out, " expect({field_expr}.trim()).toBe({js_val});");
732 }
733 } else {
734 let _ = writeln!(out, " expect({field_expr}).toBe({js_val});");
735 }
736 }
737 }
738 "contains" => {
739 if let Some(expected) = &assertion.value {
740 let js_val = json_to_js(expected);
741 let resolved = assertion.field.as_deref().unwrap_or("");
743 if !resolved.is_empty()
744 && expected.is_string()
745 && field_resolver.is_optional(field_resolver.resolve(resolved))
746 {
747 let _ = writeln!(out, " expect({field_expr} ?? \"\").toContain({js_val});");
748 } else {
749 let _ = writeln!(out, " expect({field_expr}).toContain({js_val});");
750 }
751 }
752 }
753 "contains_all" => {
754 if let Some(values) = &assertion.values {
755 for val in values {
756 let js_val = json_to_js(val);
757 let _ = writeln!(out, " expect({field_expr}).toContain({js_val});");
758 }
759 }
760 }
761 "not_contains" => {
762 if let Some(expected) = &assertion.value {
763 let js_val = json_to_js(expected);
764 let _ = writeln!(out, " expect({field_expr}).not.toContain({js_val});");
765 }
766 }
767 "not_empty" => {
768 let resolved = assertion.field.as_deref().unwrap_or("");
770 if !resolved.is_empty() && field_resolver.is_optional(field_resolver.resolve(resolved)) {
771 let _ = writeln!(out, " expect(({field_expr} ?? \"\").length).toBeGreaterThan(0);");
772 } else {
773 let _ = writeln!(out, " expect({field_expr}.length).toBeGreaterThan(0);");
774 }
775 }
776 "is_empty" => {
777 let resolved = assertion.field.as_deref().unwrap_or("");
779 if !resolved.is_empty() && field_resolver.is_optional(field_resolver.resolve(resolved)) {
780 let _ = writeln!(out, " expect({field_expr} ?? \"\").toHaveLength(0);");
781 } else {
782 let _ = writeln!(out, " expect({field_expr}).toHaveLength(0);");
783 }
784 }
785 "contains_any" => {
786 if let Some(values) = &assertion.values {
787 let items: Vec<String> = values.iter().map(json_to_js).collect();
788 let arr_str = items.join(", ");
789 let _ = writeln!(
790 out,
791 " expect([{arr_str}].some((v) => {field_expr}.includes(v))).toBe(true);"
792 );
793 }
794 }
795 "greater_than" => {
796 if let Some(val) = &assertion.value {
797 let js_val = json_to_js(val);
798 let _ = writeln!(out, " expect({field_expr}).toBeGreaterThan({js_val});");
799 }
800 }
801 "less_than" => {
802 if let Some(val) = &assertion.value {
803 let js_val = json_to_js(val);
804 let _ = writeln!(out, " expect({field_expr}).toBeLessThan({js_val});");
805 }
806 }
807 "greater_than_or_equal" => {
808 if let Some(val) = &assertion.value {
809 let js_val = json_to_js(val);
810 let _ = writeln!(out, " expect({field_expr}).toBeGreaterThanOrEqual({js_val});");
811 }
812 }
813 "less_than_or_equal" => {
814 if let Some(val) = &assertion.value {
815 let js_val = json_to_js(val);
816 let _ = writeln!(out, " expect({field_expr}).toBeLessThanOrEqual({js_val});");
817 }
818 }
819 "starts_with" => {
820 if let Some(expected) = &assertion.value {
821 let js_val = json_to_js(expected);
822 let resolved = assertion.field.as_deref().unwrap_or("");
824 if !resolved.is_empty() && field_resolver.is_optional(field_resolver.resolve(resolved)) {
825 let _ = writeln!(
826 out,
827 " expect(({field_expr} ?? \"\").startsWith({js_val})).toBe(true);"
828 );
829 } else {
830 let _ = writeln!(out, " expect({field_expr}.startsWith({js_val})).toBe(true);");
831 }
832 }
833 }
834 "count_min" => {
835 if let Some(val) = &assertion.value {
836 if let Some(n) = val.as_u64() {
837 let _ = writeln!(out, " expect({field_expr}.length).toBeGreaterThanOrEqual({n});");
838 }
839 }
840 }
841 "count_equals" => {
842 if let Some(val) = &assertion.value {
843 if let Some(n) = val.as_u64() {
844 let _ = writeln!(out, " expect({field_expr}.length).toBe({n});");
845 }
846 }
847 }
848 "is_true" => {
849 let _ = writeln!(out, " expect({field_expr}).toBe(true);");
850 }
851 "not_error" => {
852 }
854 "error" => {
855 }
857 other => {
858 let _ = writeln!(out, " // TODO: unsupported assertion type: {other}");
859 }
860 }
861}
862
863fn json_to_js_camel(value: &serde_json::Value) -> String {
869 match value {
870 serde_json::Value::Object(map) => {
871 let entries: Vec<String> = map
872 .iter()
873 .map(|(k, v)| {
874 let camel_key = snake_to_camel(k);
875 let key = if camel_key
877 .chars()
878 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
879 && !camel_key.starts_with(|c: char| c.is_ascii_digit())
880 {
881 camel_key.clone()
882 } else {
883 format!("\"{}\"", escape_js(&camel_key))
884 };
885 format!("{key}: {}", json_to_js_camel(v))
886 })
887 .collect();
888 format!("{{ {} }}", entries.join(", "))
889 }
890 serde_json::Value::Array(arr) => {
891 let items: Vec<String> = arr.iter().map(json_to_js_camel).collect();
892 format!("[{}]", items.join(", "))
893 }
894 other => json_to_js(other),
896 }
897}
898
899fn snake_to_camel(s: &str) -> String {
901 let mut result = String::with_capacity(s.len());
902 let mut capitalize_next = false;
903 for ch in s.chars() {
904 if ch == '_' {
905 capitalize_next = true;
906 } else if capitalize_next {
907 result.extend(ch.to_uppercase());
908 capitalize_next = false;
909 } else {
910 result.push(ch);
911 }
912 }
913 result
914}
915
916fn json_to_js(value: &serde_json::Value) -> String {
918 match value {
919 serde_json::Value::String(s) => format!("\"{}\"", escape_js(s)),
920 serde_json::Value::Bool(b) => b.to_string(),
921 serde_json::Value::Number(n) => n.to_string(),
922 serde_json::Value::Null => "null".to_string(),
923 serde_json::Value::Array(arr) => {
924 let items: Vec<String> = arr.iter().map(json_to_js).collect();
925 format!("[{}]", items.join(", "))
926 }
927 serde_json::Value::Object(map) => {
928 let entries: Vec<String> = map
929 .iter()
930 .map(|(k, v)| {
931 let key = if k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
933 && !k.starts_with(|c: char| c.is_ascii_digit())
934 {
935 k.clone()
936 } else {
937 format!("\"{}\"", escape_js(k))
938 };
939 format!("{key}: {}", json_to_js(v))
940 })
941 .collect();
942 format!("{{ {} }}", entries.join(", "))
943 }
944 }
945}
946
947fn build_typescript_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
953 use std::fmt::Write as FmtWrite;
954 let mut visitor_obj = String::new();
955 let _ = writeln!(visitor_obj, "{{");
956 for (method_name, action) in &visitor_spec.callbacks {
957 emit_typescript_visitor_method(&mut visitor_obj, method_name, action);
958 }
959 let _ = writeln!(visitor_obj, " }}");
960
961 setup_lines.push(format!("const _testVisitor = {visitor_obj}"));
962 "_testVisitor".to_string()
963}
964
965fn emit_typescript_visitor_method(out: &mut String, method_name: &str, action: &CallbackAction) {
967 use std::fmt::Write as FmtWrite;
968
969 let camel_method = to_camel_case(method_name);
970 let params = match method_name {
971 "visit_link" => "ctx, href, text, title",
972 "visit_image" => "ctx, src, alt, title",
973 "visit_heading" => "ctx, level, text, id",
974 "visit_code_block" => "ctx, lang, code",
975 "visit_code_inline"
976 | "visit_strong"
977 | "visit_emphasis"
978 | "visit_strikethrough"
979 | "visit_underline"
980 | "visit_subscript"
981 | "visit_superscript"
982 | "visit_mark"
983 | "visit_button"
984 | "visit_summary"
985 | "visit_figcaption"
986 | "visit_definition_term"
987 | "visit_definition_description" => "ctx, text",
988 "visit_text" => "ctx, text",
989 "visit_list_item" => "ctx, ordered, marker, text",
990 "visit_blockquote" => "ctx, content, depth",
991 "visit_table_row" => "ctx, cells, isHeader",
992 "visit_custom_element" => "ctx, tagName, html",
993 "visit_form" => "ctx, actionUrl, method",
994 "visit_input" => "ctx, inputType, name, value",
995 "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
996 "visit_details" => "ctx, isOpen",
997 _ => "ctx",
998 };
999
1000 let _ = writeln!(
1001 out,
1002 " {camel_method}({params}): string | {{{{ custom: string }}}} {{"
1003 );
1004 match action {
1005 CallbackAction::Skip => {
1006 let _ = writeln!(out, " return \"skip\";");
1007 }
1008 CallbackAction::Continue => {
1009 let _ = writeln!(out, " return \"continue\";");
1010 }
1011 CallbackAction::PreserveHtml => {
1012 let _ = writeln!(out, " return \"preserve_html\";");
1013 }
1014 CallbackAction::Custom { output } => {
1015 let escaped = escape_js(output);
1016 let _ = writeln!(out, " return {{ custom: {escaped} }};");
1017 }
1018 CallbackAction::CustomTemplate { template } => {
1019 let _ = writeln!(out, " return {{ custom: `{template}` }};");
1020 }
1021 }
1022 let _ = writeln!(out, " }},");
1023}
1024
1025fn to_camel_case(snake: &str) -> String {
1027 use heck::ToLowerCamelCase;
1028 snake.to_lower_camel_case()
1029}