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
use std::{
    collections::BTreeMap,
    path::{Path, PathBuf},
};

use anyhow::Context;
use wasmer_config::package::{Command, Manifest, Package, MANIFEST_FILE_NAME};
use webc::metadata::{
    annotations::{self, FileSystemMapping, FileSystemMappings, VolumeSpecificPath},
    BindingsExtended, WaiBindings, WitBindings,
};

const README_PATHS: &[&str; 5] = &[
    "README",
    "README.md",
    "README.markdown",
    "README.mdown",
    "README.mkdn",
];

const LICENSE_PATHS: &[&str; 3] = &["LICENSE", "LICENSE.md", "COPYING"];

/// Methods for manipulating a `wasmer.toml` file and working with WAPM
/// tarballs.
pub trait Transform {
    /// Given a file map, returns the file paths of the atoms in the FileMap
    fn get_atoms_wapm_toml(
        &self,
        files: &BTreeMap<&Path, &Vec<u8>>,
    ) -> Result<Vec<(String, PathBuf)>, anyhow::Error>;

    // given the wapm.toml string, return the [key, value] of the dependencies
    fn get_dependencies(&self, wapm_toml: &str) -> Vec<(String, String)>;

    // get the package annotations
    fn get_package_annotations(
        &self,
        wapm_toml: &str,
    ) -> Result<Option<webc::metadata::annotations::Wapm>, anyhow::Error>;

    fn get_fs_table(&self, wapm_toml: &str) -> Result<FileSystemMappings, anyhow::Error>;

    // get the (name, abi, kind) of the modules
    fn get_modules(&self, wapm_toml: &str) -> Vec<(String, String, String)>;

    // get the commands from a wapm.toml file, given the atom_kinds
    fn get_commands(
        &self,
        wapm_toml: &str,
        base_path: &Path,
        atom_kinds: &BTreeMap<String, String>,
    ) -> Result<BTreeMap<String, WebcCommand>, anyhow::Error>;

    fn get_bindings(
        &self,
        wapm_toml: &str,
        base_path: &Path,
        atom_kinds: &BTreeMap<String, String>,
    ) -> Result<Vec<(String, String, serde_cbor::Value)>, anyhow::Error>;

    fn get_manifest_file_names(&self) -> Vec<PathBuf>;

    fn get_metadata_paths(&self, bindings: &[serde_cbor::Value]) -> Vec<PathBuf>;

    fn get_wapm_manifest_file_name(&self) -> PathBuf;
}

/// The default implementation of [`Transform`].
#[derive(Copy, Clone, Default)]
pub struct TransformManifestFunctions {}

impl Transform for TransformManifestFunctions {
    fn get_atoms_wapm_toml(
        &self,
        files: &BTreeMap<&Path, &Vec<u8>>,
    ) -> Result<Vec<(String, PathBuf)>, anyhow::Error> {
        {
            let paths = files;
            let wapm_toml = paths
                .get(Path::new(MANIFEST_FILE_NAME))
                // Note: old packages used "wapm.toml"
                .or_else(|| paths.get(Path::new("wapm.toml")))
                .with_context(|| {
                    anyhow::anyhow!(
                        "Could not find {MANIFEST_FILE_NAME} in FileMap: {:#?}",
                        paths.keys().collect::<Vec<_>>()
                    )
                })?;

            let wapm_toml =
                std::str::from_utf8(wapm_toml).context("toml file contains invalid UTF-8")?;
            let wapm_toml: Manifest =
                toml::from_str(wapm_toml).context("Could not parse wasmer.toml")?;

            Ok(wapm_toml
                .modules
                .into_iter()
                .map(|m| (m.name.clone(), Path::new(&m.source).to_path_buf()))
                .collect())
        }
    }

    fn get_dependencies(&self, wapm_toml: &str) -> Vec<(String, String)> {
        {
            let wapm: Manifest = match toml::from_str(wapm_toml) {
                Ok(o) => o,
                Err(_) => {
                    return Vec::new();
                }
            };

            wapm.dependencies
                .into_iter()
                .map(|(k, v)| (k, v.to_string()))
                .collect()
        }
    }

    fn get_package_annotations(
        &self,
        wapm_toml: &str,
    ) -> Result<Option<webc::metadata::annotations::Wapm>, anyhow::Error> {
        let wapm: Manifest =
            toml::from_str(wapm_toml).context("Unable to deserialize the manifest")?;
        if let Some(package) = wapm.package.as_ref() {
            return Ok(Some(transform_package_meta_to_annotations(package)));
        }
        Ok(None)
    }

    fn get_fs_table(&self, wapm_toml: &str) -> Result<FileSystemMappings, anyhow::Error> {
        {
            let wapm: Manifest =
                toml::from_str(wapm_toml).context("Unable to deserialize the manifest")?;

            let fs = wapm.fs;

            if fs.is_empty() {
                Ok(FileSystemMappings::default())
            } else {
                // When wapm-targz-to-pirita creates the final webc all files will be
                // merged into one "atom" volume, but we want to map each directory
                // separately.
                let mut entries = Vec::new();
                for (guest, _host) in fs {
                    let mapping = FileSystemMapping {
                        from: None,
                        volume_name: "atom".to_string(),
                        host_path: None,
                        mount_path: sanitize_path(guest),
                    };
                    entries.push(mapping);
                }
                Ok(FileSystemMappings(entries))
            }
        }
    }

