├── .appveyor.yml ├── .cargo-ok ├── .github └── workflows │ └── deploy-pages.yml ├── .gitignore ├── .gitpod.yml ├── .travis.yml ├── Cargo.toml ├── LICENSE ├── README.md ├── src ├── lib.rs ├── ls.rs ├── open.rs ├── panic_hook.rs ├── random_dice.rs └── sys.rs ├── tests └── web.rs └── www ├── .gitignore ├── .travis.yml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── bootstrap.js ├── browserfs.min.js ├── index.html ├── index.js ├── module.js ├── nuvfs.zip ├── package-lock.json ├── package.json └── webpack.config.js /.appveyor.yml: -------------------------------------------------------------------------------- 1 | install: 2 | - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe 3 | - if not defined RUSTFLAGS rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly 4 | - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin 5 | - rustc -V 6 | - cargo -V 7 | 8 | build: false 9 | 10 | test_script: 11 | - cargo test --locked 12 | -------------------------------------------------------------------------------- /.cargo-ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nushell/demo/3fccd11c2af42127d177f6e77f6dc58768c91b91/.cargo-ok -------------------------------------------------------------------------------- /.github/workflows/deploy-pages.yml: -------------------------------------------------------------------------------- 1 | name: Build and Deploy 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | build-and-deploy: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout 🛎️ 11 | uses: actions/checkout@v2.3.1 12 | with: 13 | persist-credentials: false 14 | 15 | - uses: jetli/wasm-pack-action@v0.3.0 16 | with: 17 | # Optional version of wasm-pack to install(eg. 'v0.9.1', 'latest') 18 | version: "latest" 19 | 20 | - name: Install and Build 🔧 21 | run: | 22 | wasm-pack build 23 | cd www 24 | npm install 25 | npm run build 26 | 27 | - name: Deploy 🚀 28 | uses: JamesIves/github-pages-deploy-action@4.0.0 29 | with: 30 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 31 | BRANCH: gh-pages # The branch the action should deploy to. 32 | FOLDER: www/dist # The folder the action should deploy. 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | bin/ 5 | pkg/ 6 | wasm-pack.log 7 | .DS_Store 8 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | image: gitpod/workspace-wasm 2 | tasks: 3 | - init: | 4 | wasm-pack build 5 | cd www 6 | npm install 7 | cd .. 8 | command: cd www && npm start 9 | github: 10 | prebuilds: 11 | branches: true 12 | pullRequestsFromForks: true 13 | addBadge: true 14 | ports: 15 | - port: 8080 16 | onOpen: open-preview 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | 4 | cache: cargo 5 | 6 | matrix: 7 | include: 8 | 9 | # Builds with wasm-pack. 10 | - rust: beta 11 | env: RUST_BACKTRACE=1 12 | addons: 13 | firefox: latest 14 | chrome: stable 15 | before_script: 16 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 17 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 18 | - cargo install-update -a 19 | - curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f 20 | script: 21 | - cargo generate --git . --name testing 22 | # Having a broken Cargo.toml (in that it has curlies in fields) anywhere 23 | # in any of our parent dirs is problematic. 24 | - mv Cargo.toml Cargo.toml.tmpl 25 | - cd testing 26 | - wasm-pack build 27 | - wasm-pack test --chrome --firefox --headless 28 | 29 | # Builds on nightly. 30 | - rust: nightly 31 | env: RUST_BACKTRACE=1 32 | before_script: 33 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 34 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 35 | - cargo install-update -a 36 | - rustup target add wasm32-unknown-unknown 37 | script: 38 | - cargo generate --git . --name testing 39 | - mv Cargo.toml Cargo.toml.tmpl 40 | - cd testing 41 | - cargo check 42 | - cargo check --target wasm32-unknown-unknown 43 | - cargo check --no-default-features 44 | - cargo check --target wasm32-unknown-unknown --no-default-features 45 | - cargo check --no-default-features --features console_error_panic_hook 46 | - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook 47 | - cargo check --no-default-features --features "console_error_panic_hook wee_alloc" 48 | - cargo check --target wasm32-unknown-unknown --no-default-features --features "console_error_panic_hook wee_alloc" 49 | 50 | # Builds on beta. 51 | - rust: beta 52 | env: RUST_BACKTRACE=1 53 | before_script: 54 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 55 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 56 | - cargo install-update -a 57 | - rustup target add wasm32-unknown-unknown 58 | script: 59 | - cargo generate --git . --name testing 60 | - mv Cargo.toml Cargo.toml.tmpl 61 | - cd testing 62 | - cargo check 63 | - cargo check --target wasm32-unknown-unknown 64 | - cargo check --no-default-features 65 | - cargo check --target wasm32-unknown-unknown --no-default-features 66 | - cargo check --no-default-features --features console_error_panic_hook 67 | - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook 68 | # Note: no enabling the `wee_alloc` feature here because it requires 69 | # nightly for now. 70 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Jonathan Turner "] 3 | edition = "2018" 4 | name = "wasm-nu" 5 | version = "0.1.0" 6 | 7 | [lib] 8 | crate-type = ["cdylib", "rlib"] 9 | 10 | [features] 11 | stable = [] 12 | default = [] 13 | 14 | [dependencies] 15 | encoding_rs = "0.8.28" 16 | serde = { version = "1.0.123", features = ["derive"] } 17 | serde_json = "1.0.62" 18 | wasm-bindgen = "0.2.70" 19 | wasm-bindgen-futures = "0.4.20" 20 | getrandom = { version = "0.2.2", features = ["js"] } 21 | instant = { version = "0.1", features = ["wasm-bindgen", "inaccurate"] } 22 | 23 | # `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size 24 | # compared to the default allocator's ~10K. It is slower than the default 25 | # allocator, however. 26 | # 27 | # Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now. 28 | wee_alloc = { version = "0.4.5", optional = true } 29 | 30 | nu-cli = { git = "https://github.com/nushell/nushell.git", branch = "main", default-features = false } 31 | nu-errors = { git = "https://github.com/nushell/nushell.git", branch = "main", default-features = false } 32 | nu-protocol = { git = "https://github.com/nushell/nushell.git", branch = "main", default-features = false } 33 | nu-source = { git = "https://github.com/nushell/nushell.git", branch = "main", default-features = false } 34 | nu-engine = { git = "https://github.com/nushell/nushell.git", branch = "main", default-features = false } 35 | nu-stream = { git = "https://github.com/nushell/nushell.git", branch = "main", default-features = false } 36 | 37 | web-sys = { version = "0.3.47", features = ["console"] } 38 | 39 | [dev-dependencies] 40 | wasm-bindgen-test = "0.3.20" 41 | 42 | [profile.release] 43 | # Tell `rustc` to optimize for small code size. 44 | opt-level = "s" 45 | 46 | # [package.metadata.wasm-pack.profile.dev] 47 | # # Should `wasm-opt` be used to further optimize the wasm binary generated after 48 | # # the Rust compiler has finished? Using `wasm-opt` can often further decrease 49 | # # binary size or do clever tricks that haven't made their way into LLVM yet. 50 | # # 51 | # # Configuration is set to `false` by default for the dev profile, but it can 52 | # # be set to an array of strings which are explicit arguments to pass to 53 | # # `wasm-opt`. For example `['-Os']` would optimize for size while `['-O4']` 54 | # # would execute very expensive optimizations passes 55 | # wasm-opt = ['-g'] 56 | 57 | # [package.metadata.wasm-pack.profile.release] 58 | # # Should `wasm-opt` be used to further optimize the wasm binary generated after 59 | # # the Rust compiler has finished? Using `wasm-opt` can often further decrease 60 | # # binary size or do clever tricks that haven't made their way into LLVM yet. 61 | # # 62 | # # Configuration is set to `false` by default for the dev profile, but it can 63 | # # be set to an array of strings which are explicit arguments to pass to 64 | # # `wasm-opt`. For example `['-Os']` would optimize for size while `['-O4']` 65 | # # would execute very expensive optimizations passes 66 | # wasm-opt = ['-g'] 67 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020-2021 Nushell Project 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nu wasm demo playground 2 | 3 | [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/nushell/wasm-nu) 4 | 5 | ## ⬇️ Install `wasm-pack` 6 | 7 | First step, [install wasm-pack](https://rustwasm.github.io/wasm-pack/installer/). 8 | 9 | ## 🛠️ Build with `wasm-pack build` 10 | 11 | ``` 12 | wasm-pack build 13 | ``` 14 | 15 | If dependencies changed, run `cargo update` before running the above again. 16 | 17 | ## 🚴 Run the example: 18 | 19 | ``` 20 | cd www 21 | npm install 22 | npm start 23 | (in a browser: ) open "http://localhost:8080" 24 | ``` 25 | 26 | ## Contributing 27 | 28 | Open it in Gitpod! Everything should be compiled and ready to go! 29 | 30 | [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/nushell/wasm-nu) 31 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | mod ls; 2 | mod open; 3 | mod panic_hook; 4 | mod random_dice; 5 | mod sys; 6 | 7 | use wasm_bindgen::prelude::*; 8 | //use wasm_bindgen_futures; 9 | 10 | use nu_cli::{create_default_context, parse_and_eval}; 11 | use nu_engine::whole_stream_command; 12 | use nu_errors::ShellError; 13 | 14 | use serde::Serialize; 15 | 16 | // A macro to provide `println!(..)`-style syntax for `console.log` logging. 17 | macro_rules! log { 18 | ( $( $t:tt )* ) => { 19 | web_sys::console::log_1(&format!( $( $t )* ).into()); 20 | } 21 | } 22 | 23 | // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global 24 | // allocator. 25 | #[cfg(feature = "wee_alloc")] 26 | #[global_allocator] 27 | static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 28 | 29 | #[wasm_bindgen] 30 | extern "C" { 31 | fn alert(s: &str); 32 | } 33 | 34 | #[derive(Serialize)] 35 | enum OkError { 36 | Ok(String), 37 | Error(ShellError), 38 | InternalError(String), 39 | } 40 | 41 | #[wasm_bindgen] 42 | pub async fn run_nu(line: String) -> String { 43 | panic_hook::set_once(); 44 | 45 | let context = create_default_context(true); 46 | match context { 47 | Ok(ctx) => { 48 | // print the command to help debug unhandled errors 49 | log!("processing line {}", &line); 50 | ctx.add_commands(vec![ 51 | whole_stream_command(random_dice::SubCommand), 52 | whole_stream_command(ls::Ls), 53 | whole_stream_command(open::Open), 54 | whole_stream_command(sys::Sys), 55 | ]); 56 | match parse_and_eval(&line, &ctx) { 57 | Ok(val) => match serde_json::to_string(&OkError::Ok(val)) { 58 | Ok(output) => output, 59 | Err(e) => format!("Error converting to json: {:?}", e), 60 | }, 61 | Err(e) => match serde_json::to_string(&OkError::Error(e)) { 62 | Ok(output) => output, 63 | Err(e) => format!("Error converting to json: {:?}", e), 64 | }, 65 | } 66 | } 67 | Err(e) => match serde_json::to_string(&OkError::InternalError(format!("{}", e))) { 68 | Ok(output) => output, 69 | Err(e) => format!("Error converting to json: {:?}", e), 70 | }, 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/ls.rs: -------------------------------------------------------------------------------- 1 | use nu_engine::{CommandArgs, Example, WholeStreamCommand}; 2 | use nu_errors::ShellError; 3 | use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue}; 4 | use nu_source::Tagged; 5 | use nu_stream::{ActionStream, IntoActionStream}; 6 | 7 | use serde::Deserialize; 8 | 9 | use wasm_bindgen::prelude::*; 10 | 11 | #[wasm_bindgen(module = "/www/module.js")] 12 | extern "C" { 13 | fn readdir(path: String) -> String; 14 | } 15 | pub struct Ls; 16 | 17 | #[allow(non_snake_case)] 18 | #[derive(Deserialize, Debug)] 19 | struct DirEntry { 20 | pub name: String, 21 | pub size: u64, 22 | pub isDir: bool, 23 | } 24 | 25 | impl WholeStreamCommand for Ls { 26 | fn name(&self) -> &str { 27 | "ls" 28 | } 29 | 30 | fn signature(&self) -> Signature { 31 | Signature::build("ls").optional( 32 | "path", 33 | SyntaxShape::GlobPattern, 34 | "a path to get the directory contents from", 35 | ) 36 | } 37 | 38 | fn usage(&self) -> &str { 39 | "View the contents of the current or given path." 40 | } 41 | 42 | fn run_with_actions(&self, args: CommandArgs) -> Result { 43 | let name = args.call_info.name_tag.clone(); 44 | let path: Option = args.opt(0)?; 45 | 46 | let s = readdir(path.map(|x| x).unwrap_or_else(|| "/".to_string())); 47 | 48 | let results: Result, String>, _> = serde_json::from_str(&s); 49 | 50 | if let Ok(results) = results { 51 | let results: Vec> = results 52 | .map_err(|e| ShellError::labeled_error(e.clone(), e, name.span))? 53 | .into_iter() 54 | .map(move |x| { 55 | let mut dict = TaggedDictBuilder::new(name.clone()); 56 | dict.insert_untagged("name", UntaggedValue::string(x.name)); 57 | dict.insert_untagged( 58 | "type", 59 | UntaggedValue::string(if x.isDir { "Dir" } else { "File" }), 60 | ); 61 | dict.insert_untagged("size", UntaggedValue::filesize(x.size)); 62 | 63 | ReturnSuccess::value(dict.into_value()) 64 | }) 65 | .collect(); 66 | 67 | Ok(results.into_iter().into_action_stream()) 68 | } else { 69 | Ok(ActionStream::empty()) 70 | } 71 | } 72 | 73 | fn examples(&self) -> Vec { 74 | vec![ 75 | Example { 76 | description: "List all files in the current directory", 77 | example: "ls", 78 | result: None, 79 | }, 80 | Example { 81 | description: "List all files in a subdirectory", 82 | example: "ls subdir", 83 | result: None, 84 | }, 85 | Example { 86 | description: "List all rust files", 87 | example: "ls *.rs", 88 | result: None, 89 | }, 90 | ] 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/open.rs: -------------------------------------------------------------------------------- 1 | use encoding_rs::{Encoding, UTF_8}; 2 | use nu_engine::{CommandArgs, Example, WholeStreamCommand}; 3 | use nu_errors::ShellError; 4 | use nu_protocol::{CommandAction, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value}; 5 | use nu_source::{AnchorLocation, Span, Tag, Tagged}; 6 | use nu_stream::ActionStream; 7 | 8 | use serde::Deserialize; 9 | 10 | use wasm_bindgen::prelude::*; 11 | 12 | #[wasm_bindgen(module = "/www/module.js")] 13 | extern "C" { 14 | fn readfile(path: String) -> String; 15 | } 16 | 17 | pub struct Open; 18 | 19 | #[derive(Deserialize)] 20 | pub struct OpenArgs { 21 | path: Tagged, 22 | raw: Tagged, 23 | encoding: Option>, 24 | } 25 | 26 | impl WholeStreamCommand for Open { 27 | fn name(&self) -> &str { 28 | "open" 29 | } 30 | 31 | fn signature(&self) -> Signature { 32 | Signature::build(self.name()) 33 | .required( 34 | "path", 35 | SyntaxShape::FilePath, 36 | "the file path to load values from", 37 | ) 38 | .switch( 39 | "raw", 40 | "load content as a string instead of a table", 41 | Some('r'), 42 | ) 43 | .named( 44 | "encoding", 45 | SyntaxShape::String, 46 | "encoding to use to open file", 47 | Some('e'), 48 | ) 49 | } 50 | 51 | fn usage(&self) -> &str { 52 | r#"Load a file into a cell, convert to table if possible (avoid by appending '--raw')."# 53 | } 54 | 55 | fn run_with_actions(&self, args: CommandArgs) -> Result { 56 | open(args) 57 | } 58 | 59 | fn examples(&self) -> Vec { 60 | vec![Example { 61 | description: "Opens \"users.csv\" and creates a table from the data", 62 | example: "open users.csv", 63 | result: None, 64 | }] 65 | } 66 | } 67 | 68 | fn open(args: CommandArgs) -> Result { 69 | let scope = args.scope().clone(); 70 | 71 | let path: Tagged = args.req(0)?; 72 | let raw = args.has_flag("raw"); 73 | let encoding: Option> = args.get_flag("encoding")?; 74 | 75 | let span = path.tag.span; 76 | // let ext = if raw.item { 77 | // None 78 | // } else { 79 | // let path = std::path::PathBuf::from(&path.item); 80 | // path.extension() 81 | // .map(|name| name.to_string_lossy().to_string()) 82 | // }; 83 | 84 | let (ext, tagged_contents) = fetch(&path.item, span, raw, encoding)?; 85 | 86 | if let Some(ext) = ext { 87 | // Check if we have a conversion command 88 | if let Some(_command) = scope.get_command(&format!("from {}", ext)) { 89 | // The tag that will used when returning a Value 90 | 91 | return Ok(ActionStream::one(ReturnSuccess::action( 92 | CommandAction::AutoConvert(tagged_contents, ext), 93 | ))); 94 | } 95 | } 96 | 97 | Ok(ActionStream::one(ReturnSuccess::value(tagged_contents))) 98 | } 99 | 100 | #[derive(Deserialize)] 101 | struct JSBuffer { 102 | data: Vec, 103 | } 104 | 105 | // Note that we do not output a Stream in "fetch" since it is only used by "enter" command 106 | // Which we expect to use a concrete Value a not a Stream 107 | pub fn fetch( 108 | path: &str, 109 | span: Span, 110 | raw: bool, 111 | encoding_choice: Option>, 112 | ) -> Result<(Option, Value), ShellError> { 113 | let ext = if raw { 114 | None 115 | } else { 116 | let path = std::path::PathBuf::from(path); 117 | path.extension() 118 | .map(|name| name.to_string_lossy().to_string()) 119 | }; 120 | let file_tag = Tag { 121 | span, 122 | anchor: Some(AnchorLocation::File(path.to_string())), 123 | }; 124 | 125 | let contents = readfile(path.to_string()); 126 | let buffer: Result = serde_json::from_str(&contents)?; 127 | let buffer = buffer.map_err(|e| { 128 | ShellError::labeled_error( 129 | format!("Could not open file: {}", e), 130 | "could not open", 131 | span, 132 | ) 133 | })?; 134 | 135 | let res = buffer.data; 136 | 137 | // If no encoding is provided we try to guess the encoding to read the file with 138 | let encoding = if encoding_choice.is_none() { 139 | UTF_8 140 | } else { 141 | get_encoding(encoding_choice.clone())? 142 | }; 143 | 144 | // If the user specified an encoding, then do not do BOM sniffing 145 | let decoded_res = if encoding_choice.is_some() { 146 | let (cow_res, _replacements) = encoding.decode_with_bom_removal(&res); 147 | cow_res 148 | } else { 149 | // Otherwise, use the default UTF-8 encoder with BOM sniffing 150 | let (cow_res, _actual_encoding, replacements) = encoding.decode(&res); 151 | // If we had to use replacement characters then fallback to binary 152 | if replacements { 153 | return Ok((ext, UntaggedValue::binary(res).into_value(file_tag))); 154 | } 155 | cow_res 156 | }; 157 | let v = UntaggedValue::string(decoded_res.to_string()).into_value(file_tag); 158 | Ok((ext, v)) 159 | } 160 | 161 | pub fn get_encoding(opt: Option>) -> Result<&'static Encoding, ShellError> { 162 | match opt { 163 | None => Ok(UTF_8), 164 | Some(label) => match Encoding::for_label((&label.item).as_bytes()) { 165 | None => Err(ShellError::labeled_error( 166 | format!( 167 | r#"{} is not a valid encoding, refer to https://docs.rs/encoding_rs/0.8.23/encoding_rs/#statics for a valid list of encodings"#, 168 | label.item 169 | ), 170 | "invalid encoding", 171 | label.span(), 172 | )), 173 | Some(encoding) => Ok(encoding), 174 | }, 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /src/panic_hook.rs: -------------------------------------------------------------------------------- 1 | // adapted from the console_error_panic_hook, to allow showing the panic 2 | // message to the user, by adding it to the DOM somewhere 3 | use std::panic; 4 | 5 | extern crate wasm_bindgen; 6 | use wasm_bindgen::prelude::*; 7 | 8 | #[wasm_bindgen] 9 | extern "C" { 10 | // something on the JS side has to expose this global debug object with an error method 11 | #[wasm_bindgen(js_namespace = debug)] 12 | // an explicit module would be cleaner, but for some reason that isn't working here 13 | // #[wasm_bindgen(module = "/www/module.js")] 14 | fn error(msg: String); 15 | 16 | type Error; 17 | 18 | #[wasm_bindgen(constructor)] 19 | fn new() -> Error; 20 | 21 | #[wasm_bindgen(structural, method, getter)] 22 | fn stack(error: &Error) -> String; 23 | } 24 | 25 | fn hook_impl(info: &panic::PanicInfo) { 26 | let mut msg = info.to_string(); 27 | 28 | // Add the error stack to our message. 29 | // 30 | // This ensures that even if the `console` implementation doesn't 31 | // include stacks for `console.error`, the stack is still available 32 | // for the user. Additionally, Firefox's console tries to clean up 33 | // stack traces, and ruins Rust symbols in the process 34 | // (https://bugzilla.mozilla.org/show_bug.cgi?id=1519569) but since 35 | // it only touches the logged message's associated stack, and not 36 | // the message's contents, by including the stack in the message 37 | // contents we make sure it is available to the user. 38 | msg.push_str("\n\nStack:\n\n"); 39 | let e = Error::new(); 40 | let stack = e.stack(); 41 | msg.push_str(&stack); 42 | 43 | // Safari's devtools, on the other hand, _do_ mess with logged 44 | // messages' contents, so we attempt to break their heuristics for 45 | // doing that by appending some whitespace. 46 | // https://github.com/rustwasm/console_error_panic_hook/issues/7 47 | msg.push_str("\n\n"); 48 | 49 | // Finally, expose the panic with `debug.error`! 50 | error(msg); 51 | } 52 | 53 | /// A panic hook for use with 54 | /// [`std::panic::set_hook`](https://doc.rust-lang.org/nightly/std/panic/fn.set_hook.html) 55 | /// that logs panics into 56 | /// [`console.error`](https://developer.mozilla.org/en-US/docs/Web/API/Console/error). 57 | /// 58 | /// On non-wasm targets, prints the panic to `stderr`. 59 | pub fn hook(info: &panic::PanicInfo) { 60 | hook_impl(info); 61 | } 62 | 63 | /// Set the panic hook the first time this is called. Subsequent 64 | /// invocations do nothing. 65 | #[inline] 66 | pub fn set_once() { 67 | use std::sync::Once; 68 | static SET_HOOK: Once = Once::new(); 69 | SET_HOOK.call_once(|| { 70 | panic::set_hook(Box::new(hook)); 71 | }); 72 | } 73 | -------------------------------------------------------------------------------- /src/random_dice.rs: -------------------------------------------------------------------------------- 1 | use nu_engine::{CommandArgs, Example, WholeStreamCommand}; 2 | use nu_errors::ShellError; 3 | use nu_protocol::{Signature, SyntaxShape, UntaggedValue}; 4 | use nu_source::Tagged; 5 | use nu_stream::{ActionStream, IntoActionStream}; 6 | 7 | use serde::Deserialize; 8 | 9 | use wasm_bindgen::prelude::*; 10 | 11 | pub struct SubCommand; 12 | 13 | #[wasm_bindgen(module = "/www/module.js")] 14 | extern "C" { 15 | fn random(start: u32, end: u32) -> u32; 16 | } 17 | 18 | impl WholeStreamCommand for SubCommand { 19 | fn name(&self) -> &str { 20 | "random dice" 21 | } 22 | 23 | fn signature(&self) -> Signature { 24 | Signature::build("random dice") 25 | .named( 26 | "dice", 27 | SyntaxShape::Int, 28 | "The amount of dice being rolled", 29 | Some('d'), 30 | ) 31 | .named( 32 | "sides", 33 | SyntaxShape::Int, 34 | "The amount of sides a die has", 35 | Some('s'), 36 | ) 37 | } 38 | 39 | fn usage(&self) -> &str { 40 | "Generate a random dice roll" 41 | } 42 | 43 | fn run_with_actions(&self, args: CommandArgs) -> Result { 44 | dice(args) 45 | } 46 | 47 | fn examples(&self) -> Vec { 48 | vec![ 49 | Example { 50 | description: "Roll 1 dice with 6 sides each", 51 | example: "random dice", 52 | result: None, 53 | }, 54 | Example { 55 | description: "Roll 10 dice with 12 sides each", 56 | example: "random dice -d 10 -s 12", 57 | result: None, 58 | }, 59 | ] 60 | } 61 | } 62 | 63 | pub fn dice(args: CommandArgs) -> Result { 64 | let tag = args.call_info.name_tag.clone(); 65 | let dice: Option> = args.get_flag("dice")?; 66 | let sides: Option> = args.get_flag("sides")?; 67 | 68 | let dice = if let Some(dice_tagged) = dice { 69 | *dice_tagged 70 | } else { 71 | 1 72 | }; 73 | 74 | let sides = if let Some(sides_tagged) = sides { 75 | *sides_tagged 76 | } else { 77 | 6 78 | }; 79 | 80 | let iter = (0..dice).map(move |_| UntaggedValue::int(random(1, sides)).into_value(tag.clone())); 81 | 82 | Ok(iter.into_action_stream()) 83 | } 84 | -------------------------------------------------------------------------------- /src/sys.rs: -------------------------------------------------------------------------------- 1 | use nu_engine::{CommandArgs, Example, WholeStreamCommand}; 2 | use nu_errors::ShellError; 3 | use nu_protocol::{ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue}; 4 | use nu_stream::ActionStream; 5 | 6 | use serde::Deserialize; 7 | 8 | use wasm_bindgen::prelude::*; 9 | 10 | pub struct Sys; 11 | 12 | #[wasm_bindgen(module = "/www/module.js")] 13 | extern "C" { 14 | fn getPlatform() -> String; 15 | fn getBrowserCookiesEnabled() -> bool; 16 | fn getUserAgent() -> String; 17 | } 18 | 19 | #[derive(Deserialize)] 20 | pub struct SysArgs; 21 | 22 | impl WholeStreamCommand for Sys { 23 | fn name(&self) -> &str { 24 | "sys" 25 | } 26 | 27 | fn signature(&self) -> Signature { 28 | Signature::build("sys") 29 | } 30 | 31 | fn usage(&self) -> &str { 32 | "View information about the current system." 33 | } 34 | 35 | fn run_with_actions(&self, args: CommandArgs) -> Result { 36 | sys(args) 37 | } 38 | 39 | fn examples(&self) -> Vec { 40 | vec![Example { 41 | description: "View information about the current system.", 42 | example: "sys", 43 | result: None, 44 | }] 45 | } 46 | } 47 | 48 | pub fn sys(args: CommandArgs) -> Result { 49 | let tag = args.call_info.name_tag; 50 | 51 | let mut dict = TaggedDictBuilder::new(tag); 52 | dict.insert_untagged("platform", UntaggedValue::string(getPlatform())); 53 | dict.insert_untagged( 54 | "cookies", 55 | UntaggedValue::boolean(getBrowserCookiesEnabled()), 56 | ); 57 | dict.insert_untagged("agent", UntaggedValue::string(getUserAgent())); 58 | 59 | Ok(ActionStream::one(ReturnSuccess::value(dict.into_value()))) 60 | } 61 | -------------------------------------------------------------------------------- /tests/web.rs: -------------------------------------------------------------------------------- 1 | //! Test suite for the Web and headless browsers. 2 | 3 | #![cfg(target_arch = "wasm32")] 4 | 5 | extern crate wasm_bindgen_test; 6 | use wasm_bindgen_test::*; 7 | 8 | wasm_bindgen_test_configure!(run_in_browser); 9 | 10 | #[wasm_bindgen_test] 11 | fn pass() { 12 | assert_eq!(1 + 1, 2); 13 | } 14 | -------------------------------------------------------------------------------- /www/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | -------------------------------------------------------------------------------- /www/.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: "10" 3 | 4 | script: 5 | - ./node_modules/.bin/webpack 6 | -------------------------------------------------------------------------------- /www/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /www/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) [year] [name] 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /www/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

