Skip to content

Commit

Permalink
Switch to vitest, make the package work in node and in the browser
Browse files Browse the repository at this point in the history
  • Loading branch information
sandhose committed Nov 18, 2024
1 parent ae25bd3 commit ebd6e98
Show file tree
Hide file tree
Showing 27 changed files with 686 additions and 3,393 deletions.
File renamed without changes.
File renamed without changes.
10 changes: 10 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export * from "./pkg/matrix_sdk_crypto_wasm.d";

/**
* Load the WebAssembly module in the background, if it has not already been loaded.
*
* Returns a promise which will resolve once the other methods are ready.
*
* @returns {Promise<void>}
*/
export function initAsync(): Promise<void>;
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./pkg/matrix_sdk_crypto_wasm.js";
export { default as initAsync } from "./pkg/matrix_sdk_crypto_wasm.js";
11 changes: 11 additions & 0 deletions node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export * from "./pkg/matrix_sdk_crypto_wasm.js";

import { initSync } from "./pkg/matrix_sdk_crypto_wasm.js";

import { readFile } from "node:fs/promises";

export const initAsync = async () => {
const bytes = await readFile("./pkg/matrix_sdk_crypto_wasm_bg.wasm");
const module = await WebAssembly.compile(bytes);
initSync({ module });
};
36 changes: 18 additions & 18 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,33 @@
"ruma",
"nio"
],
"main": "pkg/index.js",
"types": "pkg/index.d.ts",
"exports": {
".": {
"node": "./node.js",
"import": "./index.js",
"types": "./index.d.ts"
}
},
"files": [
"pkg/matrix_sdk_crypto_wasm_bg.wasm.js",
"index.js",
"index.d.ts",
"node.js",
"pkg/matrix_sdk_crypto_wasm.js",
"pkg/matrix_sdk_crypto_wasm.js",
"pkg/matrix_sdk_crypto_wasm_bg.wasm.d.ts",
"pkg/index.js",
"pkg/index.d.ts"
"pkg/matrix_sdk_crypto_wasm_bg.wasm"
],
"devDependencies": {
"@babel/core": "^7.23.5",
"@babel/preset-env": "^7.23.5",
"@babel/preset-typescript": "^7.23.3",
"@types/jest": "^29.5.10",
"babel-jest": "^29.7.0",
"cross-env": "^7.0.3",
"eslint": "^8.55.0",
"fake-indexeddb": "^4.0",
"jest": "^28.1.0",
"prettier": "^2.8.3",
"typedoc": "^0.22.17",
"typescript": "4.7",
"wasm-pack": "^0.12.1",
"yargs-parser": "~21.0.1"
"vitest": "^2.1.5",
"wasm-pack": "^0.13.1"
},
"engines": {
"node": ">= 10"
"node": ">= 18"
},
"scripts": {
"lint": "npm run lint:eslint && npm run lint:prettier && npm run lint:types",
Expand All @@ -53,9 +54,8 @@
"lint:types": "tsc --noEmit",
"build": "WASM_PACK_ARGS=--release ./scripts/build.sh",
"build:dev": "WASM_PACK_ARGS=--dev ./scripts/build.sh",
"test": "jest --verbose && yarn run wasm-pack test --node",
"test": "vitest run && yarn run wasm-pack test --node",
"doc": "typedoc --tsconfig .",
"prepack": "npm run build && npm run test"
},
"packageManager": "[email protected]+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}
}
19 changes: 2 additions & 17 deletions scripts/build.sh
Original file line number Diff line number Diff line change
@@ -1,16 +1,7 @@
#!/bin/bash
#!/bin/sh
#
# Build the JavaScript modules
#
# This script is really a workaround for https://github.com/rustwasm/wasm-pack/issues/1074.
#
# Currently, the only reliable way to load WebAssembly in all the JS
# environments we want to target (web-via-webpack, web-via-browserify, jest)
# seems to be to pack the WASM into base64, and then unpack it and instantiate
# it at runtime.
#
# Hopefully one day, https://github.com/rustwasm/wasm-pack/issues/1074 will be
# fixed and this will be unnecessary.

set -e

