Skip to main content

js_component_bindgen/script/
bootstrap.rs

1//! Engine world merging and JavaScript bootstrap generation.
2
3use std::collections::BTreeMap;
4use std::fmt::Write as _;
5use std::path::PathBuf;
6
7use anyhow::{Context, Result, bail};
8use heck::{ToLowerCamelCase, ToUpperCamelCase};
9use wit_component::WitPrinter;
10use wit_parser::{
11    CloneMaps, FunctionKind, Interface, InterfaceId, PackageId, Resolve, Span, TypeDefKind,
12    WorldId, WorldItem, WorldKey,
13};
14
15use super::{ENGINE_WORLD_NAME, SCRIPT_ENGINE_WIT};
16
17/// World key of the script loader interface every engine exports.
18const SCRIPT_LOADER_KEY: &str = "jco:script-engine/script-loader@0.1.0";
19
20/// JavaScript export name of the script loader interface on an engine.
21const SCRIPT_LOADER_EXPORT: &str = "scriptLoader";
22
23/// A world that a script engine must support.
24/// Construct inputs with [`WitInput::builder`].
25#[derive(Debug, Clone, bon::Builder)]
26#[non_exhaustive]
27pub struct WitInput {
28    /// Path to a WIT file or directory.
29    #[builder(into)]
30    pub path: PathBuf,
31    /// World to select within the package; the package's only world when `None`.
32    #[builder(into)]
33    pub world: Option<String>,
34}
35
36/// The JavaScript engine the bootstrap module will be componentized with.
37///
38/// The engines agree on how exports are looked up but differ in how a script imports a
39/// function declared directly on the world.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum Backend {
43    StarlingMonkey,
44    QuickJs,
45}
46
47/// A merged engine world and the bootstrap module that implements it.
48/// Construct custom values with [`EngineWorld::builder`].
49#[derive(Debug, Clone, bon::Builder)]
50#[non_exhaustive]
51pub struct EngineWorld {
52    /// Single WIT document (with nested packages) that defines the engine world.
53    #[builder(into)]
54    pub wit: String,
55    /// Name of the engine world within `wit`.
56    #[builder(into)]
57    pub world_name: String,
58    /// JavaScript module to componentize as the engine.
59    #[builder(into)]
60    pub bootstrap: String,
61    /// Specifiers a script may `require`, in world order.
62    pub imports: Vec<String>,
63    /// JavaScript export names of the engine world, excluding the script loader.
64    pub exports: Vec<String>,
65}
66
67/// Build the engine world for `inputs`.
68///
69/// Every input world is merged into one world which additionally exports
70/// `jco:script-engine/script-loader`. Shared packages, such as `wasi:cli`, are unified when the
71/// inputs agree on their contents. Conflicting items with the same name, or two exported
72/// interfaces that would share a JavaScript export name, are errors: the engine has to present
73/// a single namespace to its scripts.
74pub fn engine_world(inputs: &[WitInput], backend: Backend) -> Result<EngineWorld> {
75    if inputs.is_empty() {
76        bail!("at least one WIT world is required to build a script engine");
77    }
78
79    let mut resolve = Resolve::default();
80    let engine_pkg = resolve
81        .push_str("script-engine.wit", SCRIPT_ENGINE_WIT)
82        .context("parsing the jco:script-engine WIT")?;
83    let engine = resolve
84        .select_world(&[engine_pkg], Some(ENGINE_WORLD_NAME))
85        .context("selecting the jco:script-engine world")?;
86
87    let mut clone_maps = CloneMaps::default();
88    for input in inputs {
89        let mut input_resolve = Resolve::default();
90        let (pkg, _) = input_resolve
91            .push_path(&input.path)
92            .with_context(|| format!("parsing WIT at [{}]", input.path.display()))?;
93        let world = input_resolve
94            .select_world(&[pkg], input.world.as_deref())
95            .with_context(|| format!("selecting a world in [{}]", input.path.display()))?;
96        let world_name = input_resolve.worlds[world].name.clone();
97        let remap = resolve
98            .merge(input_resolve)
99            .with_context(|| format!("merging packages from [{}]", input.path.display()))?;
100        let world = remap
101            .map_world(world, Span::default())
102            .with_context(|| format!("locating world [{world_name}] after merge"))?;
103        resolve
104            .merge_worlds(world, engine, &mut clone_maps)
105            .with_context(|| {
106                format!(
107                    "merging world [{world_name}] from [{}] into the engine world",
108                    input.path.display()
109                )
110            })?;
111    }
112
113    let bootstrap = Bootstrap::new(&resolve, engine, backend)?;
114    let wit = print_wit(&resolve, engine_pkg)?;
115
116    Ok(EngineWorld::builder()
117        .wit(wit)
118        .world_name(ENGINE_WORLD_NAME)
119        .bootstrap(bootstrap.render())
120        .imports(bootstrap.import_specifiers())
121        .exports(bootstrap.export_names())
122        .build())
123}
124
125/// Print `resolve` as one WIT document with `main` first and every other package nested.
126fn print_wit(resolve: &Resolve, main: PackageId) -> Result<String> {
127    let nested: Vec<PackageId> = resolve
128        .topological_packages()
129        .into_iter()
130        .filter(|id| *id != main)
131        .collect();
132    let mut printer = WitPrinter::default();
133    printer
134        .print(resolve, main, &nested)
135        .context("printing the engine world WIT")?;
136    Ok(printer.output.to_string())
137}
138
139/// An import of the engine world, as the bootstrap module sees it.
140#[derive(Debug)]
141struct Import {
142    /// Specifier scripts `require` and the bootstrap imports.
143    specifier: String,
144    /// Whether the import is a function declared directly on the world.
145    world_function: bool,
146}
147
148/// An export of the engine world, as the bootstrap module presents it.
149#[derive(Debug)]
150enum Export {
151    /// A function declared directly on the world.
152    Function { js_name: String },
153    /// An interface, exported as an object.
154    Interface {
155        js_name: String,
156        key: String,
157        functions: Vec<String>,
158        resources: Vec<ResourceExport>,
159    },
160}
161
162impl Export {
163    fn js_name(&self) -> &str {
164        match self {
165            Export::Function { js_name } | Export::Interface { js_name, .. } => js_name,
166        }
167    }
168}
169
170/// A resource exported by an interface, exported as a class.
171#[derive(Debug)]
172struct ResourceExport {
173    js_name: String,
174    has_constructor: bool,
175    methods: Vec<String>,
176    statics: Vec<String>,
177}
178
179/// The generated engine bootstrap module.
180struct Bootstrap {
181    imports: Vec<Import>,
182    exports: Vec<Export>,
183}
184
185impl Bootstrap {
186    fn new(resolve: &Resolve, world: WorldId, backend: Backend) -> Result<Self> {
187        let world = &resolve.worlds[world];
188
189        let mut imports = Vec::new();
190        for (key, item) in world.imports.iter() {
191            match item {
192                WorldItem::Interface { .. } => imports.push(Import {
193                    specifier: resolve.name_world_key(key),
194                    world_function: false,
195                }),
196                WorldItem::Function(function) => {
197                    if backend == Backend::QuickJs {
198                        bail!(
199                            "the engine world imports the function [{}] directly; the quickjs \
200                             backend has no module specifier for world-level function imports, \
201                             so move it into an interface or use the starlingmonkey backend",
202                            function.name
203                        );
204                    }
205                    imports.push(Import {
206                        specifier: function.name.clone(),
207                        world_function: true,
208                    });
209                }
210                WorldItem::Type { .. } => {}
211            }
212        }
213
214        let mut exports = Vec::new();
215        let mut seen: BTreeMap<String, String> = BTreeMap::new();
216        for (key, item) in world.exports.iter() {
217            let key_name = resolve.name_world_key(key);
218            if key_name == SCRIPT_LOADER_KEY {
219                continue;
220            }
221            let export = match item {
222                WorldItem::Interface { id, .. } => interface_export(resolve, key, *id, &key_name)?,
223                WorldItem::Function(function) => Export::Function {
224                    js_name: function.name.to_lower_camel_case(),
225                },
226                WorldItem::Type { .. } => continue,
227            };
228            let js_name = export.js_name().to_string();
229            if js_name == SCRIPT_LOADER_EXPORT {
230                bail!(
231                    "the export [{key_name}] would be exported as [{js_name}], which the engine \
232                     reserves for jco:script-engine/script-loader"
233                );
234            }
235            if let Some(previous) = seen.insert(js_name.clone(), key_name.clone()) {
236                bail!(
237                    "the exports [{previous}] and [{key_name}] would both be exported as \
238                     [{js_name}]; a script engine needs distinct JavaScript export names"
239                );
240            }
241            exports.push(export);
242        }
243
244        Ok(Self { imports, exports })
245    }
246
247    fn import_specifiers(&self) -> Vec<String> {
248        self.imports.iter().map(|i| i.specifier.clone()).collect()
249    }
250
251    fn export_names(&self) -> Vec<String> {
252        self.exports
253            .iter()
254            .map(|e| e.js_name().to_string())
255            .collect()
256    }
257
258    fn render(&self) -> String {
259        let mut out = String::new();
260        out.push_str(
261            "// Generated by `jco componentize --script-only`. This module is the engine: its\n\
262             // exports forward to whichever script `scriptLoader.load` evaluated last.\n\n",
263        );
264
265        for (idx, import) in self.imports.iter().enumerate() {
266            if import.world_function {
267                let _ = writeln!(
268                    out,
269                    "import $import{idx} from {};",
270                    js_str(&import.specifier)
271                );
272            } else {
273                let _ = writeln!(
274                    out,
275                    "import * as $import{idx} from {};",
276                    js_str(&import.specifier)
277                );
278            }
279        }
280
281        out.push_str("\nconst $modules = new Map([\n");
282        for (idx, import) in self.imports.iter().enumerate() {
283            if import.world_function {
284                let _ = writeln!(
285                    out,
286                    "  [{}, $namespace({{ default: $import{idx} }})],",
287                    js_str(&import.specifier)
288                );
289            } else {
290                let _ = writeln!(
291                    out,
292                    "  [{}, $namespace($import{idx})],",
293                    js_str(&import.specifier)
294                );
295            }
296        }
297        out.push_str("]);\n\n");
298
299        // The runtime refers to `$modules` and `$linkResources`, defined around it.
300        out.push_str(RUNTIME_JS);
301        out.push('\n');
302
303        let mut links = String::new();
304        for (idx, export) in self.exports.iter().enumerate() {
305            match export {
306                Export::Function { js_name } => {
307                    let _ = writeln!(
308                        out,
309                        "function $export{idx}(...args) {{\n  return $lookup([{}])(...args);\n}}\n\
310                         export {{ $export{idx} as {js_name} }};\n",
311                        js_str(js_name)
312                    );
313                }
314                Export::Interface {
315                    js_name,
316                    key,
317                    functions,
318                    resources,
319                } => {
320                    let _ = writeln!(out, "// {key}");
321                    for resource in resources {
322                        let class = format!("$export{idx}${}", resource.js_name);
323                        let path = format!("{}, {}", js_str(js_name), js_str(&resource.js_name));
324                        let _ = writeln!(out, "class {class} {{");
325                        if resource.has_constructor {
326                            let _ = writeln!(
327                                out,
328                                "  constructor(...args) {{\n    return new ($lookup([{path}]))(...args);\n  }}"
329                            );
330                        } else {
331                            let _ = writeln!(
332                                out,
333                                "  constructor() {{\n    throw new TypeError({});\n  }}",
334                                js_str(&format!(
335                                    "{}.{} has no constructor in the engine world",
336                                    js_name, resource.js_name
337                                ))
338                            );
339                        }
340                        for method in &resource.methods {
341                            let _ = writeln!(
342                                out,
343                                "  {}(...args) {{\n    return $method([{path}], {class}, {}).call(this, ...args);\n  }}",
344                                js_str(method),
345                                js_str(method)
346                            );
347                        }
348                        for stat in &resource.statics {
349                            let _ = writeln!(
350                                out,
351                                "  static {}(...args) {{\n    return $lookup([{path}, {}])(...args);\n  }}",
352                                js_str(stat),
353                                js_str(stat)
354                            );
355                        }
356                        out.push_str("}\n");
357                        let _ = writeln!(links, "  $link([{path}], {class});");
358                    }
359                    let _ = writeln!(out, "const $export{idx} = {{");
360                    for resource in resources {
361                        let _ = writeln!(
362                            out,
363                            "  {}: $export{idx}${},",
364                            js_str(&resource.js_name),
365                            resource.js_name
366                        );
367                    }
368                    for function in functions {
369                        let _ = writeln!(
370                            out,
371                            "  {}(...args) {{\n    return $lookup([{}, {}])(...args);\n  }},",
372                            js_str(function),
373                            js_str(js_name),
374                            js_str(function)
375                        );
376                    }
377                    let _ = writeln!(out, "}};\nexport {{ $export{idx} as {js_name} }};\n");
378                }
379            }
380        }
381
382        let _ = writeln!(out, "function $linkResources() {{\n{links}}}\n");
383        let _ = writeln!(out, "export {{ $scriptLoader as {SCRIPT_LOADER_EXPORT} }};");
384        out
385    }
386}
387
388/// Describe an exported interface for the bootstrap module.
389fn interface_export(
390    resolve: &Resolve,
391    key: &WorldKey,
392    id: InterfaceId,
393    key_name: &str,
394) -> Result<Export> {
395    let iface: &Interface = &resolve.interfaces[id];
396    let js_name = match key {
397        WorldKey::Name(name) => name.to_lower_camel_case(),
398        WorldKey::Interface(_) => iface
399            .name
400            .as_deref()
401            .with_context(|| format!("exported interface [{key_name}] has no name"))?
402            .to_lower_camel_case(),
403    };
404
405    let mut resources: BTreeMap<String, ResourceExport> = BTreeMap::new();
406    for (name, type_id) in iface.types.iter() {
407        if resolve.types[*type_id].kind == TypeDefKind::Resource {
408            resources.insert(
409                name.clone(),
410                ResourceExport {
411                    js_name: name.to_upper_camel_case(),
412                    has_constructor: false,
413                    methods: Vec::new(),
414                    statics: Vec::new(),
415                },
416            );
417        }
418    }
419
420    let mut functions = Vec::new();
421    for function in iface.functions.values() {
422        let resource = match function.kind.resource() {
423            None => {
424                functions.push(function.item_name().to_lower_camel_case());
425                continue;
426            }
427            Some(resource) => resource,
428        };
429        let resource_name = resolve.types[resource]
430            .name
431            .as_deref()
432            .with_context(|| format!("resource of [{}] has no name", function.name))?;
433        let export = resources.get_mut(resource_name).with_context(|| {
434            format!("resource [{resource_name}] is not defined in [{key_name}]")
435        })?;
436        match function.kind {
437            FunctionKind::Constructor(_) => export.has_constructor = true,
438            FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => export
439                .methods
440                .push(function.item_name().to_lower_camel_case()),
441            FunctionKind::Static(_) | FunctionKind::AsyncStatic(_) => export
442                .statics
443                .push(function.item_name().to_lower_camel_case()),
444            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => unreachable!(),
445        }
446    }
447
448    Ok(Export::Interface {
449        js_name,
450        key: key_name.to_string(),
451        functions,
452        resources: resources.into_values().collect(),
453    })
454}
455
456/// Runtime shared by every generated bootstrap module; see the file for how scripts are loaded.
457const RUNTIME_JS: &str = include_str!("runtime.js");
458
459/// Quote `s` as a JavaScript string literal.
460fn js_str(s: &str) -> String {
461    // Rust's debug escaping is a subset of JavaScript string literal syntax:
462    // `\"`, `\\`, `\n`, `\t`, `\r` and `\u{..}` are all accepted by JavaScript.
463    format!("{s:?}")
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469    use std::fs;
470
471    fn write_wit(dir: &std::path::Path, name: &str, contents: &str) -> PathBuf {
472        let path = dir.join(name);
473        fs::write(&path, contents).unwrap();
474        path
475    }
476
477    const WORLD_A: &str = r#"
478package local:a;
479
480interface greeter {
481  resource counter {
482    constructor(start: u32);
483    next: static func() -> counter;
484    get: func() -> u32;
485  }
486  greet: func(name: string) -> string;
487}
488
489world a {
490  import log-it: func(message: string);
491  import wasi:cli/environment@0.2.3;
492  export greeter;
493  export run: func();
494}
495
496package wasi:cli@0.2.3 {
497  interface environment {
498    get-environment: func() -> list<tuple<string, string>>;
499  }
500}
501"#;
502
503    const WORLD_B: &str = r#"
504package local:b;
505
506interface calc {
507  add: func(a: u32, b: u32) -> u32;
508}
509
510world b {
511  import wasi:cli/environment@0.2.3;
512  export calc;
513  export run: func();
514}
515
516package wasi:cli@0.2.3 {
517  interface environment {
518    get-environment: func() -> list<tuple<string, string>>;
519  }
520}
521"#;
522
523    #[test]
524    fn merges_worlds_and_generates_bootstrap() {
525        let dir = tempdir();
526        let a = write_wit(&dir, "a.wit", WORLD_A);
527        let b = write_wit(&dir, "b.wit", WORLD_B);
528        let engine = engine_world(
529            &[
530                WitInput::builder().path(a).build(),
531                WitInput::builder().path(b).world("b").build(),
532            ],
533            Backend::StarlingMonkey,
534        )
535        .unwrap();
536
537        // The merged world is parseable and holds the union of imports and exports.
538        let mut resolve = Resolve::default();
539        let pkg = resolve.push_str("engine.wit", &engine.wit).unwrap();
540        let world = resolve.select_world(&[pkg], Some("engine")).unwrap();
541        let world = &resolve.worlds[world];
542        let mut exports: Vec<String> = world
543            .exports
544            .keys()
545            .map(|key| resolve.name_world_key(key))
546            .collect();
547        exports.sort();
548        assert_eq!(
549            exports,
550            [
551                "jco:script-engine/script-loader@0.1.0",
552                "local:a/greeter",
553                "local:b/calc",
554                "run",
555            ]
556        );
557        let mut imports: Vec<String> = world
558            .imports
559            .keys()
560            .map(|key| resolve.name_world_key(key))
561            .collect();
562        imports.sort();
563        assert_eq!(imports, ["log-it", "wasi:cli/environment@0.2.3"]);
564
565        let mut engine_imports = engine.imports.clone();
566        engine_imports.sort();
567        assert_eq!(engine_imports, ["log-it", "wasi:cli/environment@0.2.3"]);
568        let mut engine_exports = engine.exports.clone();
569        engine_exports.sort();
570        assert_eq!(engine_exports, ["calc", "greeter", "run"]);
571
572        let bootstrap = &engine.bootstrap;
573        assert!(bootstrap.contains(" from \"log-it\";"));
574        assert!(bootstrap.contains(" from \"wasi:cli/environment@0.2.3\";"));
575        assert!(bootstrap.contains("$namespace({ default: $import"));
576        assert!(bootstrap.contains("function $rewrite(source)"));
577        assert!(bootstrap.contains(" as greeter };"));
578        assert!(bootstrap.contains(" as run };"));
579        assert!(bootstrap.contains(" as calc };"));
580        assert!(bootstrap.contains("export { $scriptLoader as scriptLoader };"));
581        assert!(bootstrap.contains("$Counter {"));
582        assert!(bootstrap.contains("static \"next\"(...args)"));
583        assert!(bootstrap.contains("$method([\"greeter\", \"Counter\"], $export"));
584        assert!(bootstrap.contains("$link([\"greeter\", \"Counter\"], $export"));
585    }
586
587    #[test]
588    fn rejects_quickjs_world_function_imports() {
589        let dir = tempdir();
590        let a = write_wit(&dir, "a.wit", WORLD_A);
591        let err =
592            engine_world(&[WitInput::builder().path(a).build()], Backend::QuickJs).unwrap_err();
593        assert!(err.to_string().contains("log-it"), "{err}");
594    }
595
596    #[test]
597    fn rejects_conflicting_exports() {
598        let dir = tempdir();
599        let a = write_wit(&dir, "a.wit", WORLD_A);
600        let conflicting = write_wit(
601            &dir,
602            "c.wit",
603            "package local:c;\ninterface greeter { shout: func(); }\nworld c { export greeter; }\n",
604        );
605        let err = engine_world(
606            &[
607                WitInput::builder().path(a).build(),
608                WitInput::builder().path(conflicting).build(),
609            ],
610            Backend::StarlingMonkey,
611        )
612        .unwrap_err();
613        assert!(err.to_string().contains("greeter"), "{err}");
614    }
615
616    #[test]
617    fn rejects_reserved_export_name() {
618        let dir = tempdir();
619        let reserved = write_wit(
620            &dir,
621            "r.wit",
622            "package local:r;\ninterface script-loader { reload: func(); }\nworld r { export script-loader; }\n",
623        );
624        let err = engine_world(
625            &[WitInput::builder().path(reserved).build()],
626            Backend::StarlingMonkey,
627        )
628        .unwrap_err();
629        assert!(err.to_string().contains("scriptLoader"), "{err}");
630    }
631
632    fn tempdir() -> PathBuf {
633        let dir = std::env::temp_dir().join(format!(
634            "jco-script-{}-{}",
635            std::process::id(),
636            std::time::SystemTime::now()
637                .duration_since(std::time::UNIX_EPOCH)
638                .unwrap()
639                .as_nanos()
640        ));
641        fs::create_dir_all(&dir).unwrap();
642        dir
643    }
644}