forked from Echo-Mirror-Butler/echomirror-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathload.ts
More file actions
53 lines (45 loc) · 1.75 KB
/
Copy pathload.ts
File metadata and controls
53 lines (45 loc) · 1.75 KB
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
// Resolves to wasm-node/*.cjs under the "node" import condition and
// wasm-web/*.js under "browser" (see package.json#imports / "#wasm-binding").
// The nodejs target instantiates its wasm module synchronously at require
// time; the web target needs an explicit async `init()` call to fetch and
// instantiate it — `raw.default` only exists (as a function) on the web
// target, so we use its presence to decide whether there's anything to wait
// on.
import * as raw from '#wasm-binding'
let readyPromise: Promise<void> | null = null
/**
* Instantiate the wasm module. Required once, before any other call, when
* running in a browser (fetches and compiles the .wasm asset). A no-op in
* Node, where the module is already instantiated synchronously — safe to
* call unconditionally either way, and safe to call more than once.
*
* @example
* import { init, verifyMoodScore } from '@echomirror/wasm'
* await init()
* verifyMoodScore(7)
*/
export function init(): Promise<void> {
if (readyPromise) return readyPromise
const maybeInit = (raw as { default?: unknown }).default
readyPromise =
typeof maybeInit === 'function'
? Promise.resolve((maybeInit as () => unknown)()).then(() => undefined)
: Promise.resolve()
return readyPromise
}
/** True once `init()` has resolved. Wrapped calls throw a clear error before that. */
export function isReady(): boolean {
return readyPromise !== null
}
export function assertReady(fnName: string): void {
if (readyPromise === null) {
throw new WasmNotInitializedError(fnName)
}
}
export class WasmNotInitializedError extends Error {
constructor(fnName: string) {
super(`@echomirror/wasm: call init() before using ${fnName}()`)
this.name = 'WasmNotInitializedError'
}
}
export { raw }