create-wasm-app

4 | 5 | An npm init template for kick starting a project that uses NPM packages containing Rust-generated WebAssembly and bundles them with Webpack. 6 | 7 |

8 | Build Status 9 |

10 | 11 |

12 | Usage 13 | | 14 | Chat 15 |

16 | 17 | Built with 🦀🕸 by The Rust and WebAssembly Working Group 18 |
19 | 20 | ## About 21 | 22 | This template is designed for depending on NPM packages that contain 23 | Rust-generated WebAssembly and using them to create a Website. 24 | 25 | * Want to create an NPM package with Rust and WebAssembly? [Check out 26 | `wasm-pack-template`.](https://github.com/rustwasm/wasm-pack-template) 27 | * Want to make a monorepo-style Website without publishing to NPM? Check out 28 | [`rust-webpack-template`](https://github.com/rustwasm/rust-webpack-template) 29 | and/or 30 | [`rust-parcel-template`](https://github.com/rustwasm/rust-parcel-template). 31 | 32 | ## 🚴 Usage 33 | 34 | ``` 35 | npm init wasm-app 36 | ``` 37 | 38 | ## 🔋 Batteries Included 39 | 40 | - `.gitignore`: ignores `node_modules` 41 | - `LICENSE-APACHE` and `LICENSE-MIT`: most Rust projects are licensed this way, so these are included for you 42 | - `README.md`: the file you are reading now! 43 | - `index.html`: a bare bones html document that includes the webpack bundle 44 | - `index.js`: example js file with a comment showing how to import and use a wasm pkg 45 | - `package.json` and `package-lock.json`: 46 | - pulls in devDependencies for using webpack: 47 | - [`webpack`](https://www.npmjs.com/package/webpack) 48 | - [`webpack-cli`](https://www.npmjs.com/package/webpack-cli) 49 | - [`webpack-dev-server`](https://www.npmjs.com/package/webpack-dev-server) 50 | - defines a `start` script to run `webpack-dev-server` 51 | - `webpack.config.js`: configuration file for bundling your js with webpack 52 | 53 | ## License 54 | 55 | Licensed under either of 56 | 57 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 58 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 59 | 60 | at your option. 61 | 62 | ### Contribution 63 | 64 | Unless you explicitly state otherwise, any contribution intentionally 65 | submitted for inclusion in the work by you, as defined in the Apache-2.0 66 | license, shall be dual licensed as above, without any additional terms or 67 | conditions. 68 | -------------------------------------------------------------------------------- /www/bootstrap.js: -------------------------------------------------------------------------------- 1 | // initialise Sentry to track client-side errors if not on localhost 2 | if (location.hostname !== "localhost" && window.Sentry) { 3 | Sentry.init({ 4 | dsn: 5 | "https://5f1c75f3562d49fc9b17928e13006118@o431530.ingest.sentry.io/5382894", 6 | }); 7 | } 8 | 9 | // Installs globals onto window: 10 | // * Buffer 11 | // * require (monkey-patches if already defined) 12 | // * process 13 | // You can pass in an arbitrary object if you do not wish to pollute 14 | // the global namespace. 15 | BrowserFS.install(window); 16 | 17 | fetch("./nuvfs.zip") 18 | .then(function (response) { 19 | return response.arrayBuffer(); 20 | }) 21 | .then(function (zipData) { 22 | var Buffer = BrowserFS.BFSRequire("buffer").Buffer; 23 | 24 | BrowserFS.configure( 25 | { 26 | fs: "MountableFileSystem", 27 | options: { 28 | "/": { 29 | fs: "ZipFS", 30 | options: { 31 | // Wrap as Buffer object. 32 | zipData: Buffer.from(zipData), 33 | }, 34 | }, 35 | }, 36 | }, 37 | function (e) { 38 | if (e) { 39 | // An error occurred. 40 | throw e; 41 | } 42 | // Otherwise, BrowserFS is ready to use! 43 | // A dependency graph that contains any wasm must all be imported 44 | // asynchronously. This `bootstrap.js` file does the single async import, so 45 | // that no one else needs to worry about it again. 46 | import("./index.js").catch((e) => 47 | console.error("Error importing `index.js`:", e) 48 | ); 49 | } 50 | ); 51 | }); 52 | -------------------------------------------------------------------------------- /www/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Nushell demo - try the CLI in the browser 8 | 9 | 10 | 11 | 119 | 120 | 121 | 122 |
123 |

