js-component-bindgen 2.19.1

JS component bindgen for transpiling WebAssembly components into JavaScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! Engine world merging and JavaScript bootstrap generation.

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::PathBuf;

use anyhow::{Context, Result, bail};
use heck::{ToLowerCamelCase, ToUpperCamelCase};
use wit_component::WitPrinter;
use wit_parser::{
    CloneMaps, FunctionKind, Interface, InterfaceId, PackageId, Resolve, Span, TypeDefKind,
    WorldId, WorldItem, WorldKey,
};

use super::{ENGINE_WORLD_NAME, SCRIPT_ENGINE_WIT};

/// World key of the script loader interface every engine exports.
const SCRIPT_LOADER_KEY: &str = "jco:script-engine/script-loader@0.1.0";

/// JavaScript export name of the script loader interface on an engine.
const SCRIPT_LOADER_EXPORT: &str = "scriptLoader";

/// A world that a script engine must support.
/// Construct inputs with [`WitInput::builder`].
#[derive(Debug, Clone, bon::Builder)]
#[non_exhaustive]
pub struct WitInput {
    /// Path to a WIT file or directory.
    #[builder(into)]
    pub path: PathBuf,
    /// World to select within the package; the package's only world when `None`.
    #[builder(into)]
    pub world: Option<String>,
}

/// The JavaScript engine the bootstrap module will be componentized with.
///
/// The engines agree on how exports are looked up but differ in how a script imports a
/// function declared directly on the world.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Backend {
    StarlingMonkey,
    QuickJs,
}

/// A merged engine world and the bootstrap module that implements it.
/// Construct custom values with [`EngineWorld::builder`].
#[derive(Debug, Clone, bon::Builder)]
#[non_exhaustive]
pub struct EngineWorld {
    /// Single WIT document (with nested packages) that defines the engine world.
    #[builder(into)]
    pub wit: String,
    /// Name of the engine world within `wit`.
    #[builder(into)]
    pub world_name: String,
    /// JavaScript module to componentize as the engine.
    #[builder(into)]
    pub bootstrap: String,
    /// Specifiers a script may `require`, in world order.
    pub imports: Vec<String>,
    /// JavaScript export names of the engine world, excluding the script loader.
    pub exports: Vec<String>,
}

/// Build the engine world for `inputs`.
///
/// Every input world is merged into one world which additionally exports
/// `jco:script-engine/script-loader`. Shared packages, such as `wasi:cli`, are unified when the
/// inputs agree on their contents. Conflicting items with the same name, or two exported
/// interfaces that would share a JavaScript export name, are errors: the engine has to present
/// a single namespace to its scripts.
pub fn engine_world(inputs: &[WitInput], backend: Backend) -> Result<EngineWorld> {
    if inputs.is_empty() {
        bail!("at least one WIT world is required to build a script engine");
    }

    let mut resolve = Resolve::default();
    let engine_pkg = resolve
        .push_str("script-engine.wit", SCRIPT_ENGINE_WIT)
        .context("parsing the jco:script-engine WIT")?;
    let engine = resolve
        .select_world(&[engine_pkg], Some(ENGINE_WORLD_NAME))
        .context("selecting the jco:script-engine world")?;

    let mut clone_maps = CloneMaps::default();
    for input in inputs {
        let mut input_resolve = Resolve::default();
        let (pkg, _) = input_resolve
            .push_path(&input.path)
            .with_context(|| format!("parsing WIT at [{}]", input.path.display()))?;
        let world = input_resolve
            .select_world(&[pkg], input.world.as_deref())
            .with_context(|| format!("selecting a world in [{}]", input.path.display()))?;
        let world_name = input_resolve.worlds[world].name.clone();
        let remap = resolve
            .merge(input_resolve)
            .with_context(|| format!("merging packages from [{}]", input.path.display()))?;
        let world = remap
            .map_world(world, Span::default())
            .with_context(|| format!("locating world [{world_name}] after merge"))?;
        resolve
            .merge_worlds(world, engine, &mut clone_maps)
            .with_context(|| {
                format!(
                    "merging world [{world_name}] from [{}] into the engine world",
                    input.path.display()
                )
            })?;
    }

    let bootstrap = Bootstrap::new(&resolve, engine, backend)?;
    let wit = print_wit(&resolve, engine_pkg)?;

    Ok(EngineWorld::builder()
        .wit(wit)
        .world_name(ENGINE_WORLD_NAME)
        .bootstrap(bootstrap.render())
        .imports(bootstrap.import_specifiers())
        .exports(bootstrap.export_names())
        .build())
}