Expand All @@ -19,10 +10,4 @@ cd $(dirname "$0")/..
# --no-pack disables generation of a `package.json` file. Such a file is
# useless to us (our package uses the hand-written one in the root directory),
# and contains incorrect data (our `main` is `index.js`).
wasm-pack build --no-pack --target web --scope matrix-org --out-dir pkg --weak-refs "${WASM_PACK_ARGS[@]}"

# Make sure that any existing package.json is deleted.
[ -f pkg/package.json ] && rm pkg/package.json

cat pkg/matrix_sdk_crypto_wasm.js scripts/epilogue.js > pkg/index.js
cat pkg/matrix_sdk_crypto_wasm.d.ts scripts/epilogue.d.ts > pkg/index.d.ts
exec wasm-pack build --no-pack --target web --scope matrix-org --out-dir pkg --weak-refs "${WASM_PACK_ARGS[@]}"
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,6 @@ pub fn get_versions() -> Versions {
pub fn start() {
console_error_panic_hook::set_once();
}

#[cfg(test)]
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_node_experimental);
17 changes: 0 additions & 17 deletions tests/asyncload.test.js

This file was deleted.

3 changes: 2 additions & 1 deletion tests/attachment.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { Attachment, EncryptedAttachment } = require("../pkg");
import { describe, expect, test } from "vitest";
import { Attachment, EncryptedAttachment } from "../";