Welcome to our Nushell demo

124 |
125 | 126 | 128 | 129 |
130 | Contribute on GitHub 131 |
132 | 133 |

134 | 135 | 136 |

137 |
138 | Paste here to provide your own file, saved as "custom" 139 |

140 | 141 |

142 |

143 | For example, paste some json from swapi.dev, then run 146 |

147 |
148 |
149 | 151 |
152 | 153 | Press Enter to run and Ctrl+Enter (or Command+Enter on OSX) to add a new line (add 154 | linebreak) 155 | 156 |

157 |

Loading WebAssembly module and initializing virtual file system...

158 |

159 | This is a work in progress. Not all commands work and some errors break everything, requiring a page reload. 160 | More details on GitHub 161 |

162 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | -------------------------------------------------------------------------------- /www/index.js: -------------------------------------------------------------------------------- 1 | import * as wasm from "wasm-nu"; 2 | 3 | const data = [ 4 | { name: "Bob", age: 25 }, 5 | { name: "Fred", age: 35 }, 6 | ]; 7 | const examples = [ 8 | { 9 | label: "process json", 10 | command: `echo '${JSON.stringify(data)}' | from json`, 11 | }, 12 | { 13 | label: "use where filter", 14 | command: `echo '${JSON.stringify(data)}' | from json | where age > 30`, 15 | }, 16 | { 17 | label: "format as strings", 18 | command: `echo '${JSON.stringify( 19 | data 20 | )}' | from json | format "{name} is {age} old"`, 21 | }, 22 | ]; 23 | 24 | async function run_nu(input) { 25 | try { 26 | return await wasm.run_nu(input); 27 | } catch (e) { 28 | console.log("this never executes, right?!?"); 29 | console.log(e); 30 | return ""; 31 | } 32 | } 33 | 34 | window.addEventListener("unhandledrejection", (event) => { 35 | demo.innerHTML += `
Unhandled promise rejection: ${event.reason}
`; 36 | }); 37 | 38 | // export something for a custom panic hook to call 39 | // for some reason, that's not working with wasm-bindgen and a separate module, 40 | // so we export something global instead 41 | // @ts-ignore 42 | window.debug = { 43 | error(error) { 44 | demo.innerHTML = ` 45 | Uh oh, the Rust process panicked. This likely means we ran a command that isn't supported in the browser. This breaks the entire runtime, which requires a reload of the page to fix.
46 | 47 |
48 | Error message and stack: 49 |
error: ${error}
`; 50 | // @ts-ignore 51 | window.Sentry && Sentry.captureMessage(error); 52 | }, 53 | }; 54 | 55 | var custom = /** @type HTMLTextAreaElement */ (document.getElementById( 56 | "custom" 57 | )); 58 | var nuinput = /** @type HTMLTextAreaElement */ (document.getElementById( 59 | "nuinput" 60 | )); 61 | var demo = document.getElementById("demo"); 62 | demo.classList.remove("loading"); 63 | 64 | async function runCommand() { 65 | var inputsRaw = nuinput.value.split("\n").filter(Boolean); 66 | var inputs = inputsRaw.map((input) => { 67 | return run_nu(input + " | to html --html_color --partial"); 68 | }); 69 | let outputs = await Promise.all(inputs); 70 | 71 | demo.innerHTML = outputs 72 | .map((rawOutput, index) => { 73 | var output = JSON.parse(rawOutput); 74 | if (output.Ok) { 75 | var result = output.Ok.replace( 76 | /(.*)<\/body><\/html>/, 77 | "$1" 78 | ); 79 | if (result) { 80 | return result; 81 | } 82 | return "[no output]"; 83 | } 84 | const error = output.Error.error; 85 | console.log("print error", error); 86 | return `
87 | error: ${ 88 | (error.UntaggedRuntimeError && error.UntaggedRuntimeError.reason) || 89 | (error.Diagnostic && error.Diagnostic.diagnostic.message) || 90 | `unexpected error shape: ${JSON.stringify(error)}` 91 | } 92 |
${index + 1}: ${inputsRaw[index]}
93 | ${ 94 | error.Diagnostic && 95 | error.Diagnostic.diagnostic.labels.map((label) => { 96 | var padding = " ".repeat(label.range.start + 3); 97 | var marker = "^".repeat(label.range.end - label.range.start); 98 | return `
${padding}${marker} ${label.message}
`; 99 | }) 100 | } 101 |
`; 102 | }) 103 | .join("
"); 104 | if (inputsRaw.some((input) => input === "help commands")) { 105 | const commandCells = document.querySelectorAll( 106 | "tr:not(:first-child) td:first-child" 107 | ); 108 | for (const commandCell of commandCells) { 109 | const command = commandCell.textContent; 110 | const link = document.createElement("a"); 111 | link.textContent = command; 112 | link.href = `#${command}`; 113 | link.addEventListener("click", () => { 114 | nuinput.value = `${command} --help`; 115 | runCommand(); 116 | }); 117 | commandCell.textContent = ""; 118 | commandCell.appendChild(link); 119 | } 120 | } 121 | const tables = document.querySelectorAll("#demo > table"); 122 | tables.forEach((table, index) => { 123 | if (table.clientWidth > document.body.clientWidth) { 124 | const button = document.createElement("button"); 125 | button.textContent = "Pivot this overflowing table"; 126 | button.setAttribute( 127 | "data-command", 128 | `${inputsRaw[index]} | pivot | rename key value` 129 | ); 130 | button.style.marginBottom = "0.5rem"; 131 | table.parentNode.insertBefore(button, table.nextSibling); 132 | } 133 | }); 134 | } 135 | 136 | document.getElementById("run-nu").addEventListener("click", (event) => { 137 | runCommand(); 138 | }); 139 | 140 | const examplesContainer = document.getElementById("examples"); 141 | for (const example of examples) { 142 | const button = document.createElement("button"); 143 | button.setAttribute("data-command", example.command); 144 | button.getAttribute; 145 | button.textContent = example.label; 146 | examplesContainer.appendChild(button); 147 | } 148 | document.body.addEventListener("click", (event) => { 149 | const button = /** @type HTMLButtonElement */ (event.target); 150 | const command = button.getAttribute("data-command"); 151 | if (command) { 152 | nuinput.value = command; 153 | runCommand(); 154 | } 155 | if (button.classList.contains("reload")) { 156 | nuinput.value = "help commands"; 157 | location.reload(); 158 | } 159 | }); 160 | 161 | // @ts-ignore 162 | var fs = BrowserFS.BFSRequire("fs"); 163 | if (custom.value) { 164 | fs.writeFile("custom", custom.value); 165 | } 166 | custom.addEventListener("input", () => { 167 | fs.writeFileSync("custom", custom.value); 168 | }); 169 | 170 | nuinput.addEventListener("keydown", (event) => { 171 | if (event.key == "Enter") { 172 | if (event.metaKey || event.ctrlKey) { 173 | const startPos = nuinput.selectionStart; 174 | const endPos = nuinput.selectionEnd; 175 | nuinput.value = 176 | nuinput.value.substring(0, nuinput.selectionStart) + 177 | "\n" + 178 | nuinput.value.substring(nuinput.selectionEnd, nuinput.value.length); 179 | nuinput.selectionStart = startPos + 1; 180 | nuinput.selectionEnd = startPos + 1; 181 | } else { 182 | event.preventDefault(); 183 | try { 184 | runCommand(); 185 | } catch (e) { 186 | console.log(e); 187 | } 188 | } 189 | } 190 | }); 191 | 192 | runCommand(); 193 | -------------------------------------------------------------------------------- /www/module.js: -------------------------------------------------------------------------------- 1 | function getRandomInt(max) { 2 | return Math.floor(Math.random() * Math.floor(max)); 3 | } 4 | 5 | export function random(start, end) { 6 | return getRandomInt(end) + start; 7 | } 8 | 9 | export function writefile(filename, contents) { 10 | // Otherwise, BrowserFS is ready-to-use! 11 | var fs = BrowserFS.BFSRequire("fs"); 12 | fs.writeFileSync(filename, contents); 13 | } 14 | 15 | export function readfile(filename) { 16 | // Otherwise, BrowserFS is ready-to-use! 17 | try { 18 | var fs = BrowserFS.BFSRequire("fs"); 19 | let contents = fs.readFileSync(filename); 20 | 21 | let output = JSON.stringify({ Ok: contents }); 22 | return output; 23 | } catch (e) { 24 | let output = JSON.stringify({ Err: "file not found" }); 25 | return output; 26 | } 27 | } 28 | 29 | export function readdir(path) { 30 | let results = []; 31 | 32 | try { 33 | var fs = BrowserFS.BFSRequire("fs"); 34 | let contents = fs.readdirSync(path); 35 | 36 | let output = []; 37 | 38 | for (let idx in contents) { 39 | let stats = fs.statSync(path + "/" + contents[idx]); 40 | 41 | let out = { 42 | isDir: stats.isDirectory(), 43 | size: stats.size, 44 | name: contents[idx], 45 | }; 46 | output.push(out); 47 | } 48 | 49 | return JSON.stringify({ Ok: output }); 50 | } catch (e) { 51 | let output = JSON.stringify({ Err: e.toString() }); 52 | return output; 53 | } 54 | } 55 | 56 | export function getPlatform() { 57 | return navigator.platform; 58 | } 59 | 60 | export function getBrowserCookiesEnabled() { 61 | return navigator.cookieEnabled; 62 | } 63 | 64 | export function getUserAgent() { 65 | return navigator.userAgent; 66 | } 67 | -------------------------------------------------------------------------------- /www/nuvfs.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nushell/demo/3fccd11c2af42127d177f6e77f6dc58768c91b91/www/nuvfs.zip -------------------------------------------------------------------------------- /www/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wasm-nu", 3 | "version": "0.1.0", 4 | "description": "a demo playground for nushell in the browser", 5 | "main": "index.js", 6 | "scripts": { 7 | "build": "webpack --config webpack.config.js", 8 | "start": "webpack-dev-server" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/nushell/wasm-nu.git" 13 | }, 14 | "keywords": [ 15 | "nushell", 16 | "webassembly", 17 | "wasm", 18 | "rust", 19 | "webpack" 20 | ], 21 | "author": "nushell contributors", 22 | "license": "MIT", 23 | "bugs": { 24 | "url": "https://github.com/nushell/wasm-nu/issues" 25 | }, 26 | "homepage": "https://github.com/nushell/wasm-nu#readme", 27 | "devDependencies": { 28 | "copy-webpack-plugin": "^5.0.0", 29 | "hello-wasm-pack": "^0.1.0", 30 | "webpack": "^4.29.3", 31 | "webpack-cli": "^3.1.0", 32 | "webpack-dev-server": "^3.1.5" 33 | }, 34 | "dependencies": { 35 | "browserfs": "^2.0.0", 36 | "wasm-nu": "file:../pkg" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /www/webpack.config.js: -------------------------------------------------------------------------------- 1 | const CopyWebpackPlugin = require("copy-webpack-plugin"); 2 | const path = require('path'); 3 | 4 | module.exports = { 5 | entry: "./bootstrap.js", 6 | output: { 7 | path: path.resolve(__dirname, "dist"), 8 | filename: "bootstrap.js", 9 | }, 10 | mode: "development", 11 | plugins: [ 12 | new CopyWebpackPlugin(['index.html', 'browserfs.min.js', 'nuvfs.zip']) 13 | ], 14 | }; 15 | --------------------------------------------------------------------------------