1use crate::config::E2eConfig;
4use crate::escape::{escape_js, sanitize_filename, sanitize_ident};
5use crate::field_access::FieldResolver;
6use crate::fixture::{Assertion, Fixture, FixtureGroup};
7use alef_core::backend::GeneratedFile;
8use alef_core::config::AlefConfig;
9use anyhow::Result;
10use std::fmt::Write as FmtWrite;
11use std::path::PathBuf;
12
13use super::E2eCodegen;
14
15pub struct TypeScriptCodegen;
17
18impl E2eCodegen for TypeScriptCodegen {
19 fn generate(
20 &self,
21 groups: &[FixtureGroup],
22 e2e_config: &E2eConfig,
23 _alef_config: &AlefConfig,
24 ) -> Result<Vec<GeneratedFile>> {
25 let output_base = PathBuf::from(&e2e_config.output).join(self.language_name());
26 let tests_base = output_base.join("tests");
27
28 let mut files = Vec::new();
29
30 let call = &e2e_config.call;
32 let overrides = call.overrides.get("node");
33 let module_path = overrides
34 .and_then(|o| o.module.as_ref())
35 .cloned()
36 .unwrap_or_else(|| call.module.clone());
37 let function_name = overrides
38 .and_then(|o| o.function.as_ref())
39 .cloned()
40 .unwrap_or_else(|| call.function.clone());
41 let result_var = &call.result_var;
42 let is_async = call.r#async;
43
44 let node_pkg = e2e_config.packages.get("node");
46 let pkg_path = node_pkg
47 .and_then(|p| p.path.as_ref())
48 .cloned()
49 .unwrap_or_else(|| "../../packages/typescript".to_string());
50 let pkg_name = node_pkg
51 .and_then(|p| p.name.as_ref())
52 .cloned()
53 .unwrap_or_else(|| module_path.clone());
54
55 files.push(GeneratedFile {
57 path: output_base.join("package.json"),
58 content: render_package_json(&pkg_name, &pkg_path),
59 generated_header: false,
60 });
61
62 files.push(GeneratedFile {
64 path: output_base.join("tsconfig.json"),
65 content: render_tsconfig(),
66 generated_header: false,
67 });
68
69 files.push(GeneratedFile {
71 path: output_base.join("vitest.config.ts"),
72 content: render_vitest_config(),
73 generated_header: true,
74 });
75
76 let options_type = overrides.and_then(|o| o.options_type.clone());
78 let field_resolver = FieldResolver::new(&e2e_config.fields, &e2e_config.fields_optional);
79
80 for group in groups {
82 let active: Vec<&Fixture> = group
83 .fixtures
84 .iter()
85 .filter(|f| f.skip.as_ref().is_none_or(|s| !s.should_skip("node")))
86 .collect();
87
88 if active.is_empty() {
89 continue;
90 }
91
92 let filename = format!("{}.test.ts", sanitize_filename(&group.category));
93 let content = render_test_file(
94 &group.category,
95 &active,
96 &module_path,
97 &function_name,
98 result_var,
99 is_async,
100 &e2e_config.call.args,
101 options_type.as_deref(),
102 &field_resolver,
103 );
104 files.push(GeneratedFile {
105 path: tests_base.join(filename),
106 content,
107 generated_header: true,
108 });
109 }
110
111 Ok(files)
112 }
113
114 fn language_name(&self) -> &'static str {
115 "node"
116 }
117}
118
119fn render_package_json(pkg_name: &str, pkg_path: &str) -> String {
120 format!(
121 r#"{{
122 "name": "{pkg_name}-e2e-typescript",
123 "version": "0.1.0",
124 "private": true,
125 "type": "module",
126 "scripts": {{
127 "test": "vitest run"
128 }},
129 "devDependencies": {{
130 "{pkg_name}": "file:{pkg_path}",
131 "vitest": "^3.0.0"
132 }}
133}}
134"#
135 )
136}
137
138fn render_tsconfig() -> String {
139 r#"{
140 "compilerOptions": {
141 "target": "ES2022",
142 "module": "ESNext",
143 "moduleResolution": "bundler",
144 "strict": true,
145 "esModuleInterop": true,
146 "skipLibCheck": true,
147 "noUncheckedIndexedAccess": true
148 },
149 "include": ["tests/**/*.ts", "vitest.config.ts"]
150}
151"#
152 .to_string()
153}
154
155fn render_vitest_config() -> String {
156 r#"import { defineConfig } from 'vitest/config';
157
158export default defineConfig({
159 test: {
160 include: ['tests/**/*.test.ts'],
161 },
162});
163"#
164 .to_string()
165}
166
167#[allow(clippy::too_many_arguments)]
168fn render_test_file(
169 category: &str,
170 fixtures: &[&Fixture],
171 module_path: &str,
172 function_name: &str,
173 result_var: &str,
174 is_async: bool,
175 args: &[crate::config::ArgMapping],
176 options_type: Option<&str>,
177 field_resolver: &FieldResolver,
178) -> String {
179 let mut out = String::new();
180 let _ = writeln!(out, "import {{ describe, it, expect }} from 'vitest';");
181
182 let needs_options_import = options_type.is_some()
184 && fixtures.iter().any(|f| {
185 args.iter()
186 .any(|arg| arg.arg_type == "json_object" && f.input.get(&arg.field).is_some_and(|v| !v.is_null()))
187 });
188
189 if let (true, Some(opts_type)) = (needs_options_import, options_type) {
190 let _ = writeln!(
191 out,
192 "import {{ {function_name}, type {opts_type} }} from '{module_path}';"
193 );
194 } else {
195 let _ = writeln!(out, "import {{ {function_name} }} from '{module_path}';");
196 }
197 let _ = writeln!(out);
198 let _ = writeln!(out, "describe('{category}', () => {{");
199
200 for (i, fixture) in fixtures.iter().enumerate() {
201 render_test_case(
202 &mut out,
203 fixture,
204 function_name,
205 result_var,
206 is_async,
207 args,
208 options_type,
209 field_resolver,
210 );
211 if i + 1 < fixtures.len() {
212 let _ = writeln!(out);
213 }
214 }
215
216 let _ = writeln!(out, "}});");
217 out
218}
219
220fn render_test_case(
221 out: &mut String,
222 fixture: &Fixture,
223 function_name: &str,
224 result_var: &str,
225 is_async: bool,
226 args: &[crate::config::ArgMapping],
227 options_type: Option<&str>,
228 field_resolver: &FieldResolver,
229) {
230 let test_name = sanitize_ident(&fixture.id);
231 let description = fixture.description.replace('\'', "\\'");
232 let async_kw = if is_async { "async " } else { "" };
233 let await_kw = if is_async { "await " } else { "" };
234
235 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
237
238 if expects_error {
239 let _ = writeln!(out, " it('{test_name}: {description}', {async_kw}() => {{");
240 let args_str = build_args_string(&fixture.input, args, options_type);
241 if is_async {
242 let _ = writeln!(
243 out,
244 " await expect({async_kw}() => {await_kw}{function_name}({args_str})).rejects.toThrow();"
245 );
246 } else {
247 let _ = writeln!(out, " expect(() => {function_name}({args_str})).toThrow();");
248 }
249 let _ = writeln!(out, " }});");
250 return;
251 }
252
253 let _ = writeln!(out, " it('{test_name}: {description}', {async_kw}() => {{");
254
255 let args_str = build_args_string(&fixture.input, args, options_type);
257
258 let _ = writeln!(out, " const {result_var} = {await_kw}{function_name}({args_str});");
260
261 for assertion in &fixture.assertions {
263 render_assertion(out, assertion, result_var, field_resolver);
264 }
265
266 let _ = writeln!(out, " }});");
267}
268
269fn build_args_string(
270 input: &serde_json::Value,
271 args: &[crate::config::ArgMapping],
272 options_type: Option<&str>,
273) -> String {
274 if args.is_empty() {
275 return json_to_js(input);
277 }
278
279 let parts: Vec<String> = args
280 .iter()
281 .filter_map(|arg| {
282 let val = input.get(&arg.field)?;
283 if val.is_null() && arg.optional {
284 return None;
285 }
286 if arg.arg_type == "json_object" {
288 if let Some(opts_type) = options_type {
289 return Some(format!("{} as {opts_type}", json_to_js(val)));
290 }
291 }
292 Some(json_to_js(val))
293 })
294 .collect();
295
296 parts.join(", ")
297}
298
299fn render_assertion(out: &mut String, assertion: &Assertion, result_var: &str, field_resolver: &FieldResolver) {
300 let field_expr = match &assertion.field {
301 Some(f) if !f.is_empty() => field_resolver.accessor(f, "typescript", result_var),
302 _ => result_var.to_string(),
303 };
304
305 match assertion.assertion_type.as_str() {
306 "equals" => {
307 if let Some(expected) = &assertion.value {
308 let js_val = json_to_js(expected);
309 let _ = writeln!(out, " expect({field_expr}.trim()).toBe({js_val});");
310 }
311 }
312 "contains" => {
313 if let Some(expected) = &assertion.value {
314 let js_val = json_to_js(expected);
315 let _ = writeln!(out, " expect({field_expr}).toContain({js_val});");
316 }
317 }
318 "contains_all" => {
319 if let Some(values) = &assertion.values {
320 for val in values {
321 let js_val = json_to_js(val);
322 let _ = writeln!(out, " expect({field_expr}).toContain({js_val});");
323 }
324 }
325 }
326 "not_contains" => {
327 if let Some(expected) = &assertion.value {
328 let js_val = json_to_js(expected);
329 let _ = writeln!(out, " expect({field_expr}).not.toContain({js_val});");
330 }
331 }
332 "not_empty" => {
333 let _ = writeln!(out, " expect({field_expr}.length).toBeGreaterThan(0);");
334 }
335 "starts_with" => {
336 if let Some(expected) = &assertion.value {
337 let js_val = json_to_js(expected);
338 let _ = writeln!(out, " expect({field_expr}.startsWith({js_val})).toBe(true);");
339 }
340 }
341 "not_error" => {
342 }
344 "error" => {
345 }
347 other => {
348 let _ = writeln!(out, " // TODO: unsupported assertion type: {other}");
349 }
350 }
351}
352
353fn json_to_js(value: &serde_json::Value) -> String {
355 match value {
356 serde_json::Value::String(s) => format!("\"{}\"", escape_js(s)),
357 serde_json::Value::Bool(b) => b.to_string(),
358 serde_json::Value::Number(n) => n.to_string(),
359 serde_json::Value::Null => "null".to_string(),
360 serde_json::Value::Array(arr) => {
361 let items: Vec<String> = arr.iter().map(json_to_js).collect();
362 format!("[{}]", items.join(", "))
363 }
364 serde_json::Value::Object(map) => {
365 let entries: Vec<String> = map.iter().map(|(k, v)| format!("{}: {}", k, json_to_js(v))).collect();
366 format!("{{ {} }}", entries.join(", "))
367 }
368 }
369}