describe(Attachment.name, () => {
const originalData = "hello";
Expand Down
3 changes: 2 additions & 1 deletion tests/backup.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { BackupDecryptionKey } = require("../pkg");
import { describe, expect, test } from "vitest";
import { BackupDecryptionKey } from "../";

const aMegolmKey = {
algorithm: "m.megolm.v1.aes-sha2",
Expand Down
6 changes: 4 additions & 2 deletions tests/dehydrated_devices.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { afterEach, describe, expect, test } from "vitest";
import "fake-indexeddb/auto";

import {
DecryptionSettings,
DeviceId,
Expand All @@ -10,8 +13,7 @@ import {
RoomId,
TrustRequirement,
UserId,
} from "../pkg/matrix_sdk_crypto_wasm";
import "fake-indexeddb/auto";
} from "../";

afterEach(() => {
// reset fake-indexeddb after each test, to make sure we don't leak data
Expand Down
53 changes: 37 additions & 16 deletions tests/device.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const {
import { describe, beforeAll, expect, it, test, vi } from "vitest";
import {
OlmMachine,
UserId,
DeviceId,
Expand All @@ -25,9 +26,10 @@ const {
Qr,
QrCode,
QrCodeScan,
} = require("../pkg");
const { zip, addMachineToMachine } = require("./helper");
const { VerificationRequestPhase, QrState } = require("../pkg");
VerificationRequestPhase,
QrState,
} from "../";
import { zip, addMachineToMachine } from "./helper";

// Uncomment to enable debug logging for tests
//const { Tracing, LoggerLevel } = require("../pkg");
Expand All @@ -51,9 +53,15 @@ describe("DeviceKeyName", () => {
});

describe(OlmMachine.name, () => {
const user = new UserId("@alice:example.org");
const device = new DeviceId("foobar");
const room = new RoomId("!baz:matrix.org");
let user;
let device;
let room;

beforeAll(() => {
user = new UserId("@alice:example.org");
device = new DeviceId("foobar");
room = new RoomId("!baz:matrix.org");
});

function machine(newUser, newDevice) {
return OlmMachine.initialize(newUser || user, newDevice || device);
Expand Down Expand Up @@ -147,8 +155,13 @@ describe(OlmMachine.name, () => {
});

describe("Send to-device message", () => {
const userId1 = new UserId("@alice:example.org");
const deviceId1 = new DeviceId("alice_device");
let userId1;
let deviceId1;

beforeAll(() => {
userId1 = new UserId("@alice:example.org");
deviceId1 = new DeviceId("alice_device");
});

function machine(newUser, newDevice) {
return OlmMachine.initialize(newUser, newDevice);
Expand Down Expand Up @@ -229,11 +242,19 @@ describe("Send to-device message", () => {
});

describe("Key Verification", () => {
const userId1 = new UserId("@alice:example.org");
const deviceId1 = new DeviceId("alice_device");
let userId1;
let deviceId1;

const userId2 = new UserId("@bob:example.org");
const deviceId2 = new DeviceId("bob_device");
let userId2;
let deviceId2;

beforeAll(() => {
userId1 = new UserId("@alice:example.org");
deviceId1 = new DeviceId("alice_device");

userId2 = new UserId("@bob:example.org");
deviceId2 = new DeviceId("bob_device");
});

function machine(newUser, newDevice) {
return OlmMachine.initialize(newUser || userId1, newDevice || deviceId1);
Expand All @@ -250,7 +271,7 @@ describe("Key Verification", () => {
let verificationRequest1;

/** registerChangesCallback function for `verificationRequest1` */
const verificationRequest1ChangesCallback = jest.fn().mockImplementation(() => Promise.resolve());
const verificationRequest1ChangesCallback = vi.fn().mockImplementation(() => Promise.resolve());

// The flow ID.
let flowId;
Expand Down Expand Up @@ -424,7 +445,7 @@ describe("Key Verification", () => {
let sas1;

/** registerChangesCallback function for `sas1` */
const sas1ChangesCallback = jest.fn().mockImplementation(() => Promise.resolve());
const sas1ChangesCallback = vi.fn().mockImplementation(() => Promise.resolve());

// can fetch and accept an ongoing SAS verification (`m.key.verification.accept`)
{
Expand Down Expand Up @@ -933,7 +954,7 @@ describe("Key Verification", () => {
let qr2;

/** registerChangesCallback function for `qr1` */
const qr2ChangesCallback = jest.fn().mockImplementation(() => Promise.resolve());
const qr2ChangesCallback = vi.fn().mockImplementation(() => Promise.resolve());

// can generate a QR code
{
Expand Down
3 changes: 2 additions & 1 deletion tests/ecies.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { Ecies, SecretsBundle, UserId, DeviceId, OlmMachine, RequestType } = require("../pkg/matrix_sdk_crypto_wasm");
import { describe, expect, test } from "vitest";
import { Ecies, SecretsBundle, UserId, DeviceId, OlmMachine, RequestType } from "../";

describe(Ecies.name, () => {
test("can establish a channel and decrypt the initial message", () => {
Expand Down
9 changes: 2 additions & 7 deletions tests/encryption.test.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
const {
CollectStrategy,
EncryptionAlgorithm,
EncryptionSettings,
HistoryVisibility,
VerificationState,
} = require("../pkg");
import { describe, expect, test } from "vitest";
import { CollectStrategy, EncryptionAlgorithm, EncryptionSettings, HistoryVisibility, VerificationState } from "../";

describe("EncryptionAlgorithm", () => {
test("has the correct variant values", () => {
Expand Down
3 changes: 2 additions & 1 deletion tests/events.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { HistoryVisibility } = require("../pkg");
import { describe, expect, test } from "vitest";
import { HistoryVisibility } from "../";

describe("HistoryVisibility", () => {
test("has the correct variant values", () => {
Expand Down
15 changes: 7 additions & 8 deletions tests/helper.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
const { DeviceLists, RequestType, KeysUploadRequest, KeysQueryRequest } = require("../pkg");
import { expect, beforeAll } from "vitest";
import { DeviceLists, RequestType, KeysUploadRequest, KeysQueryRequest } from "../";
import { initAsync } from "../";

function* zip(...arrays) {
beforeAll(() => initAsync());

export function* zip(...arrays) {
const len = Math.min(...arrays.map((array) => array.length));

for (let nth = 0; nth < len; ++nth) {
Expand All @@ -10,7 +14,7 @@ function* zip(...arrays) {

// Add a machine to another machine, i.e. be sure a machine knows
// another exists.
async function addMachineToMachine(machineToAdd, machine) {
export async function addMachineToMachine(machineToAdd, machine) {
const toDeviceEvents = JSON.stringify([]);
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = new Map();
Expand Down Expand Up @@ -86,8 +90,3 @@ async function addMachineToMachine(machineToAdd, machine) {
expect(marked).toStrictEqual(true);
}
}

module.exports = {
zip,
addMachineToMachine,
};
Loading

0 comments on commit ebd6e98

Please sign in to comment.