1use crate::emitter::lower_stmt::{Body, Item};
5use crate::ts_build::ident;
6use bynk_check::checker::TypedCommons;
7use bynk_model::{
8 IrHandlerKind, IrHttpMethod, ProtocolIr, lower_handler_kind_ir, lower_protocol_ir_from_commons,
9};
10use bynk_syntax::ast::{CommonsItem, Param};
11
12pub fn http_handler_method_name_ir(method: IrHttpMethod, path: &str) -> String {
24 http_handler_method_name_from_str(method.as_str(), path)
25}
26
27fn http_handler_method_name_from_str(method: &str, path: &str) -> String {
28 let mut s = format!("http_{method}");
29 for seg in path.split('/').filter(|s| !s.is_empty()) {
30 s.push('_');
31 if let Some(rest) = seg.strip_prefix(':') {
32 s.push_str("Param_");
33 s.push_str(&sanitise_path_segment(rest));
34 } else {
35 s.push_str(&sanitise_path_segment(seg));
36 }
37 }
38 s
39}
40
41pub fn collect_handler_labels(commons: &TypedCommons) -> Option<String> {
49 let mut entries: Vec<(String, String)> = Vec::new();
50 for item in &commons.commons.items {
51 match item {
52 CommonsItem::Service(s) => {
53 let (mut cron_idx, mut queue_idx) = (0usize, 0usize);
54 for h in &s.handlers {
55 let pair = match lower_handler_kind_ir(&h.kind) {
56 IrHandlerKind::Http { method, path } => (
57 http_handler_method_name_ir(method, &path),
58 format!("{} \"{}\"", method.as_str(), path),
59 ),
60 IrHandlerKind::Cron { expr } => {
61 let n = cron_handler_method_name(&s.name.name, cron_idx);
62 cron_idx += 1;
63 (n, format!("cron \"{expr}\""))
64 }
65 IrHandlerKind::Message
66 if matches!(
67 lower_protocol_ir_from_commons(&s.protocol, commons),
68 ProtocolIr::WebSocket { .. }
69 ) =>
70 {
71 ("message".to_string(), "WebSocket message".to_string())
72 }
73 IrHandlerKind::Message => {
74 let n = queue_handler_method_name(&s.name.name, queue_idx);
75 queue_idx += 1;
76 (n, "message".to_string())
77 }
78 IrHandlerKind::Call => {
79 ("call".to_string(), handler_op_label("call", &h.params))
80 }
81 IrHandlerKind::Open => ("open".to_string(), "WebSocket open".to_string()),
82 IrHandlerKind::Close => {
83 ("close".to_string(), "WebSocket close".to_string())
84 }
85 IrHandlerKind::Event => ("event".to_string(), "event".to_string()),
89 IrHandlerKind::Rejected => ("rejected".to_string(), "rejected".to_string()),
90 };
91 entries.push(pair);
92 }
93 }
94 CommonsItem::Agent(a) => {
95 for h in &a.handlers {
96 if let Some(name) = &h.method_name {
97 entries.push((name.name.clone(), handler_op_label(&name.name, &h.params)));
98 }
99 }
100 }
101 CommonsItem::Type(_)
102 | CommonsItem::Fn(_)
103 | CommonsItem::Capability(_)
104 | CommonsItem::Provider(_)
105 | CommonsItem::Actor(_)
106 | CommonsItem::Messages(_)
107 | CommonsItem::Event(_)
108 | CommonsItem::Asset(_)
109 | CommonsItem::Embed(_)
110 | CommonsItem::Const(_) => {}
111 }
112 }
113 if entries.is_empty() {
114 return None;
115 }
116 let mut seen = std::collections::HashSet::new();
120 let mut out = String::from("{");
121 let mut first = true;
122 for (k, v) in &entries {
123 if !seen.insert(k.clone()) {
124 continue;
125 }
126 if !first {
127 out.push(',');
128 }
129 first = false;
130 out.push_str(&bynk_project::json_string(k));
131 out.push(':');
132 out.push_str(&bynk_project::json_string(v));
133 }
134 out.push('}');
135 Some(out)
136}
137
138fn handler_op_label(name: &str, params: &[Param]) -> String {
141 let ps: Vec<String> = params.iter().map(|p| p.name.name.clone()).collect();
142 format!("{}({})", name, ps.join(", "))
143}
144
145pub fn cron_handler_method_name(service: &str, index: usize) -> String {
152 format!("cron_{service}_{index}")
153}
154
155pub fn queue_handler_method_name(service: &str, index: usize) -> String {
161 format!("queue_{service}_{index}")
162}
163
164fn sanitise_path_segment(s: &str) -> String {
165 let mut out = String::with_capacity(s.len());
166 for ch in s.chars() {
167 if ch.is_ascii_alphanumeric() {
168 out.push(ch);
169 } else {
170 out.push('_');
171 }
172 }
173 out
174}
175
176pub(super) fn join_plus(mut parts: Vec<bynk_ts::TsExpr>) -> bynk_ts::TsExpr {
182 let first = parts.remove(0);
183 parts
184 .into_iter()
185 .fold(first, |acc, next| bynk_ts::TsExpr::Binary {
186 op: bynk_ts::TsBinaryOp::Add,
187 left: Box::new(acc),
188 right: Box::new(next),
189 })
190}
191
192pub(super) fn events_decl_item() -> Item {
194 Item::Node(Box::new(bynk_ts::TsStmt::const_stmt(
195 bynk_ts::TsBindingName::Ident("__events".to_string()),
196 Some(bynk_ts::TsType::named_with_args(
197 "globalThis.Array",
198 vec![bynk_ts::TsType::named(
199 crate::emitter::EVENTS_WIRE_EVENT_TS_TYPE,
200 )],
201 )),
202 bynk_ts::TsExpr::array(Vec::new()),
203 None,
204 )))
205}
206
207pub(super) fn iife_const_item(name: &str, awaited: bool, body: Body) -> Item {
212 let closure = bynk_ts::TsExpr::Arrow {
213 params: Vec::new(),
214 is_async: awaited,
215 generics: Vec::new(),
216 return_type: None,
217 body: Box::new(bynk_ts::TsArrowBody::Multiline(body.into_stmts())),
218 };
219 let call = bynk_ts::TsExpr::Call {
220 callee: Box::new(bynk_ts::TsExpr::Paren(Box::new(closure))),
221 args: Vec::new(),
222 };
223 let init = if awaited {
224 bynk_ts::TsExpr::Await(Box::new(call))
225 } else {
226 call
227 };
228 Item::Node(Box::new(bynk_ts::TsStmt::const_stmt(
229 bynk_ts::TsBindingName::Ident(name.to_string()),
230 None,
231 init,
232 None,
233 )))
234}
235
236pub(super) fn result_closure_item(body: Body) -> Item {
238 iife_const_item("__result", true, body)
239}
240
241pub(super) fn return_undefined_unless(test: bynk_ts::TsExpr) -> Item {
243 Item::Node(Box::new(crate::ts_build::if_(
244 crate::ts_build::not_expr(crate::ts_build::paren(test)),
245 crate::ts_build::return_(Some(crate::ts_build::ident("undefined"))),
246 )))
247}
248
249pub(super) fn events_flush_item(inline: bool) -> Item {
252 let dispatch = bynk_ts::TsStmt::expr_stmt(
253 bynk_ts::TsExpr::Await(Box::new(bynk_ts::TsExpr::Call {
254 callee: Box::new(bynk_ts::TsExpr::Member {
255 object: Box::new(ident("deps")),
256 property: "__eventsDispatch".to_string(),
257 }),
258 args: vec![ident("__events")],
259 })),
260 None,
261 );
262 let then = if inline {
263 bynk_ts::TsStmt::inline_block(vec![dispatch], None)
264 } else {
265 bynk_ts::TsStmt::block(vec![dispatch], None)
266 };
267 let cond = bynk_ts::TsExpr::Binary {
268 op: bynk_ts::TsBinaryOp::GreaterThan,
269 left: Box::new(bynk_ts::TsExpr::Member {
270 object: Box::new(ident("__events")),
271 property: "length".to_string(),
272 }),
273 right: Box::new(bynk_ts::TsExpr::Lit(bynk_ts::TsLit::Num("0".to_string()))),
274 };
275 Item::Node(Box::new(bynk_ts::TsStmt::if_stmt(cond, then, None)))
276}
277
278pub(super) fn return_result_item() -> Item {
279 Item::Node(Box::new(bynk_ts::TsStmt::return_stmt(
280 Some(bynk_ts::TsExpr::Ident("__result".to_string())),
281 None,
282 )))
283}
284
285pub(super) fn events_release_body(body: Body) -> Body {
289 let mut wrapped = Body::new();
290 wrapped.push(events_decl_item());
291 wrapped.push(result_closure_item(body));
292 wrapped.push(events_flush_item(false));
293 wrapped.push(return_result_item());
294 wrapped
295}