    fn get_modules(&self, wapm_toml: &str) -> Vec<(String, String, String)> {
        {
            let wapm: Manifest = match toml::from_str(wapm_toml) {
                Ok(o) => o,
                Err(_) => {
                    return Vec::new();
                }
            };
            wapm.modules
                .iter()
                .map(|m| {
                    (
                        m.name.to_string(),
                        m.abi.to_string(),
                        m.kind.as_deref().unwrap_or("wasm").to_string(),
                    )
                })
                .collect()
        }
    }

    fn get_commands(
        &self,
        wapm_toml: &str,
        base_path: &Path,
        atom_kinds: &BTreeMap<String, String>,
    ) -> Result<BTreeMap<String, WebcCommand>, anyhow::Error> {
        {
            let wapm: Manifest = toml::from_str(wapm_toml)?;
            let mut commands = BTreeMap::new();

            for command in &wapm.commands {
                match command {
                    #[allow(deprecated)]
                    Command::V1(command) => {
                        let name = &command.name;
                        let module = command.module.to_string();
                        let main_args = command.main_args.as_ref();
                        let package = command.package.as_ref();

                        if commands.iter().any(|(k, _)| k == name) {
                            return Err(anyhow::anyhow!(
                                "Command {name} is defined more than once"
                            ));
                        }

                        let abi = atom_kinds.get(&module).map(|s| s.as_str());
                        let runner = match abi {
                            Some("emscripten") => annotations::EMSCRIPTEN_RUNNER_URI,
                            Some("wasm4") => annotations::WASM4_RUNNER_URI,
                            Some("wcgi") => annotations::WCGI_RUNNER_URI,
                            Some("wasi") | Some("generic") => annotations::WASI_RUNNER_URI,
                            _ => {
                                return Err(anyhow::anyhow!(
                                    "Unknown ABI in command {name:?}: {:?}",
                                    abi.unwrap_or("")
                                ));
                            }
                        };

                        let annotations_str = match abi {
                            Some("emscripten") => annotations::Emscripten::KEY,
                            Some("wasm4") => "wasm4",
                            Some("wcgi") => annotations::Wcgi::KEY,
                            Some("wasi") | Some("generic") => annotations::Wasi::KEY,
                            _ => {
                                return Err(anyhow::anyhow!(
                                    "Unknown ABI in command {name:?}: {:?}",
                                    abi.unwrap_or("")
                                ));
                            }
                        };

                        let annotations = vec![(
                            annotations_str.to_string(),
                            serde_cbor::value::to_value(TransformCmdArgs {
                                atom: module,
                                main_args: main_args.cloned(),
                                package: package.cloned(),
                            })
                            .unwrap(),
                        )]
                        .into_iter()
                        .collect();

                        commands.insert(
                            name.clone(),
                            WebcCommand {
                                runner: runner.to_string(),
                                annotations,
                            },
                        );
                    }
                    Command::V2(command) => {
                        let runner = runner_uri_from_name(&command.runner);

                        let annotations = command
                            .get_annotations(base_path)
                            .map_err(|e| anyhow::anyhow!("command {}: {e}", command.name))?;

                        let annotations = match annotations {
                            Some(serde_cbor::Value::Map(annotations)) => annotations
                                .into_iter()
                                .filter_map(|(k, v)| match k {
                                    serde_cbor::Value::Text(key) => Some((key, v)),
                                    _ => None,
                                })
                                .collect(),
                            _ => BTreeMap::default(),
                        };

                        commands.insert(
                            command.name.clone(),
                            WebcCommand {
                                runner,
                                annotations,
                            },
                        );
                    }
                }
            }

            Ok(commands)
        }
    }

    fn get_bindings(
        &self,
        wapm_toml: &str,
        base_path: &Path,
        atom_kinds: &BTreeMap<String, String>,
    ) -> Result<Vec<(String, String, serde_cbor::Value)>, anyhow::Error> {
        {
            let _base_path = base_path;
            let _atom_kinds = atom_kinds;
            let wapm: Manifest = toml::from_str(wapm_toml)?;
            let mut bindings = Vec::new();

            for module in &wapm.modules {
                if let Some(b) = module.bindings.as_ref() {
                    bindings.push(bindings_to_webc(b, &module.name)?);
                }
            }

            Ok(bindings)
        }
    }

    fn get_manifest_file_names(&self) -> Vec<PathBuf> {
        vec![Path::new(MANIFEST_FILE_NAME).to_path_buf()]
    }

