Files
vscode-extension-samples/wasm-component-model-async/src/extension.ts
2025-08-06 23:43:14 -07:00

47 lines
2.1 KiB
TypeScript

/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { Worker } from 'worker_threads';
// Import the code generated by wit2ts
import { Types, calculator } from './calculator';
export async function activate(context: vscode.ExtensionContext): Promise<void> {
// The channel for printing the result.
const channel = vscode.window.createOutputChannel('Calculator');
context.subscriptions.push(channel);
// The channel for printing the log.
const log = vscode.window.createOutputChannel('Calculator - Log', { log: true });
context.subscriptions.push(log);
// The implementation of the log function that is called from WASM
const service: calculator.Imports.Promisified = {
log: (msg: string) => {
log.info(msg);
}
};
// Load the Wasm module
const filename = vscode.Uri.joinPath(context.extensionUri, 'target', 'wasm32-unknown-unknown', 'debug', 'calculator.wasm');
const bits = await vscode.workspace.fs.readFile(filename) as Uint8Array<ArrayBuffer>;
const module = await WebAssembly.compile(bits);
const worker = new Worker(vscode.Uri.joinPath(context.extensionUri, './out/worker.js').fsPath);
const api = await calculator._.bind(service, module, worker);
context.subscriptions.push(vscode.commands.registerCommand('vscode-samples.wasm-component-model-async.run', async () => {
channel.show();
channel.appendLine('Running calculator example');
const add = Types.Operation.Add({ left: 1, right: 2 });
channel.appendLine(`Add ${await api.calc(add)}`);
const sub = Types.Operation.Sub({ left: 10, right: 8 });
channel.appendLine(`Sub ${await api.calc(sub)}`);
const mul = Types.Operation.Mul({ left: 3, right: 7 });
channel.appendLine(`Mul ${await api.calc(mul)}`);
const div = Types.Operation.Div({ left: 10, right: 2 });
channel.appendLine(`Div ${await api.calc(div)}`);
}));
}