/// Print `resolve` as one WIT document with `main` first and every other package nested.
fn print_wit(resolve: &Resolve, main: PackageId) -> Result<String> {
    let nested: Vec<PackageId> = resolve
        .topological_packages()
        .into_iter()
        .filter(|id| *id != main)
        .collect();
    let mut printer = WitPrinter::default();
    printer
        .print(resolve, main, &nested)
        .context("printing the engine world WIT")?;
    Ok(printer.output.to_string())
}

/// An import of the engine world, as the bootstrap module sees it.
#[derive(Debug)]
struct Import {
    /// Specifier scripts `require` and the bootstrap imports.
    specifier: String,
    /// Whether the import is a function declared directly on the world.
    world_function: bool,
}

/// An export of the engine world, as the bootstrap module presents it.
#[derive(Debug)]
enum Export {
    /// A function declared directly on the world.
    Function { js_name: String },
    /// An interface, exported as an object.
    Interface {
        js_name: String,
        key: String,
        functions: Vec<String>,
        resources: Vec<ResourceExport>,
    },
}

impl Export {
    fn js_name(&self) -> &str {
        match self {
            Export::Function { js_name } | Export::Interface { js_name, .. } => js_name,
        }
    }
}

/// A resource exported by an interface, exported as a class.
#[derive(Debug)]
struct ResourceExport {
    js_name: String,
    has_constructor: bool,
    methods: Vec<String>,
    statics: Vec<String>,
}

/// The generated engine bootstrap module.
struct Bootstrap {
    imports: Vec<Import>,
    exports: Vec<Export>,
}

impl Bootstrap {
    fn new(resolve: &Resolve, world: WorldId, backend: Backend) -> Result<Self> {
        let world = &resolve.worlds[world];

        let mut imports = Vec::new();
        for (key, item) in world.imports.iter() {
            match item {
                WorldItem::Interface { .. } => imports.push(Import {
                    specifier: resolve.name_world_key(key),
                    world_function: false,
                }),
                WorldItem::Function(function) => {
                    if backend == Backend::QuickJs {
                        bail!(
                            "the engine world imports the function [{}] directly; the quickjs \
                             backend has no module specifier for world-level function imports, \
                             so move it into an interface or use the starlingmonkey backend",
                            function.name
                        );
                    }
                    imports.push(Import {
                        specifier: function.name.clone(),
                        world_function: true,
                    });
                }
                WorldItem::Type { .. } => {}
            }
        }

        let mut exports = Vec::new();
        let mut seen: BTreeMap<String, String> = BTreeMap::new();
        for (key, item) in world.exports.iter() {
            let key_name = resolve.name_world_key(key);
            if key_name == SCRIPT_LOADER_KEY {
                continue;
            }
            let export = match item {
                WorldItem::Interface { id, .. } => interface_export(resolve, key, *id, &key_name)?,
                WorldItem::Function(function) => Export::Function {
                    js_name: function.name.to_lower_camel_case(),
                },
                WorldItem::Type { .. } => continue,
            };
            let js_name = export.js_name().to_string();
            if js_name == SCRIPT_LOADER_EXPORT {
                bail!(
                    "the export [{key_name}] would be exported as [{js_name}], which the engine \
                     reserves for jco:script-engine/script-loader"
                );
            }
            if let Some(previous) = seen.insert(js_name.clone(), key_name.clone()) {
                bail!(
                    "the exports [{previous}] and [{key_name}] would both be exported as \
                     [{js_name}]; a script engine needs distinct JavaScript export names"
                );
            }
            exports.push(export);
        }

        Ok(Self { imports, exports })
    }

