1use std::path::Path;
35
36use crate::emit_model::{EmitProjectCtx, ImportExt};
37use bynk_check::checker::TypedCommons;
38use bynk_project::UnitKind;
39use bynk_ts::TsStmt;
40
41use super::runtime_files::{is_runtime_export, is_type_only_export};
42
43const ORDER: &[&str] = &[
48 "Ok",
50 "Err",
51 "Some",
52 "None",
53 "Result",
54 "Option",
55 "ValidationError",
56 "DecodeError",
57 "Connection",
58 "__DurableObjectState",
60 "__DurableObjectNamespace",
61 "__StateRegistry",
62 "__makeAgent",
63 "__noteAgentInstance",
64 "__inspectAgent",
65 "__historyBefore",
66 "__historyRecord",
67 "__invariantViolation",
68 "__AgentWire",
69 "__decodeAgentArgs",
70 "__encodeAgentResult",
71 "__decodeAgentKey",
72 "__AGENT_WIRE_PASS",
73 "__dispatchToEventsFanout",
74 "__rehydrationViolation",
75 "__migrationFailed",
76 "__reportUnknownStoredKeys",
77 "__checkStoredLayout",
78 "__readStored",
79 "__commitStored",
80 "__noteClock",
81 "__StoreCache",
83 "__StoreLog",
84 "__StoreMap",
85 "__StoreSet",
86 "__attachLazy",
87 "__bynkThen",
88 "__fillHeld",
89 "__fillLog",
90 "__fillMap",
91 "__fillSet",
92 "__readsLazily",
93 "__wireEntries",
94 "__wireHeld",
95 "__wireHeldOrder",
96 "__wireLog",
97 "__wireMap",
98 "__wirePostings",
99 "__wireSet",
100 "__checkStoredSchemaVersion",
101 "__wakeForMigration",
102 "__resolveConnection",
104 "__connIdOf",
105 "__acceptHibernatableConnection",
106 "__newWebSocketPair",
107 "__webSocketUpgradeResponse",
108 "__WorkersConnection",
109 "HttpResult",
110 "QueueResult",
111 "__JsonValue",
113 "__BoundaryError",
114 "__ServiceBinding",
115 "__callService",
116 "__boundaryError",
117 "__bynkBytesEqual",
119 "__bynkBytesToBase64",
120 "__bynkBytesFromBase64",
121 "__bynkBytesDecodeUtf8",
122 "__bynkBytesConcat",
123 "__bynkBytesCompare",
124 "__bynkBytesToHex",
125 "__bynkBytesFromHex",
126 "__bynkBytesToBase64Url",
127 "__bynkBytesFromBase64Url",
128 "__bynkInstantToIso",
129 "__bynkInstantFromIso",
130 "__bynkPgRow",
131 "__bynkIsIsoDate",
132 "__bynkIsCron",
133 "__bynkCodePointLength",
134 "__bynkYamlParse",
135 "__bynkSettleAll",
136 "__bynkWithin",
137 "__bynkRace",
138 "__bynkDetach",
139 "__fault",
140 "__traceStep",
141 "__traceBinding",
142 "__bynkPercentEncode",
144 "__bynkPercentDecode",
145 "__requestHeaders",
146 "__requestCookies",
147 "__requestCookiesHeader",
148 "__issueSessionCookie",
149 "__expireSessionCookie",
150 "__sessionKeysOf",
151 "__cookieValue",
152 "__signSessionCookie",
153 "__newSessionKey",
154 "__requestQuery",
155 "__queryString",
156 "__formDecode",
157 "__formString",
158 "__cookieString",
159 "__multipartForm",
160 "__bynkEq",
162 "__bynkIntDiv",
163 "__bynkToInt",
164 "__bynkIntDivFloor",
165 "__bynkIntRem",
166 "__bynkIntMod",
167 "__bynkIntPow",
168 "__bynkIntAnd",
169 "__bynkIntOr",
170 "__bynkIntXor",
171 "__bynkIntAndNot",
172 "__bynkIntShl",
173 "__bynkIntShr",
174 "__selectPluralArm",
175 "__formatIcuNumber",
176 "__formatIcuDate",
177];
178
179const WORKER_ORDER: &[&str] = &[
186 "HttpResult",
187 "Ok",
188 "Option",
189 "__AiSearchInstance",
190 "__AnalyticsDataset",
191 "__D1Database",
192 "__Hyperdrive",
193 "__KVNamespace",
194 "__QueueProducer",
195 "__R2Bucket",
196 "__RateLimiter",
197 "__SecretsStoreSecret",
198 "__SendEmail",
199 "__SenderIdentity",
200 "__ServiceBinding",
201 "__JsonValue",
202 "__VectorizeIndex",
203 "__WorkerAiBinding",
204 "__WorkerImagesBinding",
205 "__WorkerVersionMetadata",
206 "__bynkBytesEqual",
207 "__bynkDecimalParseWire",
208 "__bynkDecimalToString",
209 "__handleEmail",
210 "__matchPath",
211 "__mysqlExecute",
212 "__pgExecute",
213 "__serialiseAgentClass",
214 "__serialiseAgentKey",
215 "__dispatchToEventsFanout",
216 "__sessionCookieOf",
217 "__verifyBearerJwtHs256",
218 "__verifyOidcJwt",
219 "__verifySignatureHmacSha256",
220 "__verifySignedCookie",
221 "Err",
222 "Result",
223 "__AnalyticsSqlBinding",
224 "__BoundaryError",
225 "__InboundMessage",
226 "__bynkBytesToBase64",
227 "__csrfAllowed",
228 "__httpResultToResponse",
229 "__tokenClaims",
230 "__boundaryError",
231 "__bynkBytesFromBase64",
232 "__oidcTrust",
233 "__withPlainJson",
234 "__headResponse",
235 "__bynkBytesDecodeUtf8",
236 "__notModifiedIfMatch",
237 "__verifyCall",
238 "__applyCache",
239 "__CorsPolicy",
240 "__applyCors",
241 "__applyEdgeCache",
242 "__corsPreflightResponse",
243 "__faultResponse",
244 "__readBodyCapped",
245 "__deserialiseEventEnvelope",
246 "__noStore",
247 "__edgeCacheGuard",
248 "__varyAcceptLanguage",
249 "__SecurityPolicy",
250 "__applySecurityHeaders",
251 "__requestBodyStream",
252 "__untilBodyTooLarge",
253 "__mediaTypeMatches",
254 "__requestHeaders",
255 "__queryObject",
256 "__cookieObject",
257 "__multipartMediaTypeMatches",
258 "__multipartObject",
259 "__formMediaTypeMatches",
260 "__formObject",
261 "__requestCookies",
262 "__cfObject",
263 "__renderRejection",
264 "__requestQuery",
265];
266
267const TEST_ORDER: &[&str] = &[
274 "HttpResult",
275 "Ok",
276 "Err",
277 "Some",
278 "None",
279 "Result",
280 "Option",
281 "TestConnection",
282 "ValidationError",
283 "DecodeError",
284 "__BynkKeyMap",
285 "__BynkKeySet",
286 "__DurableObjectNamespace",
287 "__DurableObjectState",
288 "__bynkBytesEqual",
289 "__bynkBytesToBase64",
290 "__bynkBytesFromBase64",
291 "__bynkBytesDecodeUtf8",
292 "__bynkBytesConcat",
293 "__bynkBytesCompare",
294 "__bynkBytesToHex",
295 "__bynkBytesFromHex",
296 "__bynkBytesToBase64Url",
297 "__bynkBytesFromBase64Url",
298 "__bynkCmpBytes",
299 "__bynkCmpDecimal",
300 "__bynkCmpFloat",
301 "__bynkCmpInt",
302 "__bynkCmpList",
303 "__bynkCmpOption",
304 "__bynkCmpRecord",
305 "__bynkCmpString",
306 "__bynkCmpSum",
307 "__bynkDecimalAbs",
308 "__bynkDecimalAdd",
309 "__bynkDecimalDiv",
310 "__bynkDecimalEqual",
311 "__bynkDecimalFromInt",
312 "__bynkDecimalMin",
313 "__bynkDecimalMul",
314 "__bynkDecimalNeg",
315 "__bynkDecimalParse",
316 "__bynkDecimalParseWire",
317 "__bynkDecimalRound",
318 "__bynkDecimalShow",
319 "__bynkDecimalSub",
320 "__bynkDecimalToFloat",
321 "__bynkDecimalToInt",
322 "__bynkDecimalToString",
323 "__bynkDistinctBy",
324 "__bynkEq",
325 "__bynkGroupBy",
326 "__bynkInstantToIso",
327 "__bynkInstantFromIso",
328 "__bynkJoinOn",
329 "__bynkMapInsert",
330 "__bynkSetInsert",
331 "__bynkSetOf",
332 "__bynkSetRemove",
333 "__bynkSettleAll",
334 "__callService",
335 "__JsonValue",
336 "__BoundaryError",
337 "__ServiceBinding",
338 "__makeIntegrationAi",
339 "__makeIntegrationAnalytics",
340 "__makeIntegrationD1",
341 "__makeIntegrationEmail",
342 "__makeIntegrationImages",
343 "__makeIntegrationKv",
344 "__makeIntegrationDoNamespace",
345 "__makeIntegrationQueue",
346 "__makeIntegrationR2",
347 "__makeIntegrationRateLimit",
348 "__makeIntegrationSecretsStoreSecret",
349 "__makeIntegrationVectorize",
350 "__makeIntegrationVersionMetadata",
351 "__makeTestState",
352 "__responseToHttpResult",
353 "__responseToHttpOutcome",
354 "__responseToUnauthOutcome",
355 "__requestHeaders",
356 "__requestCookies",
357 "__requestCookiesHeader",
358 "__requestQuery",
359 "__queryString",
360 "__multipartForm",
361 "__cookieString",
362 "__requestHeaderPairs",
363 "__requestQuerySearch",
364 "__signSessionCookie",
365 "__newSessionKey",
366];
367
368pub(crate) fn derived_runtime_names(stmts: &[TsStmt]) -> Vec<String> {
375 names_in_order(stmts, |n| ORDER.iter().position(|o| *o == n))
376}
377
378pub(crate) fn derived_test_runtime_names(stmts: &[TsStmt]) -> Vec<String> {
380 names_in_order(stmts, |n| TEST_ORDER.iter().position(|o| *o == n))
381}
382
383pub(crate) fn derived_worker_runtime_names(stmts: &[TsStmt]) -> Vec<String> {
385 names_in_order(stmts, |n| {
386 WORKER_ORDER.iter().position(|o| *o == n).or_else(|| {
387 ORDER
388 .iter()
389 .position(|o| *o == n)
390 .map(|i| WORKER_ORDER.len() + i)
391 })
392 })
393}
394
395fn names_in_order(stmts: &[TsStmt], position: impl Fn(&str) -> Option<usize>) -> Vec<String> {
396 let mut used: Vec<String> = bynk_ts::unbound_names_in(stmts, is_runtime_export)
397 .into_iter()
398 .filter(|n| is_runtime_export(n))
399 .collect();
400 let rank = |n: &str| position(n).unwrap_or(usize::MAX);
401 used.sort_by(|a, b| rank(a).cmp(&rank(b)).then_with(|| a.cmp(b)));
402 used.into_iter()
403 .map(|n| {
404 if is_type_only_export(&n) {
405 format!("type {n}")
406 } else {
407 n
408 }
409 })
410 .collect()
411}
412
413pub fn runtime_import_for(from_source: &Path, ext: ImportExt) -> String {
417 let depth = from_source
418 .parent()
419 .map(|p| {
420 p.components()
421 .filter(|c| matches!(c, std::path::Component::Normal(_)))
422 .count()
423 })
424 .unwrap_or(0);
425 let ext = ext.as_str();
426 if depth == 0 {
427 format!("./runtime.{ext}")
428 } else {
429 let prefix: String = "../".repeat(depth);
430 format!("{prefix}runtime.{ext}")
431 }
432}
433
434pub(super) fn write_header(
440 commons: &TypedCommons,
441 ctx: &EmitProjectCtx,
442 body: &[bynk_ts::TsStmt],
443) -> Vec<bynk_ts::TsStmt> {
444 let kind = match ctx.unit_kind {
448 UnitKind::Commons => "commons",
449 UnitKind::Context => "context",
450 UnitKind::Test => "test",
451 UnitKind::Integration => "integration test",
452 UnitKind::Adapter => "adapter",
453 };
454 let mut stmts = vec![
460 bynk_ts::TsStmt::comment("Generated by bynk — do not edit by hand.", None),
461 bynk_ts::TsStmt::comment(format!("{kind} {}", commons.commons.name.joined()), None),
462 ];
463 if !commons.commons.items.is_empty() {
464 let names = derived_runtime_names(body);
465 stmts.extend(super::runtime_files::runtime_import_stmts(
466 false,
467 &names,
468 &runtime_import_for(&ctx.source_path, ctx.import_ext),
469 ));
470 }
471 stmts
472}
473
474pub(super) fn header_single(
479 commons: &TypedCommons,
480 body: &[bynk_ts::TsStmt],
481) -> Vec<bynk_ts::TsStmt> {
482 let mut stmts = vec![
485 bynk_ts::TsStmt::comment("Generated by bynk — do not edit by hand.", None),
486 bynk_ts::TsStmt::comment(
487 format!(
488 "commons {}",
489 bynk_project::display_unit_name(&commons.commons.name.joined())
490 ),
491 None,
492 ),
493 ];
494 if !commons.commons.items.is_empty() {
495 let names = derived_runtime_names(body);
496 let imports = super::runtime_files::runtime_import_stmts(false, &names, "./runtime.js");
497 if imports.is_empty() {
500 let mut blank = bynk_ts::TsStmt::blank(None);
501 blank.no_blank_before = true;
502 stmts.push(blank);
503 }
504 stmts.extend(imports);
505 }
506 stmts
507}
508
509#[cfg(test)]
510mod tests {
511 use super::*;
512 use crate::emitter::runtime_files::is_runtime_export;
513 use bynk_ts::{TsDecl, TsExpr, TsParam, TsType};
514
515 fn program_using(body: Vec<TsStmt>) -> Vec<TsStmt> {
516 body
517 }
518
519 fn call(name: &str) -> TsStmt {
520 TsStmt::expr_stmt(
521 TsExpr::Call {
522 callee: Box::new(TsExpr::Ident(name.to_string())),
523 args: vec![],
524 },
525 None,
526 )
527 }
528
529 fn function_over(ty: TsType) -> TsStmt {
530 TsStmt::decl(
531 TsDecl::Function {
532 name: "f".to_string(),
533 generics: vec![],
534 params: vec![TsParam::new("x".to_string(), Some(ty))],
535 return_type: None,
536 body: vec![],
537 is_async: false,
538 inline: false,
539 },
540 None,
541 )
542 }
543
544 #[test]
545 fn the_order_names_runtime_exports_once_each() {
546 let mut seen = std::collections::BTreeSet::new();
547 for n in ORDER {
548 assert!(is_runtime_export(n), "{n} is not a runtime export");
549 assert!(seen.insert(*n), "{n} is listed twice");
550 }
551 }
552
553 #[test]
554 fn the_worker_order_names_runtime_exports_once_each() {
555 let mut seen = std::collections::BTreeSet::new();
556 for n in WORKER_ORDER {
557 assert!(is_runtime_export(n), "{n} is not a runtime export");
558 assert!(seen.insert(*n), "{n} is listed twice");
559 }
560 }
561
562 #[test]
563 fn a_worker_header_ranks_by_the_worker_order() {
564 let stmts = program_using(vec![
565 call("__JsonValue"),
566 call("__ServiceBinding"),
567 call("Ok"),
568 ]);
569 assert_eq!(
570 derived_worker_runtime_names(&stmts),
571 ["Ok", "type __ServiceBinding", "type __JsonValue"]
572 );
573 assert_eq!(
574 derived_runtime_names(&stmts),
575 ["Ok", "type __JsonValue", "type __ServiceBinding"]
576 );
577 }
578
579 #[test]
580 fn a_module_that_uses_nothing_imports_nothing() {
581 assert!(derived_runtime_names(&program_using(vec![])).is_empty());
582 let stmts = program_using(vec![call("helper"), function_over(TsType::named("Order"))]);
584 assert!(derived_runtime_names(&stmts).is_empty());
585 }
586
587 #[test]
591 fn a_global_is_not_imported_from_the_runtime() {
592 let stmts = program_using(vec![
593 call("Response"),
594 function_over(TsType::named("Promise<Request>")),
595 ]);
596 assert!(derived_runtime_names(&stmts).is_empty());
597 }
598
599 #[test]
600 fn a_used_name_is_imported_and_a_type_gets_its_prefix() {
601 let stmts = program_using(vec![
602 call("Some"),
603 function_over(TsType::named("Option<number>")),
604 function_over(TsType::named("HttpResult<string>")),
605 ]);
606 assert_eq!(
607 derived_runtime_names(&stmts),
608 ["Some", "type Option", "HttpResult"]
609 );
610 }
611
612 #[test]
613 fn names_keep_their_historical_order_and_unknown_ones_follow() {
614 let stmts = program_using(vec![
615 call("__bynkCmpInt"),
616 call("__bynkEq"),
617 call("Err"),
618 call("__bynkCmpFloat"),
619 call("Ok"),
620 ]);
621 assert_eq!(
622 derived_runtime_names(&stmts),
623 ["Ok", "Err", "__bynkEq", "__bynkCmpFloat", "__bynkCmpInt"]
624 );
625 }
626
627 #[test]
628 fn a_name_the_module_binds_is_not_imported() {
629 let stmts = program_using(vec![
630 TsStmt::decl(
631 TsDecl::Import {
632 type_only: false,
633 names: vec!["Some".to_string()],
634 from: "./elsewhere.js".to_string(),
635 },
636 None,
637 ),
638 call("Some"),
639 call("None"),
640 ]);
641 assert_eq!(derived_runtime_names(&stmts), ["None"]);
642 }
643
644 #[test]
645 fn runtime_import_depth_resolves_correctly() {
646 assert_eq!(
647 runtime_import_for(Path::new("compose.ts"), ImportExt::Js),
648 "./runtime.js"
649 );
650 assert_eq!(
651 runtime_import_for(Path::new("commerce/payment.ts"), ImportExt::Js),
652 "../runtime.js"
653 );
654 assert_eq!(
655 runtime_import_for(Path::new("commerce/orders/types.ts"), ImportExt::Js),
656 "../../runtime.js"
657 );
658 assert_eq!(
659 runtime_import_for(Path::new("tests/commerce_payment.test.ts"), ImportExt::Js),
660 "../runtime.js"
661 );
662 }
663}
664
665#[cfg(test)]
673mod conditional_runtime_import_tests {
674 use crate::testkit::emit_source;
675
676 fn runtime_import_line(ts: &str) -> String {
679 ts.lines()
680 .filter(|l| l.starts_with("import ") && l.contains("__bynk_runtime/"))
681 .collect::<Vec<_>>()
682 .join("\n")
683 }
684
685 #[test]
686 fn bytes_helpers_are_imported_when_a_bytes_value_is_built() {
687 let ts = emit_source(
688 "commons b\n\nfn decode(s: String) -> Option[Bytes] {\n Bytes.fromBase64(s)\n}\n",
689 );
690 assert!(
691 runtime_import_line(&ts).contains("__bynkBytesFromBase64"),
692 "{ts}"
693 );
694 }
695
696 #[test]
697 fn bytes_helpers_are_imported_for_content_equality() {
698 let ts = emit_source("commons b\n\nfn same(a: Bytes, b: Bytes) -> Bool {\n a == b\n}\n");
699 assert!(
700 runtime_import_line(&ts).contains("__bynkBytesEqual"),
701 "{ts}"
702 );
703 }
704
705 #[test]
709 fn bytes_ops_helpers_are_imported_only_when_an_operation_is_called() {
710 let base = emit_source("commons b\n\nfn same(a: Bytes, b: Bytes) -> Bool {\n a == b\n}\n");
711 assert!(
712 !runtime_import_line(&base).contains("__bynkBytesConcat"),
713 "{base}"
714 );
715 let ops = emit_source("commons b\n\nfn hex(b: Bytes) -> String {\n b.toHex()\n}\n");
716 let line = runtime_import_line(&ops);
717 assert!(line.contains("__bynkBytesToHex"), "{ops}");
718 assert!(!line.contains("__bynkBytesEqual"), "{ops}");
719 }
720
721 #[test]
724 fn instant_iso_helpers_are_imported_only_when_called() {
725 let base = emit_source("commons t\n\nfn ms(i: Instant) -> Int {\n i.toEpochMillis()\n}\n");
726 assert!(
727 !runtime_import_line(&base).contains("__bynkInstant"),
728 "{base}"
729 );
730 let ts = emit_source(
731 "commons t\n\nfn iso(i: Instant) -> String {\n i.toIso()\n}\n\nfn read(s: String) -> Option[Instant] {\n Instant.fromIso(s)\n}\n",
732 );
733 let line = runtime_import_line(&ts);
734 assert!(line.contains("__bynkInstantToIso"), "{ts}");
735 assert!(line.contains("__bynkInstantFromIso"), "{ts}");
736 assert!(ts.contains("__bynkInstantToIso(i)"), "{ts}");
737 assert!(ts.contains("__bynkInstantFromIso(s)"), "{ts}");
738 }
739
740 #[test]
742 fn percent_helpers_are_imported_only_when_called() {
743 let base = emit_source("commons u\n\nfn n(s: String) -> Int {\n s.length()\n}\n");
744 assert!(
745 !runtime_import_line(&base).contains("__bynkPercent"),
746 "{base}"
747 );
748 let ts = emit_source(
749 "commons u\n\nfn e(s: String) -> String {\n s.percentEncode()\n}\n\nfn d(s: String) -> Option[String] {\n s.percentDecode()\n}\n",
750 );
751 let line = runtime_import_line(&ts);
752 assert!(
753 line.contains("__bynkPercentEncode") && line.contains("__bynkPercentDecode"),
754 "{ts}"
755 );
756 assert!(
757 ts.contains("__bynkPercentEncode(s)") && ts.contains("__bynkPercentDecode(s)"),
758 "{ts}"
759 );
760 }
761
762 #[test]
764 fn bytes_slice_needs_no_helper() {
765 let ts = emit_source("commons b\n\nfn tag(b: Bytes) -> Bytes {\n b.slice(0, 4)\n}\n");
766 assert!(!runtime_import_line(&ts).contains("__bynkBytes"), "{ts}");
767 }
768
769 #[test]
770 fn bytes_helpers_are_absent_from_a_module_that_never_uses_bytes() {
771 let ts = emit_source("commons b\n\nfn double(n: Int) -> Int {\n n * 2\n}\n");
772 assert!(!runtime_import_line(&ts).contains("__bynkBytes"), "{ts}");
773 }
774
775 #[test]
781 fn escapes_a_marker_in_a_string_literal() {
782 let ts = emit_source("commons b\n\nfn label() -> String {\n \"__bynkBytesEqual\"\n}\n");
783 assert!(
784 ts.contains("\"__bynkBytesEqual\""),
785 "the literal should survive into the body: {ts}"
786 );
787 assert!(
788 !runtime_import_line(&ts).contains("__bynkBytes"),
789 "a marker inside a string literal is not a helper reference: {ts}"
790 );
791 }
792}