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

use anyhow::Context;
use dialoguer::Select;
use wasmer_api::backend::{gql::UserWithNamespaces, BackendClient};
use wasmer_deploy_schema::schema::{StringWebcPackageIdent, WebcPackageIdentifierV1};

use super::prompts::PackageCheckMode;

const WASM_STATIC_SERVER_PACKAGE: &str = "wasmer/static-web-server";
const WASM_STATIC_SERVER_VERSION: &str = "1";

const SAMPLE_INDEX_HTML: &str = r#"
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>{title}</title>

    <style>
      body {
        font-family: Arial, sans-serif;
        background-color: #f1f1f1;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        margin: 0;
      }

      .container {
        max-width: 800px;
        text-align: center;
        padding: 50px 20px;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
      }

      h1 {
        font-size: 36px;
        margin-bottom: 20px;
      }

      img {
        max-width: 100%;
        height: auto;
        margin-bottom: 20px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <img src="https://wasmer.io/images/logo.svg" alt="Your Logo" />
      <h1>Hello World!</h1>
      <h2>{title}</h2
      <p>
        Welcome to the Wasmer platform. This is a sample page that you can use as a
        template to create a new app. <br />
        Happy coding!
      </p>
    </div>
  </body>
</html>
"#;

#[derive(clap::ValueEnum, Clone, Copy, Debug)]
pub enum PackageType {
    #[clap(name = "regular")]
    Regular,
    /// A static website.
    #[clap(name = "static-website")]
    StaticWebsite,
}

#[derive(Clone, Copy, Debug)]
pub enum CreateMode {
    Create,
    SelectExisting,
    CreateOrSelect,
}

fn prompt_for_pacakge_type() -> Result<PackageType, anyhow::Error> {
    Select::new()
        .with_prompt("What type of package do you want to create?")
        .items(&["Basic pacakge", "Static website"])
        .interact()
        .map(|idx| match idx {
            0 => PackageType::Regular,
            1 => PackageType::StaticWebsite,
            _ => unreachable!(),
        })
        .map_err(anyhow::Error::from)
}

#[derive(Debug)]
pub struct PackageWizard {
    pub path: PathBuf,
    pub type_: Option<PackageType>,

    pub create_mode: CreateMode,

    /// Namespace to use.
    pub namespace: Option<String>,
    /// Default namespace to use.
    /// Will still show a prompt, with this as the default value.
    /// Ignored if [`Self::namespace`] is set.
    pub namespace_default: Option<String>,

    /// Pre-configured package name.
    pub name: Option<String>,

    pub user: Option<UserWithNamespaces>,
}

pub struct PackageWizardOutput {
    pub ident: StringWebcPackageIdent,
    pub api: Option<wasmer_api::backend::gql::Package>,
    pub local_path: Option<PathBuf>,
    pub local_manifest: Option<wasmer_toml::Manifest>,
}

impl PackageWizard {
    fn build_new_package(&self) -> Result<PackageWizardOutput, anyhow::Error> {
        // New package

        let owner = if let Some(namespace) = &self.namespace {
            namespace.clone()
        } else {
            super::prompts::prompt_for_namespace(
                "Who should own this package?",
                None,
                self.user.as_ref(),
            )?
        };

        let ty = match self.type_ {
            Some(t) => t,
            None => prompt_for_pacakge_type()?,
        };

        let name = if let Some(name) = &self.name {
            name.clone()
        } else {
            super::prompts::prompt_for_ident("What should the package be called?", None)?
        };

        if !self.path.is_dir() {
            std::fs::create_dir_all(&self.path).with_context(|| {
                format!("Failed to create directory: '{}'", self.path.display())
            })?;
        }

        let ident = WebcPackageIdentifierV1 {
            repository: None,
            namespace: owner,
            name,
            tag: None,
        };
        let manifest = match ty {
            PackageType::Regular => todo!(),
            PackageType::StaticWebsite => initialize_static_site(&self.path, &ident)?,
        };

        let manifest_path = self.path.join("wasmer.toml");
        let manifest_raw = manifest
            .to_string()
            .context("could not serialize package manifest")?;
        std::fs::write(manifest_path, manifest_raw)
            .with_context(|| format!("Failed to write manifest to '{}'", self.path.display()))?;

        Ok(PackageWizardOutput {
            ident: ident.into(),
            api: None,
            local_path: Some(self.path.clone()),
            local_manifest: Some(manifest),
        })
    }

    async fn prompt_existing_package(
        &self,
        api: Option<&BackendClient>,
    ) -> Result<PackageWizardOutput, anyhow::Error> {
        // Existing package
        let check = if api.is_some() {
            Some(PackageCheckMode::MustExist)
        } else {
            None
        };

        eprintln!("Enter the name of an existing package:");
        let (ident, api) = super::prompts::prompt_for_package("Package", None, check, api).await?;
        Ok(PackageWizardOutput {
            ident,
            api,
            local_path: None,
            local_manifest: None,
        })
    }

    pub async fn run(
        self,
        api: Option<&BackendClient>,
    ) -> Result<PackageWizardOutput, anyhow::Error> {
        match self.create_mode {
            CreateMode::Create => self.build_new_package(),
            CreateMode::SelectExisting => self.prompt_existing_package(api).await,
            CreateMode::CreateOrSelect => {
                let index = Select::new()
                    .with_prompt("What package do you want to use?")
                    .items(&["Create new package", "Use existing package"])
                    .default(0)
                    .interact()?;

                match index {
                    0 => self.build_new_package(),
                    1 => self.prompt_existing_package(api).await,
                    other => {
                        unreachable!("Unexpected index: {other}");
                    }
                }
            }
        }
    }
}

fn initialize_static_site(
    path: &Path,
    ident: &WebcPackageIdentifierV1,
) -> Result<wasmer_toml::Manifest, anyhow::Error> {
    let full_name = format!("{}/{}", ident.namespace, ident.name);

    let pubdir_name = "public";
    let pubdir = path.join(pubdir_name);
    if !pubdir.is_dir() {
        std::fs::create_dir_all(&pubdir)
            .with_context(|| format!("Failed to create directory: '{}'", pubdir.display()))?;
    }
    let index = pubdir.join("index.html");

    if !index.is_file() {
        std::fs::write(&index, SAMPLE_INDEX_HTML)
            .with_context(|| "Could not write index.html file".to_string())?;
    }

    let manifest = wasmer_toml::Manifest {
        base_directory_path: path.to_owned(),
        module: None,
        package: wasmer_toml::Package {
            name: full_name.clone(),
            version: "0.0.0".parse().unwrap(),
            description: format!("{full_name} website"),
            license: None,
            license_file: None,
            readme: None,
            repository: None,
            homepage: None,
            wasmer_extra_flags: None,
            disable_command_rename: false,
            rename_commands_to_raw_command_name: false,
        },
        dependencies: Some(
            vec![(
                WASM_STATIC_SERVER_PACKAGE.to_string(),
                WASM_STATIC_SERVER_VERSION.to_string(),
            )]
            .into_iter()
            .collect(),
        ),
        fs: Some(
            vec![("public".to_string(), pubdir_name.into())]
                .into_iter()
                .collect(),
        ),
        command: None,
    };

    Ok(manifest)
}

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

    #[tokio::test]
    async fn test_package_wizard_create_static_site() {
        let dir = tempfile::tempdir().unwrap();

        PackageWizard {
            path: dir.path().to_owned(),
            type_: Some(PackageType::StaticWebsite),
            create_mode: CreateMode::Create,
            namespace: Some("christoph".to_string()),
            namespace_default: None,
            name: Some("test123".to_string()),
            user: None,
        }
        .run(None)
        .await
        .unwrap();

        let manifest = std::fs::read_to_string(dir.path().join("wasmer.toml")).unwrap();
        pretty_assertions::assert_eq!(
            manifest,
            r#"[package]
name = 'christoph/test123'
version = '0.0.0'
description = 'christoph/test123 website'

[dependencies]
"wasmer/static-web-server" = '1'

[fs]
public = 'public'
"#,
        );

        assert!(dir.path().join("public").join("index.html").is_file());
    }
}