Skip to content

webcontainer v1 #220

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"type": "module",
"dependencies": {
"@fontsource/roboto-mono": "^4.5.10",
"@webcontainer/api": "^0.0.8",
"@webcontainer/api": "^1.0.2",
"adm-zip": "^0.5.10",
"base64-js": "^1.5.1",
"marked": "^4.2.12",
Expand Down
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 8 additions & 8 deletions src/app.d.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/// <reference types="@sveltejs/kit" />

// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare namespace App {
// interface Locals {}
// interface Platform {}
// interface Session {}
interface Stuff {
index: import('$lib/types').PartStub[];
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface Platform {}
}
}

export {};
72 changes: 32 additions & 40 deletions src/lib/client/adapters/webcontainer/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { load } from '@webcontainer/api';
import { WebContainer } from '@webcontainer/api';
import base64 from 'base64-js';
import { get_depth } from '../../../utils.js';
import { ready } from '../common/index.js';

/** @type {import('@webcontainer/api').WebContainer} Web container singleton */
let vm;

/** @param {string} label */
function console_stream(label) {
return new WritableStream({
write(chunk) {
console.log(`[${label}] ${chunk}`);
}
});
}

/**
* @param {import('$lib/types').Stub[]} stubs
* @param {(progress: number, status: string) => void} callback
Expand All @@ -31,15 +40,12 @@ export async function create(stubs, callback) {
/** @type {boolean} Track whether there was an error from vite dev server */
let vite_error = false;

callback(1 / 6, 'loading webcontainer');
const WebContainer = await load();

callback(2 / 6, 'booting webcontainer');
callback(1 / 5, 'booting webcontainer');
vm = await WebContainer.boot();

callback(3 / 6, 'writing virtual files');
callback(2 / 5, 'writing virtual files');
const common = await ready;
await vm.loadFiles({
await vm.mount({
'common.zip': {
file: { contents: new Uint8Array(common.zipped) }
},
Expand All @@ -49,24 +55,18 @@ export async function create(stubs, callback) {
...convert_stubs_to_tree(stubs)
});

callback(4 / 6, 'unzipping files');
const unzip = await vm.run(
{
command: 'node',
args: ['unzip.cjs']
},
{
stderr: (data) => console.error(`[unzip] ${data}`)
}
);
const code = await unzip.onExit;
callback(3 / 5, 'unzipping files');
const unzip = await vm.spawn('node', ['unzip.cjs']);
unzip.output.pipeTo(console_stream('unzip'));
const code = await unzip.exit;

if (code !== 0) {
throw new Error('Failed to initialize WebContainer');
}

await vm.run({ command: 'chmod', args: ['a+x', 'node_modules/vite/bin/vite.js'] });
await vm.spawn('chmod', ['a+x', 'node_modules/vite/bin/vite.js']);

callback(5 / 6, 'starting dev server');
callback(4 / 5, 'starting dev server');
const base = await new Promise(async (fulfil, reject) => {
const error_unsub = vm.on('error', (error) => {
error_unsub();
Expand All @@ -75,27 +75,21 @@ export async function create(stubs, callback) {

const ready_unsub = vm.on('server-ready', (port, base) => {
ready_unsub();
callback(6 / 6, 'ready');
callback(5 / 5, 'ready');
fulfil(base); // this will be the last thing that happens if everything goes well
});

await run_dev();

async function run_dev() {
const process = await vm.run(
{ command: 'turbo', args: ['run', 'dev'] },
{
stdout: (data) => {
console.log(`[dev] ${data}`);
},
stderr: (data) => {
vite_error = true;
console.error(`[dev] ${data}`);
}
}
);
const process = await vm.spawn('turbo', ['run', 'dev']);

// TODO differentiate between stdout and stderr (sets `vite_error` to `true`)
// https://github.com/stackblitz/webcontainer-core/issues/971
process.output.pipeTo(console_stream('dev'));

// keep restarting dev server (can crash in case of illegal +files for example)
process.onExit.then((code) => {
process.exit.then((code) => {
if (code !== 0) {
setTimeout(() => {
run_dev();
Expand Down Expand Up @@ -185,10 +179,10 @@ export async function create(stubs, callback) {
// This will invoke a restart of Vite. Hacky but it works.
// TODO: remove when https://github.com/vitejs/vite/issues/12127 is closed
if (!previous_env && current_stubs.has('/.env')) {
await vm.run({ command: 'touch', args: ['.env']});
await vm.spawn('touch', ['.env']);
}

await vm.loadFiles(convert_stubs_to_tree(to_write));
await vm.mount(convert_stubs_to_tree(to_write));
await promise;
await new Promise((f) => setTimeout(f, 200)); // wait for chokidar

Expand Down Expand Up @@ -220,13 +214,13 @@ export async function create(stubs, callback) {
};
}

tree = /** @type {import('@webcontainer/api').DirectoryEntry} */ (tree[part]).directory;
tree = /** @type {import('@webcontainer/api').DirectoryNode} */ (tree[part]).directory;
}

tree[basename] = to_file(stub);
}

await vm.loadFiles(root);
await vm.mount(root);

stubs_to_map(stubs, current_stubs);

Expand All @@ -236,8 +230,6 @@ export async function create(stubs, callback) {
},
destroy: async () => {
vm.teardown();
// @ts-ignore
vm = null;
}
};
}
Expand Down