Skip to content

Commit

Permalink
update examples, fix deno build
Browse files Browse the repository at this point in the history
  • Loading branch information
WanderLanz committed Jul 20, 2023
1 parent 63fc370 commit 149a793
Show file tree
Hide file tree
Showing 9 changed files with 114 additions and 107 deletions.
2 changes: 1 addition & 1 deletion common.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { VirtualFile } from "./pkg/wasmer_wasix_js";
import { VirtualFile } from "./pkg/wasmer_wasix_js.js";

export function VirtualFileReader(file: VirtualFile, opts?: { chunkSize?: number, strategy?: QueuingStrategy<Uint8Array> }): ReadableStream<Uint8Array> {
let chunkSize = opts?.chunkSize || 65536;
Expand Down
4 changes: 2 additions & 2 deletions examples/deno/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
This example outputs hello world in the `stdout`.

```
$ deno run --allow-net helloworld.ts
$ deno run --allow-read helloworld.ts
hello world
(exit code: 0)
```
Expand All @@ -15,7 +15,7 @@ hello world
This example lists the files and directories on `/`.

```
$ deno run --allow-net fs.ts
$ deno run --allow-read fs.ts
"./a"
"./b"
"./file"
Expand Down
55 changes: 28 additions & 27 deletions examples/deno/fs.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,46 @@
// import init, { WASI } from "https://deno.land/x/wasm/wasi.ts";
import init, { WASI } from "../../wasix.ts";
Error.stackTraceLimit += 30;

// This is needed to load the WASI library first
await init();

const decoder = new TextDecoder("utf-8");
const strategy = new ByteLengthQueuingStrategy({ highWaterMark: 4096 });
const stdout = new WritableStream({
/** @argument {Uint8Array} chunk */
write(chunk) {
let text = decoder.decode(chunk, { stream: true });
console.log(text);
},
close() { console.log("stdout closed"); },
abort() { console.log("stdout aborted"); },
}, strategy);

const wasi = new WASI({
env: {},
args: [],
stdout: stdout.getWriter(),
});

const moduleBytes = fetch(
new URL('../../tests/mapdir.wasm', import.meta.url),
);
// Keep track of open handles (Promises)
let handles: Promise<void>[] = [];

// pipe wasi.stdout to `stdout` string
let stdout = "";
const DecodeStream = () => new TextDecoderStream("utf-8", { ignoreBOM: false, fatal: true });
const StdoutWritable = () => new WritableStream({
write(chunk, _controller) { stdout += chunk; }
});
handles.push(wasi.stdout.pipeThrough(DecodeStream()).pipeTo(StdoutWritable()));

const moduleBytes = fetch(new URL("../../tests/mapdir.wasm", import.meta.url));
const module = await WebAssembly.compileStreaming(moduleBytes);
await wasi.instantiate(module, {});
wasi.instantiate(module, {});

wasi.fs.createDir("/a");
wasi.fs.createDir("/b");

{
const file = wasi.fs.open("/file", { read: true, write: true, create: true });
await file.writeString("fileContents");
await file.flush();
console.log("readString: ", await file.readString());
file.free();
}
const file = wasi.fs.open("/file", { read: true, write: true, create: true });
await file.writeString("fileContents");
await file.seek(0);

const exitCode = wasi.start();

// WASI must be freed before handles are closed, either manually, "wasi.free()", or by garbage collection
wasi.free();
// This should print "hello world (exit code: 0)"
console.log(`(exit code: ${exitCode})`);
// Wait for handles to finish before proceeding
Promise.all(handles).then(() => {
// This should print:
// "./a"
// "./b"
// "./file"
// (exit code: 0)
console.log(`${stdout}(exit code: ${exitCode})`);
});
32 changes: 25 additions & 7 deletions examples/deno/helloworld.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { init, WASI } from "https://deno.land/x/wasm/wasi.ts";
// import init, { WASI } from "https://deno.land/x/wasm/wasi.ts";
import init, { WASI } from "../../wasix.ts";

// This is needed to load the WASI library first
await init();
Expand All @@ -8,13 +9,30 @@ const wasi = new WASI({
args: [],
});

const moduleBytes = fetch(
"https://cdn.deno.land/wasm/versions/v1.0.2/raw/tests/demo.wasm",
);
// Keep track of open handles (Promises)
let handles: Promise<void>[] = [];

// pipe wasi.stdout to `stdout` string
let stdout = "";
const DecodeStream = () => new TextDecoderStream("utf-8", { ignoreBOM: false, fatal: true });
const StdoutWritable = () => new WritableStream({
write(chunk, _controller) { stdout += chunk; }
});
handles.push(wasi.stdout.pipeThrough(DecodeStream()).pipeTo(StdoutWritable()));


const moduleBytes = fetch(new URL("../../tests/demo.wasm", import.meta.url));
const module = await WebAssembly.compileStreaming(moduleBytes);
await wasi.instantiate(module, {});

const exitCode = wasi.start();
const stdout = wasi.getStdoutString();
// This should print "hello world (exit code: 0)"
console.log(`${stdout}(exit code: ${exitCode})`);

// WASI must be freed before handles are closed, either manually, "wasi.free()", or by garbage collection
wasi.free();
// Wait for handles to finish before proceeding
Promise.all(handles).then(() => {
// This should print:
// hello world
// (exit code: 0)
console.log(`${stdout}(exit code: ${exitCode})`);
});
8 changes: 1 addition & 7 deletions examples/node/README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
# Wasmer/WASI Node examples

You can run the code with:

```shell
npm i
```

## Hello World

This example outputs hello world in the `stdout`.
Expand All @@ -26,4 +20,4 @@ $ node fs.mjs
"./b"
"./file"
(exit code: 0)
```
```
87 changes: 31 additions & 56 deletions examples/node/fs.mjs
Original file line number Diff line number Diff line change
@@ -1,75 +1,50 @@
// This should print
// ```
// hello world
// (exit code: 0)
// ```

import fs from "node:fs";
import url from "node:url";
import stream from "node:stream";
import init, { WASI, TtyState, VirtualFileReader, VirtualFileWriter } from "../../dist/lib.mjs";
Error.stackTraceLimit += 30;
import fs from "fs";
// import init, { WASI } from "@wasmer/wasi";
import init, { WASI } from "../../dist/lib.min.mjs";

// This is needed to load the WASI library first, must be called before API can be used
// This is needed to load the WASI library first
await init();

const defaultTtyState = Object.assign(new TtyState(), {
columns: 800,
rows: 250,
});

let wasi = new WASI({
env: {},
args: [],
// define the starting state of the tty
tty: defaultTtyState,
});

// keep track of tty/io Promises
// Keep track of open handles (Promises)
let handles = [];
let stdoutBuf = "";

{ // setup tty and stdio handlers
handles.push(
(() => {
const handle = wasi.tty;
const handler = new TransformStream({ transform(chunk, controller) { controller.enqueue(chunk ? chunk : defaultTtyState) } });
return handle.readable.pipeThrough(handler).pipeTo(handle.writable);
})()
);
handles.push(
(() => {
const decoder = new TransformStream({
start(controller) { this.decoder = new TextDecoder("utf-8"); },
transform(chunk, controller) { controller.enqueue(this.decoder.decode(chunk, { stream: true })) },
});
const handler = new WritableStream({
write(chunk, _controller) { stdoutBuf += chunk; }
});
return wasi.stdout.pipeThrough(decoder).pipeTo(handler);
})()
);
}
// pipe wasi.stdout to `stdout` string
let stdout = "";
const DecodeStream = () => new TextDecoderStream("utf-8", { ignoreBOM: false, fatal: true });
const StdoutWritable = () => new WritableStream({
write(chunk, _controller) { stdout += chunk; }
});
handles.push(wasi.stdout.pipeThrough(DecodeStream()).pipeTo(StdoutWritable()));

{ // test fs
wasi.fs.createDir("/a");
wasi.fs.createDir("/b");
let file = wasi.fs.open("/file", { read: true, write: true, create: true });
console.log("await file.writeString(\"fileContents\") ... ", await file.writeString("fileContents"));
await file.flush();
console.log("await file.text() ... ", await file.text());
file.free();
}
const buf = fs.readFileSync(new URL('../../tests/mapdir.wasm', import.meta.url));

const wasm = fs.readFileSync(url.fileURLToPath(new URL('../../tests/mapdir.wasm', import.meta.url)));
const module = await WebAssembly.compile(
new Uint8Array(wasm)
new Uint8Array(buf)
);
wasi.instantiate(module, {});

wasi.fs.createDir("/a");
wasi.fs.createDir("/b");

let file = wasi.fs.open("/file", { read: true, write: true, create: true });
await file.writeString("fileContents");
await file.seek(0);

let exitCode = wasi.start();

// You must call WASI.free() before handles can resolve
// WASI must be freed before handles are closed, either manually, "wasi.free()", or by garbage collection
wasi.free();
// Await handles to flush tty/io
// Wait for handles to finish before proceeding
await Promise.all(handles);
console.log(`${stdoutBuf}(exit code: ${exitCode})`);

// This should print:
// "./a"
// "./b"
// "./file"
// (exit code: 0)
console.log(`${stdout}(exit code: ${exitCode})`);
29 changes: 24 additions & 5 deletions examples/node/helloworld.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fs from "fs";
import { init, WASI } from "@wasmer/wasi";
// import init, { WASI } from "@wasmer/wasi";
import init, { WASI } from "../../dist/lib.min.mjs";

// This is needed to load the WASI library first
await init();
Expand All @@ -9,14 +10,32 @@ let wasi = new WASI({
args: [],
});

const buf = fs.readFileSync('../../tests/demo.wasm');
// Keep track of open handles (Promises)
let handles = [];

// pipe wasi.stdout to `stdout` string
let stdout = "";
const DecodeStream = () => new TextDecoderStream("utf-8", { ignoreBOM: false, fatal: true });
const StdoutWritable = () => new WritableStream({
write(chunk, _controller) { stdout += chunk; }
});
handles.push(wasi.stdout.pipeThrough(DecodeStream()).pipeTo(StdoutWritable()));

const buf = fs.readFileSync(new URL('../../tests/demo.wasm', import.meta.url));

const module = await WebAssembly.compile(
new Uint8Array(buf)
);
await wasi.instantiate(module, {});
wasi.instantiate(module, {});

let exitCode = wasi.start();
let stdout = wasi.getStdoutString();
// This should print "hello world (exit code: 0)"

// WASI must be freed before handles are closed, either manually, "wasi.free()", or by garbage collection
wasi.free();
// Wait for handles to finish before proceeding
await Promise.all(handles);

// This should print:
// hello world
// (exit code: 0)
console.log(`${stdout}(exit code: ${exitCode})`);
Binary file modified pkg/wasmer_wasix_js_bg.wasm
Binary file not shown.
4 changes: 2 additions & 2 deletions wasix.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// @deno-types="./pkg/wasmer_wasix_js.d.ts"
import _init from "./pkg/wasmer_wasix_js.js";
// @deno-types="./pkg/wasmer_wasix_js.d.ts"
export * from "./pkg/wasmer_wasix_js";
export * from "./common";
export * from "./pkg/wasmer_wasix_js.js";
export * from "./common.ts";

let inited: Promise<any> | null = null;
export default async function init(...args: any[]) {
Expand Down

0 comments on commit 149a793

Please sign in to comment.