    fn get_metadata_paths(&self, bindings: &[serde_cbor::Value]) -> Vec<PathBuf> {
        {
            let mut paths = Vec::new();

            for b in bindings {
                if let Ok(wit) =
                    serde_cbor::from_slice::<BindingsExtended>(&serde_cbor::to_vec(b).unwrap())
                {
                    paths.extend(
                        wit.metadata_paths()
                            .into_iter()
                            .map(|p| p.replacen("metadata://", "", 1))
                            .map(PathBuf::from),
                    );
                }
            }

            for p in README_PATHS.iter() {
                paths.push(Path::new(p).to_path_buf());
            }
            for p in LICENSE_PATHS.iter() {
                paths.push(Path::new(p).to_path_buf());
            }
            paths
        }
    }

    fn get_wapm_manifest_file_name(&self) -> PathBuf {
        Path::new(MANIFEST_FILE_NAME).to_path_buf()
    }
}

fn runner_uri_from_name(runner: &str) -> String {
    // Special cases
    match runner {
        "wasi" => return webc::metadata::annotations::WASI_RUNNER_URI.to_string(),
        "wcgi" => return webc::metadata::annotations::WCGI_RUNNER_URI.to_string(),
        "emscripten" => return webc::metadata::annotations::EMSCRIPTEN_RUNNER_URI.to_string(),
        "wasm4" => return webc::metadata::annotations::WASM4_RUNNER_URI.to_string(),
        _ => {}
    }

    // We'll leave valid URLs as-is.
    if let Ok(url) = url::Url::parse(runner) {
        if url.has_host() {
            return runner.to_string();
        }
    }

    // fall back to something under webc.org
    format!("https://webc.org/runner/{}", runner)
}

/// Turn any path that gets passed in into something WASI can use.
///
/// In general, this means...
///
/// - Use "/" everywhere
/// - Remove "." or ".." components
/// - Make the path absolute because when loaded it'll be absolute with respect
///   to the volume
/// - Get rid of any UNC path stuff
fn sanitize_path(path: impl AsRef<Path>) -> String {
    let path = path.as_ref();

    let mut segments = Vec::new();

    for component in path.components() {
        match component {
            std::path::Component::Prefix(_) | std::path::Component::RootDir => {}
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                segments.pop();
            }
            std::path::Component::Normal(segment) => {
                segments.push(segment.to_string_lossy());
            }
        }
    }

    let mut sanitized = String::new();

    for segment in segments {
        sanitized.push('/');
        sanitized.push_str(&segment);
    }

    sanitized
}

#[derive(Debug, Clone)]
pub struct WebcCommand {
    pub runner: String,
    pub annotations: BTreeMap<String, serde_cbor::Value>,
}

type WebcBinding = (String, String, serde_cbor::Value);

fn bindings_to_webc(
    b: &wasmer_config::package::Bindings,
    module_name: &str,
) -> Result<WebcBinding, anyhow::Error> {
    match b {
        wasmer_config::package::Bindings::Wit(wit) => wit_bindings_to_webc(wit, module_name),
        wasmer_config::package::Bindings::Wai(wai) => wai_bindings_to_webc(wai, module_name),
    }
}

fn wai_bindings_to_webc(
    wai: &wasmer_config::package::WaiBindings,
    module_name: &str,
) -> Result<WebcBinding, anyhow::Error> {
    let exports = wai
        .exports
        .as_ref()
        .map(|exports| format!("metadata://{}", exports.display()));
    let imports = wai
        .imports
        .iter()
        .map(|import| format!("metadata://{}", import.display()))
        .collect();

    let value = serde_cbor::value::to_value(BindingsExtended::Wai(WaiBindings {
        module: format!("atoms://{module_name}"),
        exports,
        imports,
    }))?;

    Ok((
        "library-bindings".to_string(),
        format!("wai@{}", wai.wai_version),
        value,
    ))
}

fn wit_bindings_to_webc(
    wit: &wasmer_config::package::WitBindings,
    module_name: &str,
) -> Result<WebcBinding, anyhow::Error> {
    let value = serde_cbor::value::to_value(BindingsExtended::Wit(WitBindings {
        exports: format!("metadata://{}", wit.wit_exports.display()),
        module: format!("atoms://{module_name}"),
    }))?;

    Ok((
        "library-bindings".to_string(),
        format!("wit@{}", wit.wit_bindgen),
        value,
    ))
}

#[derive(serde::Serialize, serde::Deserialize)]
struct TransformCmdArgs {
    atom: String,
    main_args: Option<String>,
    package: Option<String>,
}

fn transform_package_meta_to_annotations(package: &Package) -> webc::metadata::annotations::Wapm {
    let mut wapm = webc::metadata::annotations::Wapm::new(
        package.name.clone(),
        package.version.clone().map(|v| v.to_string()),
        package.description.clone(),
    );

    wapm.license = package.license.clone();
    wapm.license_file = package
        .license_file
        .as_ref()
        .map(|path| VolumeSpecificPath {
            volume: "metadata".to_string(),
            path: path.display().to_string(),
        });
    wapm.readme = package.readme.as_ref().map(|path| VolumeSpecificPath {
        volume: "metadata".to_string(),
        path: path.display().to_string(),
    });
    wapm.repository = package.repository.clone();
    wapm.homepage = package.homepage.clone();

    wapm
}