    fn import_specifiers(&self) -> Vec<String> {
        self.imports.iter().map(|i| i.specifier.clone()).collect()
    }

    fn export_names(&self) -> Vec<String> {
        self.exports
            .iter()
            .map(|e| e.js_name().to_string())
            .collect()
    }

    fn render(&self) -> String {
        let mut out = String::new();
        out.push_str(
            "// Generated by `jco componentize --script-only`. This module is the engine: its\n\
             // exports forward to whichever script `scriptLoader.load` evaluated last.\n\n",
        );

        for (idx, import) in self.imports.iter().enumerate() {
            if import.world_function {
                let _ = writeln!(
                    out,
                    "import $import{idx} from {};",
                    js_str(&import.specifier)
                );
            } else {
                let _ = writeln!(
                    out,
                    "import * as $import{idx} from {};",
                    js_str(&import.specifier)
                );
            }
        }

        out.push_str("\nconst $modules = new Map([\n");
        for (idx, import) in self.imports.iter().enumerate() {
            if import.world_function {
                let _ = writeln!(
                    out,
                    "  [{}, $namespace({{ default: $import{idx} }})],",
                    js_str(&import.specifier)
                );
            } else {
                let _ = writeln!(
                    out,
                    "  [{}, $namespace($import{idx})],",
                    js_str(&import.specifier)
                );
            }
        }
        out.push_str("]);\n\n");

        // The runtime refers to `$modules` and `$linkResources`, defined around it.
        out.push_str(RUNTIME_JS);
        out.push('\n');

        let mut links = String::new();
        for (idx, export) in self.exports.iter().enumerate() {
            match export {
                Export::Function { js_name } => {
                    let _ = writeln!(
                        out,
                        "function $export{idx}(...args) {{\n  return $lookup([{}])(...args);\n}}\n\
                         export {{ $export{idx} as {js_name} }};\n",
                        js_str(js_name)
                    );
                }
                Export::Interface {
                    js_name,
                    key,
                    functions,
                    resources,
                } => {
                    let _ = writeln!(out, "// {key}");
                    for resource in resources {
                        let class = format!("$export{idx}${}", resource.js_name);
                        let path = format!("{}, {}", js_str(js_name), js_str(&resource.js_name));
                        let _ = writeln!(out, "class {class} {{");
                        if resource.has_constructor {
                            let _ = writeln!(
                                out,
                                "  constructor(...args) {{\n    return new ($lookup([{path}]))(...args);\n  }}"
                            );
                        } else {
                            let _ = writeln!(
                                out,
                                "  constructor() {{\n    throw new TypeError({});\n  }}",
                                js_str(&format!(
                                    "{}.{} has no constructor in the engine world",
                                    js_name, resource.js_name
                                ))
                            );
                        }
                        for method in &resource.methods {
                            let _ = writeln!(
                                out,
                                "  {}(...args) {{\n    return $method([{path}], {class}, {}).call(this, ...args);\n  }}",
                                js_str(method),
                                js_str(method)
                            );
                        }
                        for stat in &resource.statics {
                            let _ = writeln!(
                                out,
                                "  static {}(...args) {{\n    return $lookup([{path}, {}])(...args);\n  }}",
                                js_str(stat),
                                js_str(stat)
                            );
                        }
                        out.push_str("}\n");
                        let _ = writeln!(links, "  $link([{path}], {class});");
                    }
                    let _ = writeln!(out, "const $export{idx} = {{");
                    for resource in resources {
                        let _ = writeln!(
                            out,
                            "  {}: $export{idx}${},",
                            js_str(&resource.js_name),
                            resource.js_name
                        );
                    }
                    for function in functions {
                        let _ = writeln!(
                            out,
                            "  {}(...args) {{\n    return $lookup([{}, {}])(...args);\n  }},",
                            js_str(function),
                            js_str(js_name),
                            js_str(function)
                        );
                    }
                    let _ = writeln!(out, "}};\nexport {{ $export{idx} as {js_name} }};\n");
                }
            }
        }

        let _ = writeln!(out, "function $linkResources() {{\n{links}}}\n");
        let _ = writeln!(out, "export {{ $scriptLoader as {SCRIPT_LOADER_EXPORT} }};");
        out
    }
}

