aboutsummaryrefslogtreecommitdiff
path: root/src/api/demo/lib/api.ts
blob: d2e19218e76a527de784f17c271b98e434529ea9 (plain) (blame)
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import * as Schema from "../../schema";
import { ByteBuffer } from "peechy";
import { transform as sucraseTransform } from "sucrase";

export interface WebAssemblyModule {
  init(): number;
  transform(a: number): number;
  malloc(a: number): number;
  calloc(a: number): number;
  realloc(a: number): number;
  free(a: number): number;
  cycle(): void;
}

const wasm_imports_sym: symbol | string =
  process.env.NODE_ENV === "development"
    ? "wasm_imports"
    : Symbol("wasm_imports");

const ptr_converter = new ArrayBuffer(8);
const ptr_float = new Float64Array(ptr_converter);
const slice = new Uint32Array(ptr_converter);

var scratch: Uint8Array;

export class ESDev {
  static has_initialized = false;
  static wasm_source: WebAssembly.WebAssemblyInstantiatedSource = null;
  static get wasm_exports(): WebAssemblyModule {
    return ESDev.wasm_source.instance.exports as any;
  }
  static get memory() {
    return ESDev[wasm_imports_sym].memory as WebAssembly.Memory;
  }

  static memory_array: Uint8Array;

  static _decoder: TextDecoder;

  static _wasmPtrToSlice(offset: number) {
    if (ESDev.memory_array.buffer !== ESDev.memory.buffer) {
      ESDev.memory_array = new Uint8Array(ESDev.memory.buffer);
    }
    ptr_float[0] = offset;
    return ESDev.memory_array.subarray(slice[0], slice[0] + slice[1]);
  }

  static _wasmPtrLenToString(slice: number) {
    if (!ESDev._decoder) {
      ESDev._decoder = new TextDecoder("utf8");
    }

    const region = this._wasmPtrToSlice(slice);

    return ESDev._decoder.decode(region);
  }

  // We don't want people to be calling these manually
  static [wasm_imports_sym] = {
    console_log(slice: number) {
      console.log(ESDev._wasmPtrLenToString(slice));
    },
    console_error(slice: number) {
      console.error(ESDev._wasmPtrLenToString(slice));
    },
    console_warn(slice: number) {
      console.warn(ESDev._wasmPtrLenToString(slice));
    },
    console_info(slice: number) {
      console.info(ESDev._wasmPtrLenToString(slice));
    },
    memory: null,
    // __indirect_function_table: new WebAssembly.Table({
    //   initial: 0,
    //   element: "anyfunc",
    // }),
    // __stack_pointer: new WebAssembly.Global({
    //   mutable: true,
    //   value: "i32",
    // }),
    // __multi3(one: number, two: number) {
    //   return Math.imul(one | 0, two | 0);
    // },
    // fmod(one: number, two: number) {
    //   return one % two;
    // },
    // memset(ptr: number, value: number, len: number) {
    //   ESDev.memory_array.fill(value, ptr, ptr + len);
    // },
    // memcpy(ptr: number, value: number, len: number) {
    //   ESDev.memory_array.copyWithin(ptr, value, value + len);
    // },
    // // These functions convert a to an unsigned long long, rounding toward zero. Negative values all become zero.
    // __fixunsdfti(a: number) {
    //   return Math.floor(a);
    // },
    // // These functions return the remainder of the unsigned division of a and b.
    // __umodti3(a: number, b: number) {
    //   return (a | 0) % (b | 0);
    // },
    // // These functions return the quotient of the unsigned division of a and b.
    // __udivti3(a: number, b: number) {
    //   return (a | 0) / (b | 0);
    // },
    // // These functions return the result of shifting a left by b bits.
    // __ashlti3(a: number, b: number) {
    //   return (a | 0) >> (b | 0);
    // },
    // /* Returns: convert a to a double, rounding toward even. */
    // __floatuntidf(a: number) {
    //   const mod = a % 2;
    //   if (mod === 0) {
    //     return Math.ceil(a);
    //   } else if (mod === 1) {
    //     return Math.floor(a);
    //   }
    // },
  };

  static async init(url) {
    globalThis.sucraseTransform = sucraseTransform;
    scratch = new Uint8Array(8096);

    if (ESDev.has_initialized) {
      return;
    }

    ESDev[wasm_imports_sym].memory = new WebAssembly.Memory({
      initial: 18,
      // shared: typeof SharedArrayBuffer !== "undefined",
      maximum: typeof SharedArrayBuffer !== "undefined" ? 5000 : undefined,
    });

    ESDev.wasm_source = await globalThis.WebAssembly.instantiateStreaming(
      fetch(url),
      { env: ESDev[wasm_imports_sym] }
    );
    ESDev.memory_array = new Uint8Array(ESDev.memory.buffer);

    const res = ESDev.wasm_exports.init();
    if (res < 0) {
      throw `[ESDev] Failed to initialize WASM module: code ${res}`;
    } else {
      console.log("WASM loaded.");
    }

    ESDev.has_initialized = true;
  }

  static transform(content: Uint8Array, file_name: string) {
    if (!ESDev.has_initialized) {
      throw "Please run await ESDev.init(wasm_url) before using this.";
    }

    // if (process.env.NODE_ENV === "development") {
    //   console.time("[ESDev] Transform " + file_name);
    // }

    const bb = new ByteBuffer(scratch);
    bb.length = 0;

    Schema.encodeTransform(
      {
        contents: content,
        path: file_name,
      },
      bb
    );
    const data = bb.toUint8Array();
    if (bb._data.buffer !== scratch.buffer) {
      scratch = bb._data;
    }

    const ptr = ESDev.wasm_exports.malloc(data.byteLength);
    this._wasmPtrToSlice(ptr).set(data);
    const resp_ptr = ESDev.wasm_exports.transform(ptr);
    var _bb = new ByteBuffer(this._wasmPtrToSlice(resp_ptr));
    const response = Schema.decodeTransformResponse(_bb);
    ESDev.wasm_exports.cycle();
    return response;
  }
}

globalThis.ESDev = ESDev;