Skip to main content

js_component_bindgen/script/
component.rs

1//! Packaging script source as a data-only WebAssembly component.
2
3use anyhow::{Context, Result};
4use wasm_encoder::{
5    CodeSection, ConstExpr, DataSection, ExportKind, ExportSection, Function, FunctionSection,
6    Instruction, MemorySection, MemoryType, Module, TypeSection, ValType,
7};
8use wasm_metadata::Producers;
9use wit_component::{ComponentEncoder, StringEncoding};
10use wit_parser::Resolve;
11
12use super::{SCRIPT_ONLY_WORLD_NAME, SCRIPT_WIT};
13
14/// A script to package as a script-only component.
15/// Construct scripts with [`ScriptComponent::builder`].
16#[derive(Debug, Clone, bon::Builder)]
17#[non_exhaustive]
18pub struct ScriptComponent {
19    /// Name the script is packaged under.
20    #[builder(into)]
21    pub name: String,
22    /// Script source: an ES module with its imports hoisted to the top and a single trailing
23    /// export list, as Rolldown emits.
24    #[builder(into)]
25    pub source: String,
26    /// Fully-qualified engine world the script was bundled against.
27    #[builder(into)]
28    pub engine_world: String,
29    /// JavaScript export names of the script.
30    pub exports: Vec<String>,
31}
32
33/// Package a script as a component exporting `jco:script/script`.
34///
35/// The component is a data-only core module: every export returns a pointer into a
36/// pre-laid-out return area, so it needs no allocator and no engine.
37pub fn script_component(script: &ScriptComponent) -> Result<Vec<u8>> {
38    let mut resolve = Resolve::default();
39    let pkg = resolve
40        .push_str("script.wit", SCRIPT_WIT)
41        .context("parsing the jco:script WIT")?;
42    let world = resolve
43        .select_world(&[pkg], Some(SCRIPT_ONLY_WORLD_NAME))
44        .context("selecting the jco:script world")?;
45
46    let mut data = DataLayout::default();
47    let exports: Vec<[u32; 2]> = script
48        .exports
49        .iter()
50        .map(|export| data.string(export))
51        .collect();
52    let mut export_list = Vec::with_capacity(exports.len() * 8);
53    for [ptr, len] in &exports {
54        export_list.extend_from_slice(&ptr.to_le_bytes());
55        export_list.extend_from_slice(&len.to_le_bytes());
56    }
57    let export_list = data.bytes(&export_list, 4);
58    let functions = [
59        ("name", data.string(&script.name)),
60        ("source", data.string(&script.source)),
61        ("engine-world", data.string(&script.engine_world)),
62        ("exports", [export_list, exports.len() as u32]),
63    ];
64    let return_areas: Vec<(&str, u32)> = functions
65        .iter()
66        .map(|(name, [ptr, len])| {
67            let mut area = Vec::with_capacity(8);
68            area.extend_from_slice(&ptr.to_le_bytes());
69            area.extend_from_slice(&len.to_le_bytes());
70            (*name, data.bytes(&area, 4))
71        })
72        .collect();
73
74    let mut types = TypeSection::new();
75    types.ty().function([], [ValType::I32]);
76    let mut funcs = FunctionSection::new();
77    let mut code = CodeSection::new();
78    let mut exports_section = ExportSection::new();
79    exports_section.export("memory", ExportKind::Memory, 0);
80    for (idx, (name, area)) in return_areas.iter().enumerate() {
81        funcs.function(0);
82        let mut function = Function::new([]);
83        function.instruction(&Instruction::I32Const(*area as i32));
84        function.instruction(&Instruction::End);
85        code.function(&function);
86        exports_section.export(
87            &format!("jco:script/script@0.1.0#{name}"),
88            ExportKind::Func,
89            idx as u32,
90        );
91    }
92    let mut memory = MemorySection::new();
93    memory.memory(MemoryType {
94        minimum: data.pages(),
95        maximum: None,
96        memory64: false,
97        shared: false,
98        page_size_log2: None,
99    });
100    let mut data_section = DataSection::new();
101    data_section.active(0, &ConstExpr::i32_const(0), data.bytes.clone());
102
103    let mut module = Module::new();
104    module
105        .section(&types)
106        .section(&funcs)
107        .section(&memory)
108        .section(&exports_section)
109        .section(&code)
110        .section(&data_section);
111    let mut bytes = module.finish();
112
113    wit_component::embed_component_metadata(&mut bytes, &resolve, world, StringEncoding::UTF8)
114        .context("embedding the jco:script world")?;
115    let component = ComponentEncoder::default()
116        .validate(true)
117        .module(&bytes)
118        .context("encoding the script-only module")?
119        .encode()
120        .context("encoding the script-only component")?;
121
122    let mut producers = Producers::default();
123    producers.add("language", "JavaScript", "");
124    producers.add("processed-by", "jco", env!("CARGO_PKG_VERSION"));
125    producers
126        .add_to_wasm(&component)
127        .context("adding producers metadata to the script-only component")
128}
129
130/// Bump allocator for the data segment of a script-only component.
131#[derive(Default)]
132struct DataLayout {
133    bytes: Vec<u8>,
134}
135
136impl DataLayout {
137    /// Append `bytes` aligned to `align`, returning its offset.
138    fn bytes(&mut self, bytes: &[u8], align: usize) -> u32 {
139        // Offset zero is left unused so every pointer, including that of empty data, is non-zero.
140        if self.bytes.is_empty() {
141            self.bytes.resize(align.max(8), 0);
142        }
143        let padding = (align - self.bytes.len() % align) % align;
144        self.bytes.resize(self.bytes.len() + padding, 0);
145        let offset = self.bytes.len() as u32;
146        self.bytes.extend_from_slice(bytes);
147        offset
148    }
149
150    /// Append a string, returning its `[ptr, len]` pair.
151    fn string(&mut self, s: &str) -> [u32; 2] {
152        [self.bytes(s.as_bytes(), 1), s.len() as u32]
153    }
154
155    /// Number of 64KiB pages needed to hold the data.
156    fn pages(&self) -> u64 {
157        (self.bytes.len() as u64).div_ceil(65536).max(1)
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    use crate::script::ENGINE_WORLD_ID;
165    use wit_component::DecodedWasm;
166
167    #[test]
168    fn packages_a_script_component() {
169        let component = script_component(
170            &ScriptComponent::builder()
171                .name("hello.js")
172                .source("export const run = () => \"héllo\";\n".repeat(5000))
173                .engine_world(ENGINE_WORLD_ID)
174                .exports(vec!["run".into(), "calc".into()])
175                .build(),
176        )
177        .unwrap();
178
179        let decoded = wit_component::decode(&component).unwrap();
180        let DecodedWasm::Component(resolve, world) = decoded else {
181            panic!("expected a component");
182        };
183        let exports: Vec<String> = resolve.worlds[world]
184            .exports
185            .keys()
186            .map(|key| resolve.name_world_key(key))
187            .collect();
188        assert_eq!(exports, ["jco:script/script@0.1.0"]);
189    }
190}