1use super::*;
6use crate::ts_build::{
8 and_expr, await_expr, binary, block, call, cond_expr, const_, expr_stmt, ident, if_, member,
9 method_call, num_lit, or_expr, str_lit, strict_eq,
10};
11use bynk_check::d1_migrations::MigrationFile;
12use bynk_ts::{
13 TsArrowBody, TsBinaryOp, TsBindingName, TsDecl, TsExpr, TsLit, TsObjectEntry, TsParam,
14 TsProgram, TsStmt, TsType, TsTypeMember,
15};
16
17pub(super) fn d1_migrations_args(files: Option<&Vec<MigrationFile>>) -> Vec<TsExpr> {
20 let Some(files) = files.filter(|f| !f.is_empty()) else {
21 return Vec::new();
22 };
23 vec![TsExpr::Array {
24 items: files
25 .iter()
26 .map(|f| TsExpr::Array {
27 items: vec![str_lit(f.name.clone()), str_lit(f.sql.clone())],
28 multiline: false,
29 })
30 .collect(),
31 multiline: true,
32 }]
33}
34
35pub(super) fn d1_migrations_text(files: &[MigrationFile]) -> String {
38 let pairs: Vec<String> = files
39 .iter()
40 .map(|f| {
41 format!(
42 "[{}, {}]",
43 bynk_project::json_string(&f.name),
44 bynk_project::json_string(&f.sql)
45 )
46 })
47 .collect();
48 if pairs.is_empty() {
49 String::new()
50 } else {
51 format!("[{}]", pairs.join(", "))
52 }
53}
54
55#[allow(clippy::too_many_arguments)]
68pub(super) fn sysdrive_driver(
69 kind: SysdriveKind<'_>,
70 sname: &str,
71 key: &str,
72 mut params: Vec<TsParam>,
73 body_stmts: Vec<TsStmt>,
74 url: TsExpr,
75 options: TsExpr,
76 binding: &str,
77 decode_fn: &str,
78 payload: Vec<TsExpr>,
79 signs_claims: bool,
80 sign_stmts: Vec<TsStmt>,
84 takes_as: bool,
87) -> TsStmt {
88 params.push(TsParam::new(
89 "__sub".to_string(),
90 Some(TsType::named("string")),
91 ));
92 if signs_claims {
95 params.push(TsParam::new(
96 "__claims".to_string(),
97 Some(TsType::named_with_args(
98 "globalThis.Record",
99 vec![TsType::named("string"), TsType::named("unknown")],
100 )),
101 ));
102 }
103 if takes_as {
104 params.push(TsParam::new(
105 "__as".to_string(),
106 Some(TsType::named("string")),
107 ));
108 }
109 let mut body = body_stmts;
110 body.extend(sign_stmts);
111 body.push(TsStmt::const_stmt(
112 TsBindingName::Ident("__h".to_string()),
113 None,
114 call(ident("__makeHarness"), vec![]),
115 None,
116 ));
117 body.push(TsStmt::const_stmt(
118 TsBindingName::Ident("__req".to_string()),
119 None,
120 TsExpr::New {
121 callee: Box::new(ident("globalThis.Request")),
122 args: vec![url, options],
123 },
124 None,
125 ));
126 body.push(TsStmt::const_stmt(
127 TsBindingName::Ident("__res".to_string()),
128 None,
129 await_expr(method_call(
130 member(member(ident("__h"), "env"), binding),
131 "fetch",
132 vec![ident("__req")],
133 )),
134 None,
135 ));
136 body.push(TsStmt::return_stmt(
137 Some(call(
138 ident(decode_fn),
139 std::iter::once(ident("__res")).chain(payload).collect(),
140 )),
141 None,
142 ));
143 TsStmt::decl(
144 TsDecl::Function {
145 name: sysdrive_name(kind, sname, key),
146 generics: Vec::new(),
147 params,
148 return_type: None,
149 body,
150 is_async: true,
151 inline: false,
152 },
153 None,
154 )
155}
156
157pub(super) fn build_run_function(entries: &[(String, String)]) -> Vec<TsStmt> {
189 let dispatch = |name: &str, runner_name: &str| {
190 TsStmt::if_stmt(
191 call(ident("want"), vec![str_lit(name.to_string())]),
192 block(vec![
193 const_("started", call(ident("__bynkCaseNow"), vec![])),
194 const_(
195 "r",
196 TsExpr::object_entries(vec![
197 TsObjectEntry::prop("name".to_string(), str_lit(name.to_string())),
198 TsObjectEntry::Spread(TsExpr::Paren(Box::new(await_expr(call(
199 ident(runner_name),
200 vec![],
201 ))))),
202 TsObjectEntry::prop(
203 "durationMs".to_string(),
204 call(ident("__bynkCaseSince"), vec![ident("started")]),
205 ),
206 ]),
207 ),
208 expr_stmt(method_call(ident("results"), "push", vec![ident("r")])),
209 if_(
210 ident("onCase"),
211 expr_stmt(call(ident("onCase"), vec![ident("r")])),
212 ),
213 ]),
214 None,
215 )
216 };
217 let mut body = vec![
218 TsStmt::const_stmt(
222 TsBindingName::Ident("results".to_string()),
223 Some(TsType::array(TsType::named("CaseResult"))),
224 TsExpr::array(vec![]),
225 None,
226 ),
227 const_(
228 "want",
229 TsExpr::Arrow {
230 params: vec![TsParam::new("n".to_string(), Some(TsType::named("string")))],
231 is_async: false,
232 generics: Vec::new(),
233 return_type: Some(TsType::named("boolean")),
234 body: Box::new(TsArrowBody::Expr(Box::new(or_expr(
235 strict_eq(ident("only"), ident("undefined")),
236 strict_eq(ident("only"), ident("n")),
237 )))),
238 },
239 ),
240 ];
241 body.extend(entries.iter().map(|(name, runner)| dispatch(name, runner)));
242 body.push(TsStmt::return_stmt(Some(ident("results")), None));
243 vec![
244 TestRuntimeModule::CaseTiming.splice(),
245 TsStmt::decl(
246 TsDecl::Export(Box::new(TsDecl::ConstDecl {
247 name: "__bynkCases".to_string(),
248 ty: Some(TsType::named("readonly string[]")),
249 init: TsExpr::array(
250 entries
251 .iter()
252 .map(|(name, _)| str_lit(name.clone()))
253 .collect(),
254 ),
255 })),
256 None,
257 ),
258 TsStmt::decl(
259 TsDecl::Export(Box::new(TsDecl::Function {
260 name: "run".to_string(),
261 generics: Vec::new(),
262 params: vec![
263 TsParam::optional("only".to_string(), Some(TsType::named("string"))),
264 TsParam::optional(
265 "onCase".to_string(),
266 Some(TsType::Fn {
267 rest: false,
268 names: vec![],
269 params: vec![TsType::named("CaseResult")],
270 ret: Box::new(TsType::named("void")),
271 }),
272 ),
273 ],
274 return_type: None,
275 body,
276 is_async: true,
277 inline: false,
278 })),
279 None,
280 ),
281 ]
282}
283
284pub(super) fn console_log(arg: TsExpr) -> TsStmt {
285 expr_stmt(method_call(ident("globalThis.console"), "log", vec![arg]))
286}
287
288struct DetachReports {
295 enabled: bool,
296}
297
298impl DetachReports {
299 fn drain(&self) -> Option<TsStmt> {
300 self.enabled.then(|| {
301 let reports = crate::ts_build::as_expr(
303 crate::ts_build::as_expr(ident("globalThis"), TsType::named("unknown")),
304 TsType::named(
305 "{ __bynkDetachedReports?: { kind: string; site: string; type: string | null; variant: string | null }[] }",
306 ),
307 );
308 let splice = crate::ts_build::call(
309 TsExpr::OptionalMember {
310 object: Box::new(member(crate::ts_build::paren(reports), "__bynkDetachedReports")),
311 property: "splice".to_string(),
312 },
313 vec![crate::ts_build::num_lit(0)],
314 );
315 crate::ts_build::const_(
316 "detached",
317 crate::ts_build::binary(
318 bynk_ts::TsBinaryOp::NullishCoalescing,
319 splice,
320 TsExpr::array(Vec::new()),
321 ),
322 )
323 })
324 }
325
326 fn entries(&self) -> Vec<TsObjectEntry> {
327 if !self.enabled {
328 return Vec::new();
329 }
330 vec![
331 TsObjectEntry::prop(
332 "detached_failures".to_string(),
333 detached_or_undefined(member(ident("detached"), "length")),
334 ),
335 TsObjectEntry::prop(
336 "detached".to_string(),
337 detached_or_undefined(ident("detached")),
338 ),
339 ]
340 }
341
342 fn wrap_ndjson(&self, stmts: Vec<TsStmt>) -> Vec<TsStmt> {
344 self.drain().into_iter().chain(stmts).collect()
345 }
346
347 fn wrap_human(&self, stmts: Vec<TsStmt>) -> Vec<TsStmt> {
349 self.wrap_ndjson(stmts)
350 .into_iter()
351 .chain(self.print())
352 .collect()
353 }
354
355 fn print(&self) -> Option<TsStmt> {
356 self.enabled.then(|| {
357 use crate::ts_build::{cond_expr, null_lit, str_lit, strict_eq};
358 let field = |name: &str| member(ident("d"), name);
359 let variant = cond_expr(
361 strict_eq(field("variant"), null_lit()),
362 str_lit(""),
363 TsExpr::template_lit(vec![".".to_string(), String::new()], vec![field("variant")]),
364 );
365 let outcome = cond_expr(
367 strict_eq(field("kind"), str_lit("err")),
368 TsExpr::template_lit(
369 vec!["returned Err (".to_string(), String::new(), ")".to_string()],
370 vec![field("type"), variant],
371 ),
372 str_lit("faulted"),
373 );
374 crate::ts_build::for_of(
375 "d",
376 ident("detached"),
377 expr_stmt(method_call(
378 ident("console"),
379 "log",
380 vec![TsExpr::template_lit(
381 vec![
382 " ! a detached effect ".to_string(),
383 " at ".to_string(),
384 String::new(),
385 ],
386 vec![outcome, field("site")],
387 )],
388 )),
389 )
390 })
391 }
392}
393
394pub fn emit_test_main(tests: &[RunnableTest], import_ext: ImportExt, pg: bool) -> TsProgram {
395 let ext = import_ext.as_str();
396 let mut program = TsProgram::new();
397 program.push(TsStmt::comment(
398 "Generated by bynk — do not edit by hand.",
399 None,
400 ));
401 program.push(TsStmt::comment("top-level test runner", None));
402 program.push(TsStmt::decl(
407 TsDecl::DeclareConst {
408 name: "process".to_string(),
409 ty: TsType::Object(vec![
410 TsTypeMember::method(
411 "exit",
412 vec![TsParam::new(
413 "code".to_string(),
414 Some(TsType::named("number")),
415 )],
416 TsType::named("never"),
417 ),
418 TsTypeMember::prop(
419 "env",
420 TsType::Object(vec![TsTypeMember::index(
421 "k",
422 TsType::named("string"),
423 TsType::union(vec![TsType::named("string"), TsType::named("undefined")]),
424 )]),
425 ),
426 ]),
427 },
428 None,
429 ));
430 let mut sorted: Vec<&RunnableTest> = tests.iter().collect();
431 sorted.sort_by(|a, b| a.target_name.cmp(&b.target_name));
432 for (i, t) in sorted.iter().enumerate() {
433 let module_stem = t
434 .module_path
435 .file_stem()
436 .and_then(|s| s.to_str())
437 .unwrap_or("test");
438 program.push(TsStmt::decl(
439 TsDecl::ImportNamespace {
440 type_only: false,
441 alias: case_alias(i),
442 from: sibling_specifier(module_stem, ext),
443 },
444 None,
445 ));
446 }
447
448 let mut main_body: Vec<TsStmt> = Vec::new();
455 let modules_items: Vec<TsExpr> = sorted
456 .iter()
457 .enumerate()
458 .map(|(i, t)| {
459 TsExpr::object(vec![
460 ("name".to_string(), str_lit(t.target_name.clone())),
461 (
462 "names".to_string(),
463 member(ident(case_alias(i)), "__bynkCases"),
464 ),
465 ("run".to_string(), member(ident(case_alias(i)), "run")),
466 ])
467 })
468 .collect();
469 main_body.push(const_("modules", TsExpr::multiline_array(modules_items)));
470 main_body.push(TsStmt::let_stmt(
471 TsBindingName::Ident("passed".to_string()),
472 None,
473 Some(num_lit("0")),
474 None,
475 ));
476 main_body.push(TsStmt::let_stmt(
477 TsBindingName::Ident("failed".to_string()),
478 None,
479 Some(num_lit("0")),
480 None,
481 ));
482 main_body.push(const_(
491 "PREFIX",
492 TsExpr::Lit(TsLit::Raw("\"system \\u00b7 \"".to_string())),
493 ));
494 main_body.push(const_(
495 "active",
496 method_call(
497 ident("modules"),
498 "filter",
499 vec![TsExpr::Arrow {
500 params: vec![TsParam::new("m".to_string(), None)],
501 is_async: false,
502 generics: Vec::new(),
503 return_type: None,
504 body: Box::new(TsArrowBody::Expr(Box::new(call(
505 ident("selected"),
506 vec![cond_expr(
507 method_call(
508 member(ident("m"), "name"),
509 "startsWith",
510 vec![ident("PREFIX")],
511 ),
512 method_call(
513 member(ident("m"), "name"),
514 "slice",
515 vec![member(ident("PREFIX"), "length")],
516 ),
517 member(ident("m"), "name"),
518 )],
519 )))),
520 }],
521 ),
522 ));
523
524 let emit_call = |entries: Vec<TsObjectEntry>| {
525 expr_stmt(call(ident("emit"), vec![TsExpr::object_entries(entries)]))
526 };
527 let remote = tests.iter().any(|t| t.remote);
530 let retries_entry = || {
531 remote.then(|| TsObjectEntry::prop("retries".to_string(), member(ident("r"), "retries")))
532 };
533 let generative = tests.iter().any(|t| t.generative);
539 let detach = DetachReports {
541 enabled: tests.iter().any(|t| t.detach_reports),
542 };
543 let generative_entries = || -> Vec<TsObjectEntry> {
544 if !generative {
545 return Vec::new();
546 }
547 ["kind", "seed", "counterexample"]
551 .into_iter()
552 .map(|k| TsObjectEntry::prop(k.to_string(), member(ident("r"), k)))
553 .collect()
554 };
555
556 let duration_entry =
560 || TsObjectEntry::prop("durationMs".to_string(), member(ident("r"), "durationMs"));
561
562 let snapshot_report = snapshot_report_decl(&sorted);
566
567 let mut ndjson_stmts = vec![
568 const_(
569 "emit",
570 TsExpr::Arrow {
571 params: vec![TsParam::new(
572 "o".to_string(),
573 Some(TsType::named("unknown")),
574 )],
575 is_async: false,
576 generics: Vec::new(),
577 return_type: None,
578 body: Box::new(TsArrowBody::Expr(Box::new(method_call(
579 ident("globalThis.console"),
580 "log",
581 vec![method_call(
582 ident("globalThis.JSON"),
583 "stringify",
584 vec![ident("o")],
585 )],
586 )))),
587 },
588 ),
589 emit_call(vec![
590 TsObjectEntry::prop("type".to_string(), str_lit("run-begin")),
591 TsObjectEntry::prop("suites".to_string(), member(ident("active"), "length")),
592 ]),
593 TsStmt::for_of(
594 "m",
595 ident("active"),
596 block(vec![
597 const_(
598 "integration",
599 method_call(
600 member(ident("m"), "name"),
601 "startsWith",
602 vec![ident("PREFIX")],
603 ),
604 ),
605 const_(
606 "suite",
607 cond_expr(
608 ident("integration"),
609 method_call(
610 member(ident("m"), "name"),
611 "slice",
612 vec![member(ident("PREFIX"), "length")],
613 ),
614 member(ident("m"), "name"),
615 ),
616 ),
617 const_(
618 "kind",
619 cond_expr(
620 ident("integration"),
621 str_lit("integration"),
622 str_lit("unit"),
623 ),
624 ),
625 emit_call(vec![
626 TsObjectEntry::prop("type".to_string(), str_lit("suite-begin")),
627 TsObjectEntry::prop("name".to_string(), ident("suite")),
628 TsObjectEntry::Shorthand("kind".to_string()),
629 TsObjectEntry::prop(
630 "tests".to_string(),
631 call(ident("planned"), vec![member(ident("m"), "names")]),
632 ),
633 ]),
634 TsStmt::decl(
635 TsDecl::Function {
636 name: "report".to_string(),
637 generics: Vec::new(),
638 params: vec![TsParam::new("r".to_string(), Some(TsType::named("Result")))],
639 return_type: None,
640 body: detach.wrap_ndjson(vec![TsStmt::if_else_same_line_stmt(
641 member(ident("r"), "pass"),
642 block(vec![
643 TsStmt::increment(ident("passed"), None),
644 emit_call(
645 vec![
646 TsObjectEntry::prop("type".to_string(), str_lit("case")),
647 TsObjectEntry::Shorthand("suite".to_string()),
648 TsObjectEntry::prop(
649 "name".to_string(),
650 member(ident("r"), "name"),
651 ),
652 TsObjectEntry::prop("outcome".to_string(), str_lit("pass")),
653 ]
654 .into_iter()
655 .chain(retries_entry())
656 .chain(detach.entries())
657 .chain(std::iter::once(duration_entry()))
658 .collect(),
659 ),
660 ]),
661 block(vec![
662 TsStmt::increment(ident("failed"), None),
663 emit_call(
664 vec![
665 TsObjectEntry::prop("type".to_string(), str_lit("case")),
666 TsObjectEntry::Shorthand("suite".to_string()),
667 TsObjectEntry::prop(
668 "name".to_string(),
669 member(ident("r"), "name"),
670 ),
671 TsObjectEntry::prop("outcome".to_string(), str_lit("fail")),
672 TsObjectEntry::prop(
673 "message".to_string(),
674 and_expr(
675 member(ident("r"), "error"),
676 member(member(ident("r"), "error"), "message"),
677 ),
678 ),
679 TsObjectEntry::prop(
680 "location".to_string(),
681 and_expr(
682 member(ident("r"), "error"),
683 member(member(ident("r"), "error"), "location"),
684 ),
685 ),
686 TsObjectEntry::prop(
689 "violation".to_string(),
690 and_expr(
691 member(ident("r"), "error"),
692 member(member(ident("r"), "error"), "violation"),
693 ),
694 ),
695 TsObjectEntry::prop(
697 "refusals".to_string(),
698 and_expr(
699 member(ident("r"), "error"),
700 member(member(ident("r"), "error"), "refusals"),
701 ),
702 ),
703 ]
704 .into_iter()
705 .chain(retries_entry())
706 .chain(detach.entries())
707 .chain(generative_entries())
708 .chain(std::iter::once(duration_entry()))
709 .collect(),
710 ),
711 ]),
712 None,
713 )]),
714 is_async: false,
715 inline: false,
716 },
717 None,
718 ),
719 expr_stmt(await_expr(call(
720 ident("runSelected"),
721 vec![member(ident("m"), "run"), ident("report")],
722 ))),
723 emit_call(vec![
724 TsObjectEntry::prop("type".to_string(), str_lit("suite-end")),
725 TsObjectEntry::prop("name".to_string(), ident("suite")),
726 ]),
727 ]),
728 None,
729 ),
730 emit_call(vec![
731 TsObjectEntry::prop("type".to_string(), str_lit("run-end")),
732 TsObjectEntry::Shorthand("passed".to_string()),
733 TsObjectEntry::Shorthand("failed".to_string()),
734 TsObjectEntry::prop("unmatched".to_string(), call(ident("unmatched"), vec![])),
737 ]),
738 ];
739 let run_end = ndjson_stmts.pop();
741 if let Some(decl) = &snapshot_report {
742 ndjson_stmts.push(decl.clone());
743 ndjson_stmts.push(emit_call(vec![
744 TsObjectEntry::prop("type".to_string(), str_lit("snapshots")),
745 TsObjectEntry::prop("files".to_string(), ident("__snapshotFiles")),
746 ]));
747 }
748 ndjson_stmts.extend(run_end);
749 let ndjson_branch = block(ndjson_stmts);
750
751 let human_branch = block(vec![
752 console_log(str_lit("Running tests...\n")),
753 TsStmt::for_of(
754 "m",
755 ident("active"),
756 block(vec![
757 console_log(TsExpr::template_lit(
758 vec![String::new(), ":".to_string()],
759 vec![member(ident("m"), "name")],
760 )),
761 TsStmt::decl(
762 TsDecl::Function {
763 name: "report".to_string(),
764 generics: Vec::new(),
765 params: vec![TsParam::new("r".to_string(), Some(TsType::named("Result")))],
766 return_type: None,
767 body: detach.wrap_human(vec![TsStmt::if_else_same_line_stmt(
768 member(ident("r"), "pass"),
769 TsStmt::inline_block(
770 vec![
771 TsStmt::increment(ident("passed"), None),
772 console_log(TsExpr::template_lit(
773 vec![" \\u2713 ".to_string(), String::new()],
774 vec![member(ident("r"), "name")],
775 )),
776 ],
777 None,
778 ),
779 TsStmt::inline_block(
780 vec![
781 TsStmt::increment(ident("failed"), None),
782 console_log(TsExpr::template_lit(
783 vec![" \\u2717 ".to_string(), String::new()],
784 vec![member(ident("r"), "name")],
785 )),
786 if_(
787 member(ident("r"), "error"),
788 console_log(TsExpr::template_lit(
789 vec![" ".to_string(), String::new()],
790 vec![member(member(ident("r"), "error"), "message")],
791 )),
792 ),
793 ],
794 None,
795 ),
796 None,
797 )]),
798 is_async: false,
799 inline: false,
800 },
801 None,
802 ),
803 expr_stmt(await_expr(call(
804 ident("runSelected"),
805 vec![member(ident("m"), "run"), ident("report")],
806 ))),
807 console_log(str_lit("")),
808 ]),
809 None,
810 ),
811 console_log(TsExpr::template_lit(
812 vec![
813 String::new(),
814 " passed, ".to_string(),
815 " failed.".to_string(),
816 ],
817 vec![ident("passed"), ident("failed")],
818 )),
819 expr_stmt(call(ident("reportUnmatched"), vec![])),
820 ]);
821 let human_branch = with_snapshot_report(human_branch, &snapshot_report);
824
825 main_body.push(TsStmt::if_else_same_line_stmt(
826 strict_eq(
827 member(member(ident("process"), "env"), "BYNK_TEST_FORMAT"),
828 str_lit("ndjson"),
829 ),
830 ndjson_branch,
831 human_branch,
832 None,
833 ));
834 main_body.extend(pg.then(pglite_teardown));
835 main_body.push(if_(
837 or_expr(
838 binary(TsBinaryOp::GreaterThan, ident("failed"), num_lit("0")),
839 TsExpr::Binary {
840 op: TsBinaryOp::StrictNotEq,
841 left: Box::new(call(ident("unmatched"), vec![])),
842 right: Box::new(ident("undefined")),
843 },
844 ),
845 expr_stmt(call(member(ident("process"), "exit"), vec![num_lit("1")])),
846 ));
847
848 program.push(TestRuntimeModule::TestFilter.splice());
849 program.push(TsStmt::decl(
850 TsDecl::Function {
851 name: "main".to_string(),
852 generics: Vec::new(),
853 params: vec![],
854 return_type: None,
855 body: main_body,
856 is_async: true,
857 inline: false,
858 },
859 None,
860 ));
861 program.push(expr_stmt(call(ident("main"), vec![])));
862 program
863}
864
865fn pglite_teardown() -> TsStmt {
869 let closer = TsExpr::OptionalCall {
871 callee: Box::new(member(
872 crate::ts_build::paren(crate::ts_build::as_expr(
873 crate::ts_build::as_expr(ident("globalThis"), TsType::named("unknown")),
874 TsType::named("{ __bynkPgliteTeardown?: () => Promise<void> }"),
875 )),
876 "__bynkPgliteTeardown",
877 )),
878 args: Vec::new(),
879 };
880 expr_stmt(await_expr(closer))
881}
882
883fn with_snapshot_report(human_branch: TsStmt, snapshot_report: &Option<TsStmt>) -> TsStmt {
886 match snapshot_report {
887 Some(decl) => {
888 let marked = crate::ts_build::binary(
890 TsBinaryOp::Add,
891 crate::ts_build::raw_lit("\"\\u0001bynk-snapshots \""),
892 method_call(
893 ident("globalThis.JSON"),
894 "stringify",
895 vec![ident("__snapshotFiles")],
896 ),
897 );
898 block(vec![
899 human_branch,
900 decl.clone(),
901 crate::ts_build::if_(
902 strict_eq(
903 member(member(ident("process"), "env"), "BYNK_SNAPSHOT_REPORT"),
904 str_lit("1"),
905 ),
906 TsStmt::inline_block(vec![console_log(marked)], None),
907 ),
908 ])
909 }
910 None => human_branch,
911 }
912}
913
914fn snapshot_files_decl(modules: Vec<TsExpr>) -> TsStmt {
917 use crate::ts_build::{arrow, index, paren};
918 let selected = method_call(
919 paren(TsExpr::AsConst(Box::new(TsExpr::array(modules)))),
920 "filter",
921 vec![arrow(
922 vec![TsParam::array_pattern(vec!["i".to_string()], None)],
923 method_call(
924 ident("active"),
925 "includes",
926 vec![TsExpr::NonNull(Box::new(index(
927 ident("modules"),
928 ident("i"),
929 )))],
930 ),
931 )],
932 );
933 const_(
934 "__snapshotFiles",
935 method_call(
936 selected,
937 "flatMap",
938 vec![arrow(
939 vec![TsParam::array_pattern(
940 vec![String::new(), "t".to_string()],
941 None,
942 )],
943 method_call(ident("t"), "__bynkSnapshotReport", Vec::new()),
944 )],
945 ),
946 )
947}
948
949fn snapshot_report_decl(sorted: &[&RunnableTest]) -> Option<TsStmt> {
951 let modules: Vec<TsExpr> = sorted
952 .iter()
953 .enumerate()
954 .filter(|(_, t)| !t.snapshot_files.is_empty())
955 .map(|(i, _)| {
956 TsExpr::array(vec![
957 crate::ts_build::num_lit(i),
958 ident(format!("test_{i}")),
959 ])
960 })
961 .collect();
962 (!modules.is_empty()).then(|| snapshot_files_decl(modules))
963}
964
965fn detached_or_undefined(when_some: TsExpr) -> TsExpr {
968 crate::ts_build::paren(crate::ts_build::cond_expr(
969 crate::ts_build::binary(
970 bynk_ts::TsBinaryOp::GreaterThan,
971 member(ident("detached"), "length"),
972 crate::ts_build::num_lit(0),
973 ),
974 when_some,
975 ident("undefined"),
976 ))
977}
978
979#[cfg(test)]
980mod tests {
981 use super::*;
982
983 #[test]
990 fn the_run_function_escapes_a_quoted_backslashed_name_exactly_once() {
991 let stmts = build_run_function(&[(r#"say "hi" \ ok"#.to_string(), "test_a".to_string())]);
992 let printed: String = stmts.iter().map(|s| bynk_ts::print_stmt(s, 0)).collect();
993 assert!(
995 printed
996 .contains(r#"export const __bynkCases: readonly string[] = ["say \"hi\" \\ ok"];"#),
997 "{printed}"
998 );
999 assert!(
1000 printed.contains(r#"if (want("say \"hi\" \\ ok")) {"#),
1001 "{printed}"
1002 );
1003 assert!(printed.contains(r#"const r = { name: "say \"hi\" \\ ok", ...(await test_a()), durationMs: __bynkCaseSince(started) };"#), "{printed}");
1004 }
1005
1006 #[test]
1009 fn the_run_function_times_each_case_and_reports_it_as_it_finishes() {
1010 let stmts = build_run_function(&[
1011 ("one".to_string(), "test_one".to_string()),
1012 ("two".to_string(), "test_two".to_string()),
1013 ]);
1014 let printed: String = stmts.iter().map(|s| bynk_ts::print_stmt(s, 0)).collect();
1015 assert!(
1016 printed.contains(r#"export const __bynkCases: readonly string[] = ["one", "two"];"#)
1017 );
1018 assert!(printed.contains(
1019 "export async function run(only?: string, onCase?: (a0: CaseResult) => void)"
1020 ));
1021 let started = printed
1022 .find("const started = __bynkCaseNow();")
1023 .expect("timed");
1024 let ran = printed.find("...(await test_one())").expect("ran");
1025 let pushed = printed.find("results.push(r);").expect("pushed");
1026 let reported = printed.find("if (onCase) onCase(r);").expect("reported");
1027 assert!(
1028 started < ran && ran < pushed && pushed < reported,
1029 "{printed}"
1030 );
1031 assert_eq!(printed.matches("const started = ").count(), 2);
1032 }
1033
1034 #[test]
1038 fn emit_test_main_threads_the_case_and_suite_filter() {
1039 let tests = vec![RunnableTest {
1040 snapshot_files: Vec::new(),
1041 target_name: "commerce.money".to_string(),
1042 module_path: std::path::PathBuf::from("tests/commerce_money.test.ts"),
1043 kind: "unit",
1044 suite_name: "commerce.money".to_string(),
1045 cases: vec![DiscoveredCase {
1046 name: "rounds".to_string(),
1047 location: None,
1048 tier: None,
1049 generative: None,
1050 doc: false,
1051 }],
1052 skipped: Vec::new(),
1053 envs: Vec::new(),
1054 remote: false,
1055 generative: false,
1056 detach_reports: false,
1057 }];
1058 let program = emit_test_main(&tests, ImportExt::Js, false);
1059 let out = bynk_ts::print(&program, "", "", "").text;
1060 assert!(
1061 out.contains("process.env.BYNK_TEST_FILTER"),
1062 "the runner must read the filter from the environment, got:\n{out}"
1063 );
1064 assert_eq!(
1067 out.matches("await runSelected(m.run, report)").count(),
1068 2,
1069 "both dispatch branches must run each suite through the filter, got:\n{out}"
1070 );
1071 assert_eq!(
1072 out.matches("for (const m of active)").count(),
1073 2,
1074 "got:\n{out}"
1075 );
1076 assert!(
1077 out.contains("unmatched: unmatched()"),
1078 "run-end reports the values that selected nothing, got:\n{out}"
1079 );
1080 }
1081
1082 #[test]
1091 fn matches_the_real_fixtures_own_tests_main_ts_byte_for_byte() {
1092 let expected = include_str!(
1093 "../../../bynk-tests/tests/fixtures/positive/109_test_with_opaque_construction/\
1094 expected/tests/main.ts"
1095 );
1096 let tests = vec![RunnableTest {
1097 snapshot_files: Vec::new(),
1098 target_name: "commerce.payment".to_string(),
1099 module_path: std::path::PathBuf::from("commerce_payment.test.js"),
1100 kind: "unit",
1101 suite_name: "commerce.payment".to_string(),
1102 cases: vec![DiscoveredCase {
1103 name: "opaque".to_string(),
1104 location: None,
1105 tier: None,
1106 generative: None,
1107 doc: false,
1108 }],
1109 skipped: Vec::new(),
1110 envs: Vec::new(),
1111 remote: false,
1112 generative: false,
1113 detach_reports: false,
1114 }];
1115 let program = emit_test_main(&tests, ImportExt::Js, false);
1116 let printed = bynk_ts::print(&program, "", "", "");
1117 assert_eq!(printed.text, expected);
1118 }
1119
1120 #[test]
1123 fn the_snapshot_report_prints_its_declaration_and_marked_line() {
1124 let decl = snapshot_files_decl(vec![
1125 TsExpr::array(vec![crate::ts_build::num_lit(0), ident("test_0")]),
1126 TsExpr::array(vec![crate::ts_build::num_lit(2), ident("test_2")]),
1127 ]);
1128 assert_eq!(
1129 bynk_ts::print_stmt(&decl, 0),
1130 "const __snapshotFiles = ([[0, test_0], [2, test_2]] as const).filter(([i]) => active.includes(modules[i]!)).flatMap(([, t]) => t.__bynkSnapshotReport());\n"
1131 );
1132 let human = with_snapshot_report(block(Vec::new()), &Some(decl));
1133 let printed = bynk_ts::print_stmt(&human, 0);
1134 assert!(
1135 printed.contains(
1136 "if (process.env.BYNK_SNAPSHOT_REPORT === \"1\") { globalThis.console.log(\"\\u0001bynk-snapshots \" + globalThis.JSON.stringify(__snapshotFiles)); }"
1137 ),
1138 "{printed}"
1139 );
1140 }
1141}