/// Describe an exported interface for the bootstrap module.
fn interface_export(
    resolve: &Resolve,
    key: &WorldKey,
    id: InterfaceId,
    key_name: &str,
) -> Result<Export> {
    let iface: &Interface = &resolve.interfaces[id];
    let js_name = match key {
        WorldKey::Name(name) => name.to_lower_camel_case(),
        WorldKey::Interface(_) => iface
            .name
            .as_deref()
            .with_context(|| format!("exported interface [{key_name}] has no name"))?
            .to_lower_camel_case(),
    };

    let mut resources: BTreeMap<String, ResourceExport> = BTreeMap::new();
    for (name, type_id) in iface.types.iter() {
        if resolve.types[*type_id].kind == TypeDefKind::Resource {
            resources.insert(
                name.clone(),
                ResourceExport {
                    js_name: name.to_upper_camel_case(),
                    has_constructor: false,
                    methods: Vec::new(),
                    statics: Vec::new(),
                },
            );
        }
    }

    let mut functions = Vec::new();
    for function in iface.functions.values() {
        let resource = match function.kind.resource() {
            None => {
                functions.push(function.item_name().to_lower_camel_case());
                continue;
            }
            Some(resource) => resource,
        };
        let resource_name = resolve.types[resource]
            .name
            .as_deref()
            .with_context(|| format!("resource of [{}] has no name", function.name))?;
        let export = resources.get_mut(resource_name).with_context(|| {
            format!("resource [{resource_name}] is not defined in [{key_name}]")
        })?;
        match function.kind {
            FunctionKind::Constructor(_) => export.has_constructor = true,
            FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => export
                .methods
                .push(function.item_name().to_lower_camel_case()),
            FunctionKind::Static(_) | FunctionKind::AsyncStatic(_) => export
                .statics
                .push(function.item_name().to_lower_camel_case()),
            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => unreachable!(),
        }
    }

    Ok(Export::Interface {
        js_name,
        key: key_name.to_string(),
        functions,
        resources: resources.into_values().collect(),
    })
}

/// Runtime shared by every generated bootstrap module; see the file for how scripts are loaded.
const RUNTIME_JS: &str = include_str!("runtime.js");

