1use boa_engine::{js_string, Context, JsError, JsNativeError, JsResult, JsValue, NativeFunction, Source};
23use drawland_graph::{At, Arg, Grammar, Graph};
24use serde_json::Value;
25use std::cell::RefCell;
26use std::fmt;
27use std::rc::Rc;
28
29pub const LIBRARY: &str = include_str!("library.js");
32
33pub type Styles = Rc<dyn Fn(&str) -> Result<String, String>>;
37
38#[derive(Clone, Default)]
43pub struct Host {
44 pub place: Option<(f64, f64)>,
45 pub styles: Option<Styles>,
46 pub typescript: bool,
49}
50
51#[cfg(feature = "typescript")]
54pub fn strip_types(source: &str) -> Result<String, ScriptError> {
55 drawland_ts::strip_types(source).map_err(|e| ScriptError {
56 message: e.message,
57 at: e.at.map(|(l, c)| At(l, c)),
58 address: None,
59 })
60}
61
62#[cfg(not(feature = "typescript"))]
64pub fn strip_types(_: &str) -> Result<String, ScriptError> {
65 Err(ScriptError { message: "TypeScript: this build runs JavaScript only; strip the types first".into(), at: None, address: None })
66}
67
68pub const SCRIPT_PATH: &str = "profile.js";
71const LIBRARY_PATH: &str = "drawland:library";
72
73pub const LOOP_LIMIT: u64 = 1_000_000;
76pub const RECURSION_LIMIT: usize = 256;
77
78#[derive(Debug, Clone, PartialEq)]
79pub struct ScriptError {
80 pub message: String,
81 pub at: Option<At>,
82 pub address: Option<String>,
85}
86
87impl fmt::Display for ScriptError {
88 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89 match self.at {
90 Some(at) => write!(f, "{at}: {}", self.message),
91 None => f.write_str(&self.message),
92 }
93 }
94}
95
96impl std::error::Error for ScriptError {}
97
98impl From<drawland_graph::Error> for ScriptError {
99 fn from(e: drawland_graph::Error) -> Self {
100 ScriptError { message: e.message, at: e.at, address: e.address }
101 }
102}
103
104pub fn evaluate(source: &str) -> Result<Grammar, ScriptError> {
107 evaluate_in(source, &Host::default())
108}
109
110pub fn evaluate_in(source: &str, host: &Host) -> Result<Grammar, ScriptError> {
112 finish(run_into(Graph::new(host.place), source, host))
113}
114
115pub fn evaluate_draft(source: &str, host: &Host) -> Result<(Grammar, bool), ScriptError> {
120 let (graph, result) = run_into(Graph::draft(host.place), source, host);
121 let drafted = graph.drafted();
122 finish((graph, result)).map(|g| (g, drafted))
123}
124
125fn finish((graph, result): (Graph, Result<(), ScriptError>)) -> Result<Grammar, ScriptError> {
126 let address = graph.wanted_address().map(str::to_string);
127 result.map_err(|e| ScriptError { address: address.clone().or(e.address.clone()), ..e })?;
128 graph.finish().map_err(ScriptError::from)
129}
130
131pub fn run_into(graph: Graph, source: &str, host: &Host) -> (Graph, Result<(), ScriptError>) {
135 let stripped;
136 let source = if host.typescript {
137 match strip_types(source) {
138 Ok(js) => {
139 stripped = js;
140 stripped.as_str()
141 }
142 Err(e) => return (graph, Err(e)),
143 }
144 } else {
145 source
146 };
147 let outer_graph = GRAPH.with(|g| g.borrow_mut().replace(graph));
148 let outer_styles = STYLES.with(|s| std::mem::replace(&mut *s.borrow_mut(), host.styles.clone()));
149 let result = run(source);
150 let graph = GRAPH.with(|g| std::mem::replace(&mut *g.borrow_mut(), outer_graph)).expect("the graph run_into lent");
151 STYLES.with(|s| *s.borrow_mut() = outer_styles);
152 (graph, result)
153}
154
155fn run(source: &str) -> Result<(), ScriptError> {
156 let mut ctx = Context::default();
157 let limits = ctx.runtime_limits_mut();
158 limits.set_loop_iteration_limit(LOOP_LIMIT);
159 limits.set_recursion_limit(RECURSION_LIMIT);
160 install(&mut ctx).map_err(|e| ScriptError { message: format!("library: {e}"), at: None, address: None })?;
161 let script = Source::from_bytes(source).with_path(std::path::Path::new(SCRIPT_PATH));
162 ctx.eval(script).map(|_| ()).map_err(|e| script_error(e, source, &mut ctx))
163}
164
165type Native = fn(&JsValue, &[JsValue], &mut Context) -> JsResult<JsValue>;
166
167fn install(ctx: &mut Context) -> JsResult<()> {
169 ctx.eval(Source::from_bytes(
170 "delete globalThis.Date; delete Math.random; delete globalThis.WeakRef; delete globalThis.FinalizationRegistry;",
171 ))?;
172 let natives: [(&str, usize, Native); 15] = [
173 ("call", 2, native_call),
174 ("prop", 1, native_prop),
175 ("get", 2, native_get),
176 ("functions", 0, native_functions),
177 ("properties", 0, native_properties),
178 ("describe", 1, native_describe),
179 ("outputBegin", 1, native_output_begin),
180 ("outputWarps", 1, native_output_warps),
181 ("remapGrid", 2, native_remap_grid),
182 ("remapMesh", 5, native_remap_mesh),
183 ("viewBegin", 1, native_view_begin),
184 ("viewEnd", 1, native_view_end),
185 ("viewStyle", 2, native_view_style),
186 ("burin", 1, native_burin),
187 ("fail", 1, native_fail),
188 ];
189 let dl = boa_engine::object::ObjectInitializer::new(ctx).build();
190 for (name, arity, f) in natives {
191 let function = boa_engine::object::FunctionObjectBuilder::new(ctx.realm(), NativeFunction::from_fn_ptr(f))
192 .name(js_string!(name))
193 .length(arity)
194 .build();
195 dl.set(js_string!(name), function, false, ctx)?;
196 }
197 let make = ctx.eval(Source::from_bytes(LIBRARY).with_path(std::path::Path::new(LIBRARY_PATH)))?;
198 let install = ctx.eval(Source::from_bytes(
200 "(function (make, dl) { const lib = make(dl); for (const [name, value] of Object.entries(lib)) Object.defineProperty(globalThis, name, { value, enumerable: false, writable: false, configurable: false }); })",
201 ).with_path(std::path::Path::new(LIBRARY_PATH)))?;
202 let install = install.as_callable().ok_or_else(|| JsNativeError::typ().with_message("library: install is not a function"))?.clone();
203 install.call(&JsValue::undefined(), &[make, dl.into()], ctx)?;
204 Ok(())
205}
206
207thread_local! {
208 static GRAPH: RefCell<Option<Graph>> = const { RefCell::new(None) };
210 static STYLES: RefCell<Option<Styles>> = const { RefCell::new(None) };
212 static FAILURE: RefCell<Option<(String, Option<At>)>> = const { RefCell::new(None) };
215}
216
217fn with<T>(at: Option<At>, f: impl FnOnce(&mut Graph) -> T) -> T {
219 GRAPH.with(|g| {
220 let mut g = g.borrow_mut();
221 let g = g.as_mut().expect("natives run inside a script");
222 g.at = at;
223 f(g)
224 })
225}
226
227fn user_at(ctx: &mut Context) -> Option<At> {
235 let error = ctx.intrinsics().constructors().error().constructor();
236 let error = error.construct(&[], None, ctx).ok()?;
237 let stack = error.get(js_string!("stack"), ctx).ok()?.to_string(ctx).ok()?.to_std_string_escaped();
238 let marker = format!("({SCRIPT_PATH}:");
239 stack.lines().find_map(|line| {
240 let spot = &line[line.find(&marker)? + marker.len()..];
241 let (l, c) = spot.trim_end_matches(')').split_once(':')?;
242 Some(At(l.parse().ok()?, c.parse().ok()?))
243 })
244}
245
246fn throw(message: String, at: Option<At>) -> JsError {
248 FAILURE.with(|f| *f.borrow_mut() = Some((message.clone(), at)));
249 JsNativeError::typ().with_message(message).into()
250}
251
252fn fail(ctx: &mut Context, message: impl Into<String>) -> JsError {
253 let at = user_at(ctx);
254 throw(message.into(), at)
255}
256
257fn graph_error(e: drawland_graph::Error, ctx: &mut Context) -> JsError {
259 let at = e.at.or_else(|| user_at(ctx));
260 throw(e.message, at)
261}
262
263fn arg(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<Arg> {
265 let value = args.get(i).cloned().unwrap_or_default();
266 Ok(Arg::decode(&value.to_json(ctx)?.unwrap_or(Value::Null)))
267}
268
269fn arg_list(v: Arg) -> Vec<Arg> {
271 let mut list = match v {
272 Arg::List(l) => l,
273 other => vec![other],
274 };
275 while list.last() == Some(&Arg::Null) {
276 list.pop();
277 }
278 list
279}
280
281fn string_arg(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<String> {
282 Ok(args.get(i).cloned().unwrap_or_default().to_string(ctx)?.to_std_string_escaped())
283}
284
285fn give(v: &Arg, ctx: &mut Context) -> JsResult<JsValue> {
286 JsValue::from_json(&v.encode(), ctx)
287}
288
289fn names(list: &[&str], ctx: &mut Context) -> JsResult<JsValue> {
290 JsValue::from_json(&Value::from(list.to_vec()), ctx)
291}
292
293fn native_call(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
295 let name = string_arg(args, 0, ctx)?;
296 let list = arg_list(arg(args, 1, ctx)?);
297 let at = user_at(ctx);
298 match with(at, |g| g.call(&name, &list)) {
299 Ok(v) => give(&v, ctx),
300 Err(e) => Err(graph_error(e, ctx)),
301 }
302}
303
304fn native_prop(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
305 let name = string_arg(args, 0, ctx)?;
306 let at = user_at(ctx);
307 match with(at, |g| g.get_property(&name)) {
308 Ok(v) => give(&v, ctx),
309 Err(e) => Err(graph_error(e, ctx)),
310 }
311}
312
313fn native_get(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
314 let of = arg(args, 0, ctx)?;
315 let part = string_arg(args, 1, ctx)?;
316 let at = user_at(ctx);
317 match with(at, |g| g.get(&of, &part)) {
318 Ok(v) => give(&v, ctx),
319 Err(e) => Err(graph_error(e, ctx)),
320 }
321}
322
323fn native_functions(_: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
324 names(drawland_graph::FUNCTIONS, ctx)
325}
326
327fn native_properties(_: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
328 names(drawland_graph::PROPERTIES, ctx)
329}
330
331fn native_describe(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
332 let v = match args.first() {
333 None => None,
334 Some(v) if v.is_undefined() => None,
335 Some(_) => Some(arg(args, 0, ctx)?),
336 };
337 Ok(JsValue::from(js_string!(drawland_graph::describe(v.as_ref()))))
338}
339
340fn native_output_begin(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
342 let spec = arg(args, 0, ctx)?;
343 let at = user_at(ctx);
344 let result = with(at, |g| match &spec {
345 Arg::Map(o) => g.output_begin(o),
346 other => g.call("output", &[other.clone()]).map(|_| false),
347 });
348 match result {
349 Ok(sample) => Ok(JsValue::from(sample)),
350 Err(e) => Err(graph_error(e, ctx)),
351 }
352}
353
354fn native_output_warps(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
355 let done = arg_list(arg(args, 0, ctx)?);
356 let at = user_at(ctx);
357 match with(at, |g| g.output_warps(&done)) {
358 Ok(()) => Ok(JsValue::undefined()),
359 Err(e) => Err(graph_error(e, ctx)),
360 }
361}
362
363fn native_remap_grid(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
365 let warp = arg(args, 0, ctx)?;
366 let n = args.get(1).cloned().unwrap_or_default().to_number(ctx)? as usize;
367 let at = user_at(ctx);
368 let warp = warp.as_map().cloned().unwrap_or_default();
369 match with(at, |g| g.remap_grid(&warp, n)) {
370 Ok((columns, rows, points)) => JsValue::from_json(&serde_json::json!({ "columns": columns, "rows": rows, "points": points }), ctx),
371 Err(e) => Err(graph_error(e, ctx)),
372 }
373}
374
375fn native_remap_mesh(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
377 let number = |i: usize, ctx: &mut Context| -> JsResult<usize> { Ok(args.get(i).cloned().unwrap_or_default().to_number(ctx)? as usize) };
378 let (n, columns, rows) = (number(0, ctx)?, number(1, ctx)?, number(2, ctx)?);
379 let points: Vec<[f64; 2]> = serde_json::from_value(args.get(3).cloned().unwrap_or_default().to_json(ctx)?.unwrap_or(Value::Null)).unwrap_or_default();
380 let went = match arg(args, 4, ctx)? {
381 Arg::List(l) => l,
382 _ => vec![],
383 };
384 let at = user_at(ctx);
385 match with(at, |g| g.remap_mesh(n, columns, rows, &points, &went)) {
386 Ok(v) => give(&v, ctx),
387 Err(e) => Err(graph_error(e, ctx)),
388 }
389}
390
391fn native_view_begin(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
392 let spec = arg(args, 0, ctx)?;
393 let at = user_at(ctx);
394 match with(at, |g| g.view_begin(&spec)) {
395 Ok(()) => Ok(JsValue::undefined()),
396 Err(e) => Err(graph_error(e, ctx)),
397 }
398}
399
400fn native_view_end(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
401 let ok = args.first().is_some_and(JsValue::to_boolean);
402 let at = user_at(ctx);
403 match with(at, |g| g.view_end(ok)) {
404 Ok(v) => give(&v, ctx),
405 Err(e) => Err(graph_error(e, ctx)),
406 }
407}
408
409fn native_view_style(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
412 let spec = arg(args, 0, ctx)?;
413 let name = string_arg(args, 1, ctx)?;
414 let at = user_at(ctx);
415 let source = match STYLES.with(|s| s.borrow().clone()) {
416 Some(styles) => styles(&name),
417 None => Err("this host lends no styles by name; pass a function that draws".to_string()),
418 };
419 let source = source.map_err(|e| fail(ctx, format!("no style {name:?}: {e}")))?;
420 if let Err(e) = with(at, |g| g.view_begin(&spec)) {
421 return Err(graph_error(e, ctx));
422 }
423 let id = with(at, |g| g.view_id().unwrap_or_default().to_string());
424 let result = run(&source);
425 if let Err(e) = result {
426 let _ = with(at, |g| g.view_end(false));
427 return Err(throw(format!("view {id} ({name}): {e}"), at));
428 }
429 match with(at, |g| g.view_end(true)) {
430 Ok(v) => give(&v, ctx),
431 Err(e) => Err(graph_error(e, ctx)),
432 }
433}
434
435fn native_burin(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
441 let callback = args.first().cloned().unwrap_or_default();
442 match burin_map_script::run_builder(ctx, &callback, SCRIPT_PATH) {
443 Ok(atlas) => Ok(JsValue::from(js_string!(atlas.to_string()))),
444 Err(e) => Err(throw(e.message, e.at.map(|a| At(a.0, a.1)))),
445 }
446}
447
448fn native_fail(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
449 let message = string_arg(args, 0, ctx)?;
450 Err(fail(ctx, message))
451}
452
453const RENAMED: [(&str, &str); 3] = [
460 ("engine.frame(", "engine.frame() is now page.frame (a property: no parentheses)"),
461 ("engine.scale(", "engine.scale() is now world.scale (a property: no parentheses)"),
462 ("engine.paper(", "engine.paper() is now page: page.width and page.height"),
463];
464
465fn script_error(err: JsError, source: &str, ctx: &mut Context) -> ScriptError {
466 let mut e = raw_script_error(err, source, ctx);
467 if e.message.contains("not a callable function") {
468 let line = e.at.and_then(|At(l, _)| source.lines().nth(l.saturating_sub(1) as usize)).unwrap_or_default();
469 if let Some((_, hint)) = RENAMED.iter().find(|(old, _)| line.contains(old)) {
470 e.message = format!("{}: {hint}", e.message);
471 }
472 }
473 e
474}
475
476fn raw_script_error(err: JsError, source: &str, ctx: &mut Context) -> ScriptError {
477 let native = err.try_native(ctx).ok();
478 let message = native.as_ref().map(|n| n.message().to_string());
479 if let (Some(message), Some((failed, at))) = (&message, FAILURE.with(|f| f.borrow_mut().take())) {
480 if *message == failed {
481 return ScriptError { message: failed, at, address: None };
482 }
483 }
484 let text = err.to_string();
485 let first = text.lines().next().unwrap_or_default();
486 let kind = native.as_ref().map(|n| format!("{}", n.kind())).unwrap_or_default();
487 let message = match (&message, kind.is_empty()) {
488 (Some(m), false) => format!("{kind}: {m}"),
489 _ => first.split(" (").next().unwrap_or(first).to_string(),
490 };
491 if let Some(name) = message.strip_prefix("ReferenceError: ").and_then(|m| m.strip_suffix(" is not defined")) {
494 if let Some(at) = first_use(source, name) {
495 return ScriptError { at: Some(at), message, address: None };
496 }
497 }
498 let marker = format!("({SCRIPT_PATH}:");
500 if let Some(i) = first.rfind(&marker) {
501 let spot = &first[i + marker.len()..first.len().saturating_sub(1)];
502 if let Some((line, column)) = spot.split_once(':') {
503 if let (Ok(line), Ok(column)) = (line.parse(), column.parse()) {
504 return ScriptError { message, at: Some(At(line, column)), address: None };
505 }
506 }
507 }
508 if let Some(i) = first.rfind(" at line ") {
510 let spot = &first[i + 9..];
511 if let Some((line, column)) = spot.split_once(", col ") {
512 let column: String = column.chars().take_while(char::is_ascii_digit).collect();
513 if let (Ok(line), Ok(column)) = (line.trim().parse(), column.parse()) {
514 let message = format!("SyntaxError: {}", first[..i].trim_start_matches("SyntaxError: "));
515 return ScriptError { message, at: Some(At(line, column)), address: None };
516 }
517 }
518 }
519 ScriptError { message, at: None, address: None }
520}
521
522fn first_use(source: &str, name: &str) -> Option<At> {
524 let word = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
525 for (i, line) in source.lines().enumerate() {
526 let mut from = 0;
527 while let Some(j) = line[from..].find(name) {
528 let start = from + j;
529 let end = start + name.len();
530 let before = line[..start].chars().next_back();
531 let after = line[end..].chars().next();
532 if !before.is_some_and(|c| word(c) || c == '.') && !after.is_some_and(word) {
533 return Some(At(i as u32 + 1, line[..start].chars().count() as u32 + 1));
534 }
535 from = end;
536 }
537 }
538 None
539}
540
541pub fn library_names() -> Result<Vec<String>, ScriptError> {
545 let outer = GRAPH.with(|g| g.borrow_mut().replace(Graph::new(None)));
546 let mut ctx = Context::default();
547 let listed = install(&mut ctx).map_err(|e| ScriptError { message: format!("library: {e}"), at: None, address: None }).and_then(|_| {
548 ctx.eval(Source::from_bytes(
549 "JSON.stringify(['features','areas','engine','page','world','lines','fills','burin','ink','modules','draw','compose','output','title','view'].flatMap((n) => typeof globalThis[n] === 'function' ? [n] : [n, ...Object.keys(globalThis[n]).filter((k) => typeof Object.getOwnPropertyDescriptor(globalThis[n], k).value === 'function').map((k) => n + '.' + k)]))",
550 ))
551 .and_then(|v| v.to_string(&mut ctx))
552 .map_err(|e| ScriptError { message: e.to_string(), at: None, address: None })
553 });
554 GRAPH.with(|g| *g.borrow_mut() = outer);
555 let mut names: Vec<String> = serde_json::from_str(&listed?.to_std_string_escaped()).unwrap_or_default();
556 names.sort();
557 Ok(names)
558}
559
560#[cfg(test)]
561mod catalog_dts;
562#[cfg(test)]
563mod tests;