-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
100 lines (97 loc) · 2.34 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="./types/std.ts" />
import {
Imports,
instantiate as asLoaderInstantiate,
ResultObject,
} from "@assemblyscript/loader";
import type {
WasmModuleInstance,
JsModuleInstance,
ModuleInstance,
AsLoaderModule,
} from "./types";
import type {
Pointer,
NonPointerTypes,
NullablePointer,
PointerCast,
PointerCastArray,
PointerCastFunction,
PointerCastInstance,
PointerCastObject,
} from "./types/pointer";
import type { AsLoaderRuntime } from "./types/runtime";
function instantiate<TModule>(
module: TModule | string,
load: (url: string) => Promise<unknown>,
imports?: Imports,
fallback?: false,
supports?: () => boolean
): Promise<WasmModuleInstance<TModule>>;
function instantiate<TModule>(
module: TModule | string,
load: (url: string) => Promise<unknown>,
imports: Imports | undefined,
fallback: true,
supports?: () => boolean
): Promise<ModuleInstance<TModule>>;
function instantiate<TModule>(
module: TModule | string,
load: (url: string) => Promise<unknown>,
imports?: Imports,
fallback?: boolean,
supports = () => typeof WebAssembly === "object"
): Promise<ModuleInstance<TModule>> {
if (supports()) {
// WebAssembly is supported
return asLoaderInstantiate<never>(
load(module as string),
imports || {}
).then(
(
result: ResultObject & {
exports: AsLoaderRuntime & PointerCastObject<TModule>;
}
) => ({
type: "wasm",
exports: result.exports,
instance: result.instance,
module: result.module,
})
);
} else if (fallback && (module as AsLoaderModule<TModule>).fallback) {
// eslint-disable-next-line
return (module as AsLoaderModule<TModule>).fallback!().then(
(exports: TModule) => ({
type: "js",
exports,
})
);
}
return Promise.reject(
new Error(
`Cannot load "${module}" module. WebAssembly is not supported in this environment.`
)
);
}
export {
instantiate,
// types
Imports,
WasmModuleInstance,
JsModuleInstance,
ModuleInstance,
AsLoaderModule,
// pointer types
Pointer,
NonPointerTypes,
NullablePointer,
PointerCast,
PointerCastArray,
PointerCastFunction,
PointerCastInstance,
PointerCastObject,
// runtime types
AsLoaderRuntime,
};