/// Quote `s` as a JavaScript string literal.
fn js_str(s: &str) -> String {
    // Rust's debug escaping is a subset of JavaScript string literal syntax:
    // `\"`, `\\`, `\n`, `\t`, `\r` and `\u{..}` are all accepted by JavaScript.
    format!("{s:?}")
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    fn write_wit(dir: &std::path::Path, name: &str, contents: &str) -> PathBuf {
        let path = dir.join(name);
        fs::write(&path, contents).unwrap();
        path
    }

    const WORLD_A: &str = r#"
package local:a;

interface greeter {
  resource counter {
    constructor(start: u32);
    next: static func() -> counter;
    get: func() -> u32;
  }
  greet: func(name: string) -> string;
}

world a {
  import log-it: func(message: string);
  import wasi:cli/environment@0.2.3;
  export greeter;
  export run: func();
}

package wasi:cli@0.2.3 {
  interface environment {
    get-environment: func() -> list<tuple<string, string>>;
  }
}
"#;

    const WORLD_B: &str = r#"
package local:b;

interface calc {
  add: func(a: u32, b: u32) -> u32;
}

world b {
  import wasi:cli/environment@0.2.3;
  export calc;
  export run: func();
}

package wasi:cli@0.2.3 {
  interface environment {
    get-environment: func() -> list<tuple<string, string>>;
  }
}
"#;

    #[test]
    fn merges_worlds_and_generates_bootstrap() {
        let dir = tempdir();
        let a = write_wit(&dir, "a.wit", WORLD_A);
        let b = write_wit(&dir, "b.wit", WORLD_B);
        let engine = engine_world(
            &[
                WitInput::builder().path(a).build(),
                WitInput::builder().path(b).world("b").build(),
            ],
            Backend::StarlingMonkey,
        )
        .unwrap();

        // The merged world is parseable and holds the union of imports and exports.
        let mut resolve = Resolve::default();
        let pkg = resolve.push_str("engine.wit", &engine.wit).unwrap();
        let world = resolve.select_world(&[pkg], Some("engine")).unwrap();
        let world = &resolve.worlds[world];
        let mut exports: Vec<String> = world
            .exports
            .keys()
            .map(|key| resolve.name_world_key(key))
            .collect();
        exports.sort();
        assert_eq!(
            exports,
            [
                "jco:script-engine/script-loader@0.1.0",
                "local:a/greeter",
                "local:b/calc",
                "run",
            ]
        );
        let mut imports: Vec<String> = world
            .imports
            .keys()
            .map(|key| resolve.name_world_key(key))
            .collect();
        imports.sort();
        assert_eq!(imports, ["log-it", "wasi:cli/environment@0.2.3"]);

        let mut engine_imports = engine.imports.clone();
        engine_imports.sort();
        assert_eq!(engine_imports, ["log-it", "wasi:cli/environment@0.2.3"]);
        let mut engine_exports = engine.exports.clone();
        engine_exports.sort();
        assert_eq!(engine_exports, ["calc", "greeter", "run"]);

        let bootstrap = &engine.bootstrap;
        assert!(bootstrap.contains(" from \"log-it\";"));
        assert!(bootstrap.contains(" from \"wasi:cli/environment@0.2.3\";"));
        assert!(bootstrap.contains("$namespace({ default: $import"));
        assert!(bootstrap.contains("function $rewrite(source)"));
        assert!(bootstrap.contains(" as greeter };"));
        assert!(bootstrap.contains(" as run };"));
        assert!(bootstrap.contains(" as calc };"));
        assert!(bootstrap.contains("export { $scriptLoader as scriptLoader };"));
        assert!(bootstrap.contains("$Counter {"));
        assert!(bootstrap.contains("static \"next\"(...args)"));
        assert!(bootstrap.contains("$method([\"greeter\", \"Counter\"], $export"));
        assert!(bootstrap.contains("$link([\"greeter\", \"Counter\"], $export"));
    }

    #[test]
    fn rejects_quickjs_world_function_imports() {
        let dir = tempdir();
        let a = write_wit(&dir, "a.wit", WORLD_A);
        let err =
            engine_world(&[WitInput::builder().path(a).build()], Backend::QuickJs).unwrap_err();
        assert!(err.to_string().contains("log-it"), "{err}");
    }

    #[test]
    fn rejects_conflicting_exports() {
        let dir = tempdir();
        let a = write_wit(&dir, "a.wit", WORLD_A);
        let conflicting = write_wit(
            &dir,
            "c.wit",
            "package local:c;\ninterface greeter { shout: func(); }\nworld c { export greeter; }\n",
        );
        let err = engine_world(
            &[
                WitInput::builder().path(a).build(),
                WitInput::builder().path(conflicting).build(),
            ],
            Backend::StarlingMonkey,
        )
        .unwrap_err();
        assert!(err.to_string().contains("greeter"), "{err}");
    }

    #[test]
    fn rejects_reserved_export_name() {
        let dir = tempdir();
        let reserved = write_wit(
            &dir,
            "r.wit",
            "package local:r;\ninterface script-loader { reload: func(); }\nworld r { export script-loader; }\n",
        );
        let err = engine_world(
            &[WitInput::builder().path(reserved).build()],
            Backend::StarlingMonkey,
        )
        .unwrap_err();
        assert!(err.to_string().contains("scriptLoader"), "{err}");
    }

    fn tempdir() -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "jco-script-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        fs::create_dir_all(&dir).unwrap();
        dir
    }
}