@steerprotocol/app-loader 0.2.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/Candle.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { RawTradeData } from './RawTradeData';
1
2
  export declare class Candle {
2
3
  timestamp: number;
3
4
  high: number;
@@ -10,3 +11,4 @@ export declare class Candle {
10
11
  }
11
12
  export declare function encodeCandle(candle: Candle): Uint32Array;
12
13
  export declare function decodeCandle(buffer: Uint32Array): Candle;
14
+ export declare function generateCandles(data: RawTradeData[], candleSize: string): Candle[];
package/lib/Candle.js CHANGED
@@ -1,6 +1,10 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decodeCandle = exports.encodeCandle = exports.Candle = void 0;
6
+ exports.generateCandles = exports.decodeCandle = exports.encodeCandle = exports.Candle = void 0;
7
+ const timestring_1 = __importDefault(require("timestring"));
4
8
  class Candle {
5
9
  constructor(timestamp, high, low, open, close, volume) {
6
10
  this.timestamp = timestamp;
@@ -30,3 +34,53 @@ function decodeCandle(buffer) {
30
34
  return new Candle(buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
31
35
  }
32
36
  exports.decodeCandle = decodeCandle;
37
+ function generateCandles(data, candleSize) {
38
+ const candleWidth = (0, timestring_1.default)(candleSize, 'ms', {});
39
+ if (data.length === 0) {
40
+ throw new Error('Input data is empty');
41
+ }
42
+ const _data = data.map((point) => {
43
+ return Object.assign(Object.assign({}, point), {
44
+ // This will convert the timestamp to milliseconds if it's in seconds
45
+ timestamp: point.timestamp && String(point.timestamp).length == 10 ? point.timestamp * 1000 : point.timestamp,
46
+ });
47
+ });
48
+ if (_data[0] === undefined || Object.keys(_data[0]).length === 0) {
49
+ return [];
50
+ }
51
+ const ohlcvData = [];
52
+ let i = 0;
53
+ let currentTimestamp = Math.floor(_data[0].timestamp / candleWidth) * candleWidth;
54
+ let open = _data[0].price;
55
+ let high = _data[0].price;
56
+ let low = _data[0].price;
57
+ let close = _data[0].price;
58
+ let volume = 0.0;
59
+ while (i < _data.length) {
60
+ open = close;
61
+ high = close;
62
+ low = close;
63
+ volume = 0.0;
64
+ let innerI = i;
65
+ while (innerI < _data.length && _data[innerI].timestamp < currentTimestamp + candleWidth) {
66
+ open = innerI === 0 ? _data[innerI].price : open;
67
+ high = Math.max(high, _data[innerI].price);
68
+ low = Math.min(low, _data[innerI].price);
69
+ close = _data[innerI].price;
70
+ volume += _data[innerI].volume;
71
+ innerI++;
72
+ }
73
+ ohlcvData.push({
74
+ timestamp: currentTimestamp,
75
+ high,
76
+ low,
77
+ open,
78
+ close,
79
+ volume,
80
+ });
81
+ currentTimestamp += candleWidth;
82
+ i = innerI;
83
+ }
84
+ return ohlcvData;
85
+ }
86
+ exports.generateCandles = generateCandles;
@@ -0,0 +1,22 @@
1
+ declare function responseHandler(body: ArrayBuffer, statusCode: number, redirected: number, callbackID: number): void;
2
+ declare function initialize(config: string): void;
3
+ declare function config(): string;
4
+ declare function version(): string;
5
+ declare function transform(): string;
6
+ declare function execute(...params: number[] | string[] | ArrayBuffer[] | null[]): string;
7
+ declare function __new(size: number, id: number): number;
8
+ declare function __pin(ptr: number): number;
9
+ declare function __unpin(ptr: number): number;
10
+ export type WasmModule = {
11
+ responseHandler: typeof responseHandler;
12
+ initialize: typeof initialize;
13
+ execute: typeof execute;
14
+ config: typeof config;
15
+ version: typeof version;
16
+ transform: typeof transform;
17
+ memory: WebAssembly.Memory;
18
+ __new: typeof __new;
19
+ __pin: typeof __pin;
20
+ __unpin: typeof __unpin;
21
+ };
22
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/lib/index.d.ts CHANGED
@@ -1,19 +1,12 @@
1
1
  import { Candle } from './Candle';
2
2
  import { RawTradeData } from './RawTradeData';
3
- export { Candle, RawTradeData };
4
- declare function responseHandler(body: ArrayBuffer, statusCode: number, redirected: number, callbackID: number): void;
5
- declare function initialize(config: string): void;
6
- declare function config(): string;
7
- declare function version(): string;
8
- declare function transform(): string;
9
- declare function execute(...params: string[]): string;
10
- export type WasmModule = {
11
- responseHandler: typeof responseHandler;
12
- initialize: typeof initialize;
13
- execute: typeof execute;
14
- config: typeof config;
15
- version: typeof version;
16
- transform: typeof transform;
17
- memory: WebAssembly.Memory;
18
- };
19
- export declare const loadWasm: (input: string | ArrayBuffer, imports?: {}) => Promise<WasmModule>;
3
+ import { WasmModule } from './WasmModule';
4
+ export { Candle, RawTradeData, WasmModule };
5
+ /**
6
+ * Load a wasm bundle synchronously. Only accepts the actual binary data.
7
+ * @param input - Wasm bundle data
8
+ * @param imports - Imports
9
+ * @returns
10
+ */
11
+ export declare function loadWasmSync(input: ArrayBuffer, imports?: {}): WasmModule;
12
+ export declare function loadWasm(input: string | ArrayBuffer, imports?: {}): Promise<WasmModule>;
package/lib/index.js CHANGED
@@ -35,429 +35,458 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
35
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
36
  };
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.loadWasm = exports.RawTradeData = exports.Candle = void 0;
38
+ exports.loadWasm = exports.loadWasmSync = exports.RawTradeData = exports.Candle = void 0;
39
39
  /* eslint-disable @typescript-eslint/ban-ts-comment */
40
40
  const ccxt_1 = __importDefault(require("ccxt"));
41
- const timestring_1 = __importDefault(require("timestring"));
42
41
  const Candle_1 = require("./Candle");
43
42
  Object.defineProperty(exports, "Candle", { enumerable: true, get: function () { return Candle_1.Candle; } });
44
43
  const RawTradeData_1 = require("./RawTradeData");
45
44
  Object.defineProperty(exports, "RawTradeData", { enumerable: true, get: function () { return RawTradeData_1.RawTradeData; } });
45
+ const ARRAYBUFFER_ID = 1;
46
+ const STRING_ID = 2;
47
+ // Pointers (for asyncify)
46
48
  let _fetchGETSyncPtr = 0;
47
49
  let _fetchPOSTSyncPtr = 0;
48
50
  let _ohlcvPtr = 0;
51
+ // Globals
52
+ let WASM_MEMORY;
53
+ let WASM_EXPORTS;
54
+ let WASM_DV;
55
+ // Constants required by Asyncify
49
56
  let ASYNCIFY_PTR = 0;
50
57
  let ASYNCIFY_MEM;
51
58
  let ASYNCIFY_INITIALIZED = false;
52
- let _exports;
53
- function instantiate(module, imports = {}) {
59
+ /**
60
+ * Load a wasm bundle synchronously. Only accepts the actual binary data.
61
+ * @param input - Wasm bundle data
62
+ * @param imports - Imports
63
+ * @returns
64
+ */
65
+ function loadWasmSync(input, imports = {}) {
66
+ return instantiate(new WebAssembly.Module(input), imports);
67
+ }
68
+ exports.loadWasmSync = loadWasmSync;
69
+ function loadWasm(input, imports = {}) {
54
70
  return __awaiter(this, void 0, void 0, function* () {
55
- const adaptedImports = {
56
- // @ts-ignore
57
- env: Object.assign(Object.create(globalThis), imports.env || {}, {
58
- _initAsyncify(frame_ptr, stack_ptr) {
59
- if (ASYNCIFY_INITIALIZED)
60
- return;
61
- ASYNCIFY_PTR = frame_ptr;
62
- ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
63
- // I don't know if I need to reserve all this memory...
64
- ASYNCIFY_MEM[ASYNCIFY_PTR + 4 >> 2] = stack_ptr;
65
- ASYNCIFY_INITIALIZED = true;
66
- },
67
- abort(message, fileName, lineNumber, columnNumber) {
68
- (() => {
69
- throw Error(`${__liftString(message)} in ${__liftString(fileName)}:${lineNumber}:${columnNumber}`);
70
- })();
71
- },
72
- generateCandles(data, candleSize) {
73
- const _data = __liftString(data) || '[]';
74
- const _candleSize = __liftString(candleSize) || '69m';
75
- const candles = generateCandles(JSON.parse(_data), _candleSize);
76
- return __lowerString(JSON.stringify(candles));
77
- },
78
- 'console.log': (text) => {
79
- console.log(__liftString(text));
80
- },
81
- ccxt_fetchOHLCV: (exchangeId, symbol, timeframe, limit, since) => {
82
- // Since may need to be passed as 64-bit?
83
- // Timestamps are large
71
+ const mod = instantiate(yield (() => __awaiter(this, void 0, void 0, function* () {
72
+ if (typeof input === 'string') {
73
+ try {
74
+ return yield WebAssembly.compileStreaming(fetch(input));
75
+ }
76
+ catch (_a) {
77
+ return WebAssembly.compile(yield (yield Promise.resolve().then(() => __importStar(require('fs/promises')))).readFile(input));
78
+ }
79
+ }
80
+ else {
81
+ return WebAssembly.compile(input);
82
+ }
83
+ }))(), imports);
84
+ return mod;
85
+ });
86
+ }
87
+ exports.loadWasm = loadWasm;
88
+ function instantiate(module, imports = {}) {
89
+ const adaptedImports = Object.assign({
90
+ console: {
91
+ log(text) {
92
+ console.log(__liftString(text));
93
+ },
94
+ },
95
+ // @ts-ignore
96
+ env: {
97
+ abort(message, fileName, lineNumber, columnNumber) {
98
+ (() => {
99
+ throw Error(`${__liftString(message)} in ${__liftString(fileName)}:${lineNumber}:${columnNumber}`);
100
+ })();
101
+ },
102
+ _initAsyncify(frame_ptr, stack_ptr) {
103
+ // @ts-ignore
104
+ if (!WASM_EXPORTS['asyncify_get_state'])
105
+ throw new Error('Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!');
106
+ if (ASYNCIFY_INITIALIZED)
107
+ return;
108
+ ASYNCIFY_PTR = frame_ptr;
109
+ ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
110
+ // I don't know if I need to reserve all this memory...
111
+ ASYNCIFY_MEM[(ASYNCIFY_PTR + 4) >> 2] = stack_ptr;
112
+ ASYNCIFY_INITIALIZED = true;
113
+ },
114
+ generateCandles(data, candleSize) {
115
+ const _data = __liftString(data) || '[]';
116
+ const _candleSize = __liftString(candleSize) || '69m';
117
+ const candles = (0, Candle_1.generateCandles)(JSON.parse(_data), _candleSize);
118
+ return __lowerString(JSON.stringify(candles));
119
+ },
120
+ 'console.log': (text) => {
121
+ console.log(__liftString(text));
122
+ },
123
+ ccxt_fetchOHLCV: (exchangeId, symbol, timeframe, limit, since) => {
124
+ // Since may need to be passed as 64-bit?
125
+ // Timestamps are large
126
+ // @ts-ignore
127
+ const currentState = WASM_EXPORTS.asyncify_get_state();
128
+ if (currentState === 2) {
129
+ //console.log("asyncify_stop_rewind() [resume wasm]");
84
130
  // @ts-ignore
85
- const currentState = _exports.asyncify_get_state();
86
- if (currentState === 2) {
87
- //console.log("asyncify_stop_rewind() [resume wasm]");
88
- // @ts-ignore
89
- _exports.asyncify_stop_rewind();
90
- return _ohlcvPtr;
91
- }
92
- else if (currentState === 0) {
93
- //console.log("asyncify_start_unwind() [pause wasm]");
131
+ WASM_EXPORTS.asyncify_stop_rewind();
132
+ return _ohlcvPtr;
133
+ }
134
+ else if (currentState === 0) {
135
+ //console.log("asyncify_start_unwind() [pause wasm]");
136
+ // @ts-ignore
137
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
138
+ // How about we pass an Enum back and forth?
139
+ const _exchange = __liftString(exchangeId);
140
+ const _symbol = __liftString(symbol);
141
+ const _timeframe = __liftString(timeframe);
142
+ if (!_exchange || !_symbol || !_timeframe)
143
+ throw new Error('Exchange, Symbol, or Timeframe not provided when fetching OHCLV data.');
144
+ // @ts-ignore
145
+ new ccxt_1.default[_exchange]({
146
+ apiKey: '',
147
+ secret: '',
148
+ })
149
+ .fetchOHLCV(_symbol, _timeframe, since, limit)
150
+ .then((data) => {
151
+ //console.log("asyncify_stop_unwind() [unpause wasm]");
94
152
  // @ts-ignore
95
- _exports.asyncify_start_unwind(ASYNCIFY_PTR);
96
- // How about we pass an Enum back and forth?
97
- const _exchange = __liftString(exchangeId);
98
- const _symbol = __liftString(symbol);
99
- const _timeframe = __liftString(timeframe);
100
- if (!_exchange || !_symbol || !_timeframe)
101
- throw new Error("Exchange, Symbol, or Timeframe not provided when fetching OHCLV data.");
153
+ WASM_EXPORTS.asyncify_stop_unwind();
154
+ // @ts-ignore: __new is defined
155
+ _ohlcvPtr = __lowerStaticArray((pointer, value) => {
156
+ __setU32(pointer, __lowerStaticArray(__setF64, 7, 3, value, Float64Array));
157
+ }, 8, 2, data);
158
+ //console.log("asyncify_start_rewind() [resuming wasm]");
102
159
  // @ts-ignore
103
- new ccxt_1.default[_exchange]({
104
- apiKey: "",
105
- secret: ""
106
- }).fetchOHLCV(_symbol, _timeframe, since, limit).then((data) => {
107
- //console.log("asyncify_stop_unwind() [unpause wasm]");
108
- // @ts-ignore
109
- _exports.asyncify_stop_unwind();
110
- // @ts-ignore: __new is defined
111
- _ohlcvPtr = __lowerStaticArray((pointer, value) => { __setU32(pointer, __lowerStaticArray(__setF64, 7, 3, value, Float64Array)); }, 8, 2, data);
112
- //console.log("asyncify_start_rewind() [resuming wasm]");
113
- // @ts-ignore
114
- _exports.asyncify_start_rewind(ASYNCIFY_PTR);
115
- _exports.execute();
116
- });
117
- }
118
- }
119
- }),
120
- console: {
121
- log: (msg) => {
122
- console.log(__liftString(msg >>> 0));
160
+ WASM_EXPORTS.asyncify_start_rewind(ASYNCIFY_PTR);
161
+ WASM_EXPORTS.execute();
162
+ });
123
163
  }
124
164
  },
125
- 'as-fetch': {
126
- _initAsyncify(frame_ptr, stack_ptr) {
127
- if (ASYNCIFY_INITIALIZED)
128
- return;
129
- ASYNCIFY_PTR = frame_ptr;
130
- ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
131
- // I don't know if I need to reserve all this memory...
132
- ASYNCIFY_MEM[ASYNCIFY_PTR + 4 >> 2] = stack_ptr;
133
- ASYNCIFY_INITIALIZED = true;
134
- },
135
- _fetchPOSTSync(url, mode, headers, body) {
136
- var _a;
165
+ },
166
+ 'as-fetch': {
167
+ _initAsyncify(frame_ptr, stack_ptr) {
168
+ // @ts-ignore
169
+ if (!WASM_EXPORTS['asyncify_get_state'])
170
+ throw new Error('Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!');
171
+ if (ASYNCIFY_INITIALIZED)
172
+ return;
173
+ ASYNCIFY_PTR = frame_ptr;
174
+ ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
175
+ // I don't know if I need to reserve all this memory...
176
+ ASYNCIFY_MEM[(ASYNCIFY_PTR + 4) >> 2] = stack_ptr;
177
+ ASYNCIFY_INITIALIZED = true;
178
+ },
179
+ _fetchPOSTSync(url, mode, headers, body) {
180
+ var _a;
181
+ // @ts-ignore
182
+ const currentState = WASM_EXPORTS.asyncify_get_state();
183
+ if (currentState === 2) {
184
+ //console.log("asyncify_stop_rewind() [resume wasm]");
137
185
  // @ts-ignore
138
- const currentState = _exports.asyncify_get_state();
139
- if (currentState === 2) {
140
- //console.log("asyncify_stop_rewind() [resume wasm]");
186
+ WASM_EXPORTS.asyncify_stop_rewind();
187
+ const ptr = _fetchPOSTSyncPtr;
188
+ _fetchPOSTSyncPtr = 0;
189
+ return ptr;
190
+ }
191
+ else if (currentState === 0) {
192
+ //console.log("asyncify_start_unwind() [pause wasm]");
193
+ // @ts-ignore
194
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
195
+ fetch((_a = __liftString(url)) !== null && _a !== void 0 ? _a : '', {
196
+ method: 'POST',
197
+ mode: modeToString(mode) || 'cors',
198
+ headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
199
+ body: __liftBuffer(body),
200
+ }).then((res) => __awaiter(this, void 0, void 0, function* () {
201
+ const value = yield res.arrayBuffer();
202
+ //console.log("asyncify_stop_unwind() [unpause wasm]");
141
203
  // @ts-ignore
142
- _exports.asyncify_stop_rewind();
143
- return _fetchPOSTSyncPtr;
144
- }
145
- else if (currentState === 0) {
146
- //console.log("asyncify_start_unwind() [pause wasm]");
204
+ WASM_EXPORTS.asyncify_stop_unwind();
147
205
  // @ts-ignore
148
- _exports.asyncify_start_unwind(ASYNCIFY_PTR);
149
- fetch((_a = __liftString(url)) !== null && _a !== void 0 ? _a : '', {
150
- method: "POST",
151
- mode: modeToString(mode) || "cors",
152
- headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
153
- body: __liftBuffer(body)
154
- }).then((res) => __awaiter(this, void 0, void 0, function* () {
155
- //console.log("asyncify_stop_unwind() [unpause wasm]");
156
- // @ts-ignore
157
- _exports.asyncify_stop_unwind();
158
- const value = yield res.arrayBuffer();
159
- // @ts-ignore
160
- _fetchPOSTSyncPtr = _exports.__new(value.byteLength, 1);
161
- new Uint8Array(_exports.memory.buffer).set(new Uint8Array(value), _fetchPOSTSyncPtr);
162
- //console.log("asyncify_start_rewind() [resuming wasm]");
163
- // @ts-ignore
164
- _exports.asyncify_start_rewind(ASYNCIFY_PTR);
165
- // @ts-ignore
166
- // Set to your execute function that your fetch calls are in. I would go and create a _start func
167
- _exports.execute();
168
- }));
169
- }
170
- },
171
- _fetchGETSync(url, mode, headers) {
172
- // @ts-ignore
173
- const currentState = _exports.asyncify_get_state();
174
- if (currentState === 2) {
206
+ _fetchPOSTSyncPtr = __lowerBuffer(value);
207
+ //wasm_exports.__new(value.byteLength, 1);
208
+ //new Uint8Array(wasm_exports.memory.buffer).set(new Uint8Array(value), _fetchPOSTSyncPtr);
209
+ //console.log("asyncify_start_rewind() [resuming wasm]");
175
210
  // @ts-ignore
176
- //console.log("asyncify_stop_rewind() [resume wasm]");
177
- _exports.asyncify_stop_rewind();
178
- return _fetchGETSyncPtr;
179
- }
180
- else if (currentState === 0) {
211
+ WASM_EXPORTS.asyncify_start_rewind(ASYNCIFY_PTR);
181
212
  // @ts-ignore
182
- //console.log("asyncify_start_unwind() [pause wasm]");
183
- _exports.asyncify_start_unwind(ASYNCIFY_PTR);
184
- fetch(__liftString(url) || "", {
185
- method: "GET",
186
- mode: modeToString(mode) || "cors",
187
- headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || []
188
- }).then((res) => __awaiter(this, void 0, void 0, function* () {
189
- // @ts-ignore
190
- //console.log("asyncify_stop_unwind() [unpause wasm]");
191
- _exports.asyncify_stop_unwind();
192
- const value = yield res.arrayBuffer();
193
- // @ts-ignore
194
- _fetchGETSyncPtr = _exports.__new(value.byteLength, 1);
195
- new Uint8Array(_exports.memory.buffer).set(new Uint8Array(value), _fetchGETSyncPtr);
196
- // @ts-ignore
197
- //console.log("asyncify_start_rewind() [resuming wasm]");
198
- _exports.asyncify_start_rewind(ASYNCIFY_PTR);
199
- // @ts-ignore
200
- _exports.execute();
201
- }));
202
- }
203
- },
204
- _fetchGET(url, mode, headers, callbackID) {
205
- fetch(__liftString(url) || "", {
206
- method: "GET",
207
- mode: modeToString(mode) || "cors",
208
- headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || []
209
- }).then((res) => __awaiter(this, void 0, void 0, function* () {
210
- const body = yield res.arrayBuffer();
211
- _exports.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);
212
- }));
213
- },
214
- _fetchPOST(url, mode, headers, body, callbackID) {
215
- fetch(__liftString(url) || "", {
216
- method: "POST",
217
- mode: modeToString(mode) || "cors",
218
- body: body,
219
- headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
220
- }).then((res) => __awaiter(this, void 0, void 0, function* () {
221
- const body = yield res.arrayBuffer();
222
- _exports.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);
213
+ // Set to your execute function that your fetch calls are in. I would go and create a _start func
214
+ WASM_EXPORTS.execute();
223
215
  }));
224
216
  }
225
217
  },
226
- };
227
- //@ts-ignore
228
- const { exports } = yield WebAssembly.instantiate(module, adaptedImports);
229
- // @ts-ignore
230
- const memory = exports.memory || imports.env.memory;
231
- _exports = exports;
232
- ASYNCIFY_MEM = new Uint32Array(memory.buffer);
233
- const adaptedExports = Object.setPrototypeOf({
234
- responseHandler(body, statusCode, redirected, callbackID) {
235
- if (exports['responseHandler']) {
236
- exports.responseHandler(__lowerBuffer(body), statusCode, redirected ? 1 : 0, callbackID);
218
+ _fetchGETSync(url, mode, headers) {
219
+ // @ts-ignore
220
+ const currentState = WASM_EXPORTS.asyncify_get_state();
221
+ if (currentState === 2) {
222
+ // @ts-ignore
223
+ //console.log("asyncify_stop_rewind() [resume wasm]");
224
+ WASM_EXPORTS.asyncify_stop_rewind();
225
+ const ptr = _fetchGETSyncPtr;
226
+ _fetchGETSyncPtr = 0;
227
+ return ptr;
237
228
  }
238
- },
239
- initialize(config) {
240
- exports.initialize(__lowerString(config));
241
- },
242
- execute(...params) {
243
- const loweredArgs = new Array(params.length);
244
- for (let i = 0; i < params.length; i++) {
245
- loweredArgs[i] = __lowerString(params[i]);
229
+ else if (currentState === 0) {
230
+ // @ts-ignore
231
+ //console.log("asyncify_start_unwind() [pause wasm]");
232
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
233
+ fetch(__liftString(url) || '', {
234
+ method: 'GET',
235
+ mode: modeToString(mode) || 'cors',
236
+ headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
237
+ }).then((res) => __awaiter(this, void 0, void 0, function* () {
238
+ const value = yield res.arrayBuffer();
239
+ // @ts-ignore
240
+ //console.log("asyncify_stop_unwind() [unpause wasm]");
241
+ WASM_EXPORTS.asyncify_stop_unwind();
242
+ // @ts-ignore
243
+ _fetchGETSyncPtr = __lowerBuffer(value);
244
+ // @ts-ignore
245
+ //console.log("asyncify_start_rewind() [resuming wasm]");
246
+ WASM_EXPORTS.asyncify_start_rewind(ASYNCIFY_PTR);
247
+ // @ts-ignore
248
+ WASM_EXPORTS.execute();
249
+ }));
246
250
  }
247
- return __liftString(exports.execute(...loweredArgs));
248
251
  },
249
- config() {
250
- return __liftString(exports.config());
252
+ _fetchGET(url, mode, headers, callbackID) {
253
+ fetch(__liftString(url) || '', {
254
+ method: 'GET',
255
+ mode: modeToString(mode) || 'cors',
256
+ headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
257
+ }).then((res) => __awaiter(this, void 0, void 0, function* () {
258
+ const body = yield res.arrayBuffer();
259
+ WASM_EXPORTS.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);
260
+ }));
251
261
  },
252
- transform() {
253
- try {
254
- return __liftString(exports.transform());
255
- }
256
- catch (e) {
257
- console.error(e);
258
- throw new Error('Unable to call .transform on wasm module. Are you sure this is a data connector?');
259
- }
262
+ _fetchPOST(url, mode, headers, body, callbackID) {
263
+ fetch(__liftString(url) || '', {
264
+ method: 'POST',
265
+ mode: modeToString(mode) || 'cors',
266
+ body: body,
267
+ headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
268
+ }).then((res) => __awaiter(this, void 0, void 0, function* () {
269
+ const body = yield res.arrayBuffer();
270
+ WASM_EXPORTS.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);
271
+ }));
260
272
  },
261
- }, exports);
262
- let __dataview = new DataView(memory.buffer);
263
- function __liftArray(liftElement, align, pointer) {
264
- if (!pointer)
265
- return null;
266
- const dataStart = __getU32(pointer + 4), length = __dataview.getUint32(pointer + 12, true), values = new Array(length);
267
- for (let i = 0; i < length; ++i)
268
- values[i] = liftElement(dataStart + (i << align));
269
- return values;
270
- }
271
- function __lowerArray(lowerElement, id, align, values) {
272
- if (values == null)
273
- return 0;
274
- const length = values.length,
275
- // @ts-ignore
276
- buffer = __retain(exports.__new(length << align, 1)),
277
- // @ts-ignore
278
- header = __retain(exports.__new(16, id));
279
- __setU32(header + 0, buffer);
280
- __dataview.setUint32(header + 4, buffer, true);
281
- __dataview.setUint32(header + 8, length << align, true);
282
- __dataview.setUint32(header + 12, length, true);
283
- for (let i = 0; i < length; ++i)
284
- lowerElement(buffer + (i << align), values[i]);
285
- // @ts-ignore
286
- //exports.__unpin(buffer);
287
- // @ts-ignore
288
- //exports.__unpin(header);
289
- return header;
290
- }
291
- function __lowerStaticArray(lowerElement, id, align, values, typedConstructor) {
292
- if (values == null)
293
- return 0;
294
- const length = values.length,
295
- // @ts-ignore: __pin and __new are defined
296
- buffer = _exports.__pin(_exports.__new(length << align, id)) >>> 0;
297
- if (typedConstructor) {
298
- new typedConstructor(_exports.memory.buffer, buffer, length).set(values);
299
- }
300
- else {
301
- for (let i = 0; i < length; i++)
302
- lowerElement(buffer + (i << align >>> 0), values[i]);
303
- }
304
- // @ts-ignore: __unpin is defined
305
- _exports.__unpin(buffer);
306
- return buffer;
307
- }
308
- function __setF64(pointer, value) {
273
+ },
274
+ }, imports);
275
+ const mod = new WebAssembly.Instance(module, adaptedImports);
276
+ WASM_EXPORTS = mod.exports;
277
+ // @ts-ignore
278
+ WASM_MEMORY = WASM_EXPORTS.memory || adaptedImports.env.memory;
279
+ ASYNCIFY_MEM = new Uint32Array(WASM_MEMORY.buffer);
280
+ const handledExports = Object.setPrototypeOf({
281
+ responseHandler(body, statusCode, redirected, callbackID) {
309
282
  try {
310
- __dataview.setFloat64(pointer, value, true);
283
+ // @ts-ignore
284
+ WASM_EXPORTS.responseHandler(__lowerBuffer(body), statusCode, redirected ? 1 : 0, callbackID);
311
285
  }
312
- catch (_a) {
313
- __dataview = new DataView(memory.buffer);
314
- __dataview.setFloat64(pointer, value, true);
286
+ catch (e) {
287
+ console.error(e);
288
+ throw new Error('Unable to call .responseHandler on wasm module. Add the line export { responseHandler } from "as-fetch/assembly" to your entry file.');
315
289
  }
316
- }
317
- function __liftBuffer(pointer) {
318
- if (!pointer)
319
- return null;
320
- return memory.buffer.slice(pointer, pointer + new Uint32Array(memory.buffer)[(pointer - 4) >>> 2]);
321
- }
322
- function __lowerBuffer(value) {
323
- if (value == null)
324
- return 0;
325
- // @ts-ignore
326
- const pointer = exports.__new(value.byteLength, 1);
327
- new Uint8Array(memory.buffer).set(new Uint8Array(value), pointer);
328
- return pointer;
329
- }
330
- function __liftString(pointer) {
331
- if (!pointer)
332
- return null;
333
- const end = (pointer + new Uint32Array(memory.buffer)[(pointer - 4) >>> 2]) >>> 1, memoryU16 = new Uint16Array(memory.buffer);
334
- let start = pointer >>> 1, string = '';
335
- while (end - start > 1024)
336
- string += String.fromCharCode(...memoryU16.subarray(start, (start += 1024)));
337
- return string + String.fromCharCode(...memoryU16.subarray(start, end));
338
- }
339
- function __lowerString(value) {
340
- if (value === null)
341
- return 0;
342
- const length = value.length;
290
+ },
291
+ initialize(config) {
343
292
  // @ts-ignore
344
- const pointer = exports.__new(length << 1, 2);
345
- const memoryU16 = new Uint16Array(memory.buffer);
346
- for (let i = 0; i < length; ++i)
347
- memoryU16[(pointer >>> 1) + i] = value.charCodeAt(i);
348
- return pointer;
349
- }
350
- function __getU32(pointer) {
351
- try {
352
- return __dataview.getUint32(pointer, true);
293
+ WASM_EXPORTS.initialize(__lowerString(config));
294
+ },
295
+ execute(...params) {
296
+ const loweredArgs = new Array(params.length);
297
+ for (let i = 0; i < params.length; i++) {
298
+ loweredArgs[i] = __lowerRetained(params[i]);
353
299
  }
354
- catch (_a) {
355
- __dataview = new DataView(memory.buffer);
356
- return __dataview.getUint32(pointer, true);
300
+ for (let i = 0; i < loweredArgs.length; i++) {
301
+ if (typeof params[i] !== 'number')
302
+ __release(loweredArgs[i]);
357
303
  }
358
- }
359
- function __setU32(pointer, value) {
304
+ // @ts-ignore
305
+ return __liftString(WASM_EXPORTS.execute(...loweredArgs));
306
+ },
307
+ config() {
308
+ return __liftString(WASM_EXPORTS.config());
309
+ },
310
+ transform() {
360
311
  try {
361
- __dataview.setUint32(pointer, value, true);
362
- }
363
- catch (_a) {
364
- __dataview = new DataView(memory.buffer);
365
- __dataview.setUint32(pointer, value, true);
366
- }
367
- }
368
- const refcounts = new Map();
369
- function __retain(pointer) {
370
- if (pointer) {
371
- const refcount = refcounts.get(pointer);
372
- if (refcount)
373
- refcounts.set(pointer, refcount + 1);
374
- // @ts-ignore: __pin is defined
375
- else
376
- refcounts.set(exports.__pin(pointer), 1);
377
- }
378
- return pointer;
379
- }
380
- function __release(pointer) {
381
- if (pointer) {
382
- const refcount = refcounts.get(pointer);
383
- // @ts-ignore: __unpin is defined
384
- if (refcount === 1)
385
- exports.__unpin(pointer), refcounts.delete(pointer);
386
- else if (refcount)
387
- refcounts.set(pointer, refcount - 1);
388
- else
389
- throw Error(`invalid refcount '${refcount}' for reference '${pointer}'`);
390
- }
391
- }
392
- function generateCandles(data, candleSize) {
393
- const candleWidth = (0, timestring_1.default)(candleSize, 'ms', {});
394
- if (data.length === 0) {
395
- throw new Error('Input data is empty');
396
- }
397
- const _data = data.map((point) => {
398
- return Object.assign(Object.assign({}, point), {
399
- // This will convert the timestamp to milliseconds if it's in seconds
400
- timestamp: point.timestamp && String(point.timestamp).length == 10 ? point.timestamp * 1000 : point.timestamp,
401
- });
402
- });
403
- if (_data[0] === undefined || Object.keys(_data[0]).length === 0) {
404
- return [];
312
+ return __liftString(WASM_EXPORTS.transform());
405
313
  }
406
- const ohlcvData = [];
407
- let i = 0;
408
- let currentTimestamp = Math.floor(_data[0].timestamp / candleWidth) * candleWidth;
409
- let open = _data[0].price;
410
- let high = _data[0].price;
411
- let low = _data[0].price;
412
- let close = _data[0].price;
413
- let volume = 0.0;
414
- while (i < _data.length) {
415
- open = close;
416
- high = close;
417
- low = close;
418
- volume = 0.0;
419
- let innerI = i;
420
- while (innerI < _data.length && _data[innerI].timestamp < currentTimestamp + candleWidth) {
421
- open = innerI === 0 ? _data[innerI].price : open;
422
- high = Math.max(high, _data[innerI].price);
423
- low = Math.min(low, _data[innerI].price);
424
- close = _data[innerI].price;
425
- volume += _data[innerI].volume;
426
- innerI++;
427
- }
428
- ohlcvData.push({
429
- timestamp: currentTimestamp,
430
- high,
431
- low,
432
- open,
433
- close,
434
- volume,
435
- });
436
- currentTimestamp += candleWidth;
437
- i = innerI;
314
+ catch (e) {
315
+ console.error(e);
316
+ throw new Error('Unable to call .transform on wasm module. Are you sure this is a data connector?');
438
317
  }
439
- return ohlcvData;
440
- }
441
- return adaptedExports;
442
- });
318
+ },
319
+ }, WASM_EXPORTS);
320
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
321
+ return handledExports;
322
+ }
323
+ const refcounts = new Map();
324
+ function __retain(ptr) {
325
+ if (ptr) {
326
+ const refcount = refcounts.get(ptr);
327
+ if (refcount)
328
+ refcounts.set(ptr, refcount + 1);
329
+ else
330
+ refcounts.set(WASM_EXPORTS.__pin(ptr), 1);
331
+ }
332
+ return ptr;
333
+ }
334
+ function __release(ptr) {
335
+ if (ptr) {
336
+ const refcount = refcounts.get(ptr);
337
+ if (refcount === 1)
338
+ WASM_EXPORTS.__unpin(ptr), refcounts.delete(ptr);
339
+ else if (refcount)
340
+ refcounts.set(ptr, refcount - 1);
341
+ else
342
+ throw Error(`invalid refcount '${refcount}' for reference '${ptr}'`);
343
+ }
344
+ }
345
+ function __lowerRetained(val) {
346
+ if (typeof val === 'number') {
347
+ return val;
348
+ }
349
+ else if (typeof val === 'string') {
350
+ return __lowerStringRetained(val);
351
+ }
352
+ else if (val instanceof ArrayBuffer) {
353
+ return __lowerBufferRetained(val);
354
+ }
355
+ else {
356
+ return 0;
357
+ }
358
+ }
359
+ function __liftString(ptr) {
360
+ if (!ptr)
361
+ return null;
362
+ const end = (ptr + new Uint32Array(WASM_MEMORY.buffer)[(ptr - 4) >>> 2]) >>> 1;
363
+ const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
364
+ let start = ptr >>> 1;
365
+ let str = '';
366
+ while (end - start > 1024)
367
+ str += String.fromCharCode(...memoryU16.subarray(start, (start += 1024)));
368
+ return str + String.fromCharCode(...memoryU16.subarray(start, end));
369
+ }
370
+ function __lowerString(str) {
371
+ if (str === null)
372
+ return 0;
373
+ const length = str.length;
374
+ // @ts-ignore
375
+ const ptr = WASM_EXPORTS.__new(length << 1, STRING_ID);
376
+ __retain(ptr);
377
+ const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
378
+ for (let i = 0; i < length; ++i)
379
+ memoryU16[(ptr >>> 1) + i] = str.charCodeAt(i);
380
+ return ptr;
381
+ }
382
+ function __lowerStringRetained(str) {
383
+ if (str === null)
384
+ return 0;
385
+ const length = str.length;
386
+ // @ts-ignore
387
+ const ptr = WASM_EXPORTS.__new(length << 1, STRING_ID);
388
+ __retain(ptr);
389
+ const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
390
+ for (let i = 0; i < length; ++i)
391
+ memoryU16[(ptr >>> 1) + i] = str.charCodeAt(i);
392
+ return ptr;
393
+ }
394
+ function __liftArray(liftElement, align, ptr) {
395
+ if (!ptr)
396
+ return null;
397
+ let dataStart;
398
+ try {
399
+ dataStart = WASM_DV.getUint32(ptr + 4, true);
400
+ }
401
+ catch (_a) {
402
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
403
+ dataStart = WASM_DV.getUint32(ptr + 4, true);
404
+ }
405
+ const length = WASM_DV.getUint32(ptr + 12, true);
406
+ const values = new Array(length);
407
+ for (let i = 0; i < length; ++i)
408
+ values[i] = liftElement(dataStart + ((i << align) >>> 0));
409
+ return values;
410
+ }
411
+ function __lowerArray(lowerElement, id, align, values) {
412
+ if (values == null)
413
+ return 0;
414
+ const length = values.length;
415
+ const buffer = WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << align, 1)) >>> 0;
416
+ const header = WASM_EXPORTS.__pin(WASM_EXPORTS.__new(16, id)) >>> 0;
417
+ WASM_DV.setUint32(header, buffer, true);
418
+ WASM_DV.setUint32(header + 4, buffer, true);
419
+ WASM_DV.setUint32(header + 8, length << align, true);
420
+ WASM_DV.setUint32(header + 12, length, true);
421
+ for (let i = 0; i < length; ++i)
422
+ lowerElement(buffer + ((i << align) >>> 0), values[i]);
423
+ WASM_EXPORTS.__unpin(buffer);
424
+ WASM_EXPORTS.__unpin(header);
425
+ return header;
426
+ }
427
+ function __liftBuffer(ptr) {
428
+ if (!ptr)
429
+ return null;
430
+ const len = new Uint32Array(WASM_MEMORY.buffer)[(ptr - 4) >>> 2];
431
+ return WASM_MEMORY.buffer.slice(ptr, ptr + len);
432
+ }
433
+ function __lowerBuffer(buf) {
434
+ if (buf == null)
435
+ return 0;
436
+ const ptr = WASM_EXPORTS.__new(buf.byteLength, ARRAYBUFFER_ID) >>> 0;
437
+ new Uint8Array(WASM_MEMORY.buffer).set(new Uint8Array(buf), ptr);
438
+ return ptr;
439
+ }
440
+ function __lowerBufferRetained(buf) {
441
+ if (buf == null)
442
+ return 0;
443
+ const ptr = WASM_EXPORTS.__new(buf.byteLength, ARRAYBUFFER_ID) >>> 0;
444
+ __retain(ptr);
445
+ new Uint8Array(WASM_MEMORY.buffer).set(new Uint8Array(buf), ptr);
446
+ return ptr;
447
+ }
448
+ function __lowerStaticArray(lowerElement, id, align, values, typedConstructor) {
449
+ if (values == null)
450
+ return 0;
451
+ const length = values.length;
452
+ const ptr = WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << align, id)) >>> 0;
453
+ if (typedConstructor) {
454
+ new typedConstructor(WASM_EXPORTS.memory.buffer, ptr, length).set(values);
455
+ }
456
+ else {
457
+ for (let i = 0; i < length; i++)
458
+ lowerElement(ptr + ((i << align) >>> 0), values[i]);
459
+ }
460
+ WASM_EXPORTS.__unpin(ptr);
461
+ return ptr;
462
+ }
463
+ function __setF64(ptr, val) {
464
+ try {
465
+ WASM_DV.setFloat64(ptr, val, true);
466
+ }
467
+ catch (_a) {
468
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
469
+ WASM_DV.setFloat64(ptr, val, true);
470
+ }
471
+ }
472
+ function __getU32(ptr) {
473
+ try {
474
+ return WASM_DV.getUint32(ptr, true);
475
+ }
476
+ catch (_a) {
477
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
478
+ return WASM_DV.getUint32(ptr, true);
479
+ }
480
+ }
481
+ function __setU32(ptr, val) {
482
+ try {
483
+ WASM_DV.setUint32(ptr, val, true);
484
+ }
485
+ catch (_a) {
486
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
487
+ WASM_DV.setUint32(ptr, val, true);
488
+ }
443
489
  }
444
- const loadWasm = (input, imports = {}) => __awaiter(void 0, void 0, void 0, function* () {
445
- const mod = (yield instantiate(yield (() => __awaiter(void 0, void 0, void 0, function* () {
446
- if (typeof input === 'string') {
447
- try {
448
- return yield globalThis.WebAssembly.compileStreaming(globalThis.fetch(input));
449
- }
450
- catch (_a) {
451
- return globalThis.WebAssembly.compile(yield (yield Promise.resolve().then(() => __importStar(require('fs/promises')))).readFile(input));
452
- }
453
- }
454
- else {
455
- return globalThis.WebAssembly.compile(input);
456
- }
457
- }))(), imports));
458
- return mod;
459
- });
460
- exports.loadWasm = loadWasm;
461
490
  function modeToString(mode) {
462
491
  if (mode == 1)
463
492
  return 'cors';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steerprotocol/app-loader",
3
- "version": "0.2.3",
3
+ "version": "1.0.0",
4
4
  "description": "App Loader for Steer Protocol",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",