@steerprotocol/app-loader 2.1.0 → 3.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/index.cjs ADDED
@@ -0,0 +1,623 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ Candle: () => Candle,
24
+ RawTradeData: () => RawTradeData,
25
+ loadWasm: () => loadWasm,
26
+ loadWasmSync: () => loadWasmSync
27
+ });
28
+ module.exports = __toCommonJS(src_exports);
29
+
30
+ // src/internal/instantiate.ts
31
+ var import_ethers = require("ethers");
32
+
33
+ // src/timestring.ts
34
+ var DEFAULT_OPTS = {
35
+ hoursPerDay: 24,
36
+ daysPerWeek: 7,
37
+ weeksPerMonth: 4,
38
+ monthsPerYear: 12,
39
+ daysPerYear: 365.25
40
+ };
41
+ var UNIT_MAP = {
42
+ ms: ["ms", "milli", "millisecond", "milliseconds"],
43
+ s: ["s", "sec", "secs", "second", "seconds"],
44
+ m: ["m", "min", "mins", "minute", "minutes"],
45
+ h: ["h", "hr", "hrs", "hour", "hours"],
46
+ d: ["d", "day", "days"],
47
+ w: ["w", "week", "weeks"],
48
+ mth: ["mon", "mth", "mths", "month", "months"],
49
+ y: ["y", "yr", "yrs", "year", "years"]
50
+ };
51
+ function parseTimestring(value, returnUnit, opts) {
52
+ const options = Object.assign({}, DEFAULT_OPTS, opts || {});
53
+ let strValue;
54
+ if (typeof value === "number") {
55
+ strValue = parseInt(value.toString()) + "ms";
56
+ } else if (value.match(/^[-+]?[0-9.]+$/g)) {
57
+ strValue = parseInt(value) + "ms";
58
+ } else {
59
+ strValue = value;
60
+ }
61
+ let totalSeconds = 0;
62
+ const unitValues = getUnitValues(options);
63
+ const groups = strValue.toLowerCase().replace(/[^.\w+-]+/g, "").match(/[-+]?[0-9.]+[a-z]+/g);
64
+ if (groups === null) {
65
+ throw new Error(`The value [${strValue}] could not be parsed by timestring`);
66
+ }
67
+ groups.forEach((group) => {
68
+ const valMatch = group.match(/[0-9.]+/g);
69
+ const unitMatch = group.match(/[a-z]+/g);
70
+ if (valMatch && unitMatch) {
71
+ const val = parseFloat(valMatch[0]);
72
+ const unit = unitMatch[0];
73
+ totalSeconds += getSeconds(val, unit, unitValues);
74
+ }
75
+ });
76
+ if (returnUnit) {
77
+ return convert(totalSeconds, returnUnit, unitValues);
78
+ }
79
+ return totalSeconds;
80
+ }
81
+ function getUnitValues(opts) {
82
+ const unitValues = {
83
+ ms: 1e-3,
84
+ s: 1,
85
+ m: 60,
86
+ h: 3600,
87
+ d: 0,
88
+ w: 0,
89
+ mth: 0,
90
+ y: 0
91
+ };
92
+ unitValues.d = opts.hoursPerDay * unitValues.h;
93
+ unitValues.w = opts.daysPerWeek * unitValues.d;
94
+ unitValues.mth = opts.daysPerYear / opts.monthsPerYear * unitValues.d;
95
+ unitValues.y = opts.daysPerYear * unitValues.d;
96
+ return unitValues;
97
+ }
98
+ function getUnitKey(unit) {
99
+ for (const key of Object.keys(UNIT_MAP)) {
100
+ if (UNIT_MAP[key].indexOf(unit) > -1) {
101
+ return key;
102
+ }
103
+ }
104
+ throw new Error(`The unit [${unit}] is not supported by timestring`);
105
+ }
106
+ function getSeconds(value, unit, unitValues) {
107
+ return value * unitValues[getUnitKey(unit)];
108
+ }
109
+ function convert(value, unit, unitValues) {
110
+ return value / unitValues[getUnitKey(unit)];
111
+ }
112
+
113
+ // src/Candle.ts
114
+ var Candle = class {
115
+ constructor(timestamp, high, low, open, close, volume) {
116
+ this.timestamp = timestamp;
117
+ this.high = high;
118
+ this.low = low;
119
+ this.open = open;
120
+ this.close = close;
121
+ this.volume = volume;
122
+ }
123
+ toString() {
124
+ return JSON.stringify(this);
125
+ }
126
+ };
127
+ function generateCandles(data, candleSize) {
128
+ const candleWidth = parseTimestring(candleSize, "ms", {});
129
+ if (data.length === 0) {
130
+ throw new Error("Input data is empty");
131
+ }
132
+ const _data = data.map((point) => {
133
+ return Object.assign(Object.assign({}, point), {
134
+ // This will convert the timestamp to milliseconds if it's in seconds
135
+ timestamp: point.timestamp && String(point.timestamp).length == 10 ? point.timestamp * 1e3 : point.timestamp
136
+ });
137
+ });
138
+ if (_data[0] === void 0 || Object.keys(_data[0]).length === 0) {
139
+ return [];
140
+ }
141
+ const ohlcvData = [];
142
+ let i = 0;
143
+ let currentTimestamp = Math.floor(_data[0].timestamp / candleWidth) * candleWidth;
144
+ let open = _data[0].price;
145
+ let high = _data[0].price;
146
+ let low = _data[0].price;
147
+ let close = _data[0].price;
148
+ let volume = 0;
149
+ while (i < _data.length) {
150
+ open = close;
151
+ high = close;
152
+ low = close;
153
+ volume = 0;
154
+ let innerI = i;
155
+ while (innerI < _data.length && _data[innerI].timestamp < currentTimestamp + candleWidth) {
156
+ open = innerI === 0 ? _data[innerI].price : open;
157
+ high = Math.max(high, _data[innerI].price);
158
+ low = Math.min(low, _data[innerI].price);
159
+ close = _data[innerI].price;
160
+ volume += _data[innerI].volume;
161
+ innerI++;
162
+ }
163
+ ohlcvData.push({
164
+ timestamp: currentTimestamp,
165
+ high,
166
+ low,
167
+ open,
168
+ close,
169
+ volume
170
+ });
171
+ currentTimestamp += candleWidth;
172
+ i = innerI;
173
+ }
174
+ return ohlcvData;
175
+ }
176
+
177
+ // src/RawTradeData.ts
178
+ var RawTradeData = class {
179
+ constructor(timestamp, price, volume) {
180
+ this.timestamp = timestamp;
181
+ this.price = price;
182
+ this.volume = volume;
183
+ }
184
+ };
185
+
186
+ // src/internal/instantiate.ts
187
+ function instantiate(module2, imports = {}, runtime = {}) {
188
+ let WASM_MEMORY;
189
+ let WASM_EXPORTS;
190
+ let WASM_DV;
191
+ let ASYNCIFY_PTR = 0;
192
+ let ASYNCIFY_MEM;
193
+ let ASYNCIFY_INITIALIZED = false;
194
+ let fetchFn = null;
195
+ let ccxtFn = null;
196
+ let detachedValue = null;
197
+ const adaptedImports = Object.assign(
198
+ {
199
+ console: {
200
+ log(text) {
201
+ console.log(__liftString(text));
202
+ }
203
+ },
204
+ ethers: {
205
+ keccak256_str(str_ptr) {
206
+ const str = __liftString(str_ptr);
207
+ const hash = import_ethers.ethers.keccak256(str);
208
+ return __lowerString(hash);
209
+ },
210
+ keccak256_buf(buf_ptr) {
211
+ const buf = __liftBuffer(buf_ptr);
212
+ const hash = import_ethers.ethers.keccak256(new Uint8Array(buf));
213
+ return __lowerString(hash);
214
+ }
215
+ },
216
+ // @ts-ignore
217
+ env: {
218
+ abort(message, fileName, lineNumber, columnNumber) {
219
+ (() => {
220
+ throw Error(`${__liftString(message)} in ${__liftString(fileName)}:${lineNumber}:${columnNumber}`);
221
+ })();
222
+ },
223
+ _initAsyncify(frame_ptr, stack_ptr) {
224
+ if (!WASM_EXPORTS["asyncify_get_state"])
225
+ throw new Error(
226
+ "Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!"
227
+ );
228
+ if (ASYNCIFY_INITIALIZED) return;
229
+ ASYNCIFY_PTR = frame_ptr;
230
+ ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
231
+ ASYNCIFY_MEM[ASYNCIFY_PTR + 4 >> 2] = stack_ptr;
232
+ ASYNCIFY_INITIALIZED = true;
233
+ },
234
+ generateCandles(data, candleSize) {
235
+ const _data = __liftString(data) || "[]";
236
+ const _candleSize = __liftString(candleSize) || "69m";
237
+ const candles = generateCandles(JSON.parse(_data), _candleSize);
238
+ return __lowerString(JSON.stringify(candles));
239
+ },
240
+ "console.log": (text) => {
241
+ console.log(__liftString(text));
242
+ },
243
+ ccxt_fetchOHLCV: (exchangeId, symbol, timeframe, limit, since) => {
244
+ const currentState = WASM_EXPORTS.asyncify_get_state();
245
+ if (currentState === 2 /* Rewinding */) {
246
+ WASM_EXPORTS.asyncify_stop_rewind();
247
+ const ptr = __lowerStaticArray(
248
+ (pointer, value) => {
249
+ __setU32(pointer, __lowerStaticArray(__setF64, 7, 3, value, Float64Array));
250
+ },
251
+ 8,
252
+ 2,
253
+ detachedValue
254
+ );
255
+ return ptr;
256
+ }
257
+ const _exchange = __liftString(exchangeId);
258
+ const _symbol = __liftString(symbol);
259
+ const _timeframe = __liftString(timeframe);
260
+ ccxtFn = async () => {
261
+ if (!_exchange || !_symbol || !_timeframe)
262
+ throw new Error("Exchange, Symbol, or Timeframe not provided when fetching OHCLV data.");
263
+ const ccxt = await getCcxtOrThrow(runtime);
264
+ const data = await new ccxt[_exchange]({
265
+ apiKey: "",
266
+ secret: ""
267
+ }).fetchOHLCV(_symbol, _timeframe, since, limit);
268
+ return data;
269
+ };
270
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
271
+ }
272
+ },
273
+ "as-fetch": {
274
+ _initAsyncify(frame_ptr, stack_ptr) {
275
+ if (!WASM_EXPORTS["asyncify_get_state"])
276
+ throw new Error(
277
+ "Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!"
278
+ );
279
+ if (ASYNCIFY_INITIALIZED) return;
280
+ ASYNCIFY_PTR = frame_ptr;
281
+ ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
282
+ ASYNCIFY_MEM[ASYNCIFY_PTR + 4 >> 2] = stack_ptr;
283
+ ASYNCIFY_INITIALIZED = true;
284
+ },
285
+ _fetchPOSTSync(url, mode, headers, body) {
286
+ const currentState = WASM_EXPORTS.asyncify_get_state();
287
+ if (currentState === 2 /* Rewinding */) {
288
+ WASM_EXPORTS.asyncify_stop_rewind();
289
+ const ptr = __lowerBuffer(detachedValue);
290
+ detachedValue = null;
291
+ return ptr;
292
+ }
293
+ fetchFn = async () => {
294
+ const fetchImpl = await getFetchOrThrow(runtime);
295
+ const res = await fetchImpl(__liftString(url) || "", {
296
+ method: "POST",
297
+ mode: modeToString(mode) || "cors",
298
+ headers: __liftArray(
299
+ (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
300
+ 2,
301
+ headers
302
+ ) || [],
303
+ body: __liftBuffer(body)
304
+ });
305
+ const value = await res.arrayBuffer();
306
+ return value;
307
+ };
308
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
309
+ },
310
+ _fetchGETSync(url, mode, headers) {
311
+ const currentState = WASM_EXPORTS.asyncify_get_state();
312
+ if (currentState === 2 /* Rewinding */) {
313
+ WASM_EXPORTS.asyncify_stop_rewind();
314
+ const ptr = __lowerBuffer(detachedValue);
315
+ detachedValue = null;
316
+ return ptr;
317
+ }
318
+ fetchFn = async () => {
319
+ const fetchImpl = await getFetchOrThrow(runtime);
320
+ const res = await fetchImpl(__liftString(url) || "", {
321
+ method: "GET",
322
+ mode: modeToString(mode) || "cors",
323
+ headers: __liftArray(
324
+ (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
325
+ 2,
326
+ headers
327
+ ) || []
328
+ });
329
+ const value = await res.arrayBuffer();
330
+ return value;
331
+ };
332
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
333
+ },
334
+ _fetchGET(url, mode, headers, callbackID) {
335
+ void (async () => {
336
+ const fetchImpl = await getFetchOrThrow(runtime);
337
+ const res = await fetchImpl(__liftString(url) || "", {
338
+ method: "GET",
339
+ mode: modeToString(mode) || "cors",
340
+ headers: __liftArray(
341
+ (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
342
+ 2,
343
+ headers
344
+ ) || []
345
+ });
346
+ const body = await res.arrayBuffer();
347
+ WASM_EXPORTS.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);
348
+ })();
349
+ },
350
+ _fetchPOST(url, mode, headers, body, callbackID) {
351
+ void (async () => {
352
+ const fetchImpl = await getFetchOrThrow(runtime);
353
+ const res = await fetchImpl(__liftString(url) || "", {
354
+ method: "POST",
355
+ mode: modeToString(mode) || "cors",
356
+ body,
357
+ headers: __liftArray(
358
+ (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
359
+ 2,
360
+ headers
361
+ ) || []
362
+ });
363
+ const responseBody = await res.arrayBuffer();
364
+ WASM_EXPORTS.responseHandler(responseBody, res.status, res.redirected ? 1 : 0, callbackID);
365
+ })();
366
+ }
367
+ }
368
+ },
369
+ imports
370
+ );
371
+ const mod = new WebAssembly.Instance(module2, adaptedImports);
372
+ WASM_EXPORTS = mod.exports;
373
+ WASM_MEMORY = WASM_EXPORTS.memory || adaptedImports.env.memory;
374
+ ASYNCIFY_MEM = new Uint32Array(WASM_MEMORY.buffer);
375
+ const handledExports = Object.setPrototypeOf(
376
+ {
377
+ responseHandler(body, statusCode, redirected, callbackID) {
378
+ if (!WASM_EXPORTS["responseHandler"])
379
+ throw new Error(
380
+ 'Unable to call .responseHandler on wasm module. Add the line export { responseHandler } from "as-fetch/assembly" to your entry file.'
381
+ );
382
+ WASM_EXPORTS.responseHandler(__lowerBuffer(body), statusCode, redirected ? 1 : 0, callbackID);
383
+ },
384
+ initialize(config) {
385
+ if (!WASM_EXPORTS["initialize"])
386
+ throw new Error("Unable to call .initialize on wasm module. Are you sure this is a data connector?");
387
+ try {
388
+ WASM_EXPORTS.initialize(__lowerString(config));
389
+ return true;
390
+ } catch (e) {
391
+ console.error(e);
392
+ return false;
393
+ }
394
+ },
395
+ async execute(...params) {
396
+ if (!WASM_EXPORTS["execute"])
397
+ throw new Error("Unable to call .execute on wasm module. Are you sure this is a data connector?");
398
+ const loweredArgs = new Array(params.length);
399
+ for (let i = 0; i < params.length; i++) {
400
+ loweredArgs[i] = __lower(params[i]);
401
+ }
402
+ let result;
403
+ try {
404
+ result = WASM_EXPORTS.execute(...loweredArgs);
405
+ } catch (error) {
406
+ if (params.length !== 0) {
407
+ throw error;
408
+ }
409
+ result = WASM_EXPORTS.execute(__lowerString(""));
410
+ }
411
+ if (ASYNCIFY_INITIALIZED) {
412
+ while (WASM_EXPORTS.asyncify_get_state() === 1 /* Unwinding */) {
413
+ WASM_EXPORTS.asyncify_stop_unwind();
414
+ if (fetchFn) detachedValue = await fetchFn();
415
+ if (ccxtFn) detachedValue = await ccxtFn();
416
+ WASM_EXPORTS.asyncify_start_rewind(ASYNCIFY_PTR);
417
+ result = WASM_EXPORTS.execute();
418
+ }
419
+ }
420
+ if (fetchFn) fetchFn = null;
421
+ if (ccxtFn) ccxtFn = null;
422
+ return __liftString(result);
423
+ },
424
+ config() {
425
+ if (!WASM_EXPORTS["config"])
426
+ throw new Error("Unable to call .config on wasm module. Are you sure this is a data connector?");
427
+ return __liftString(WASM_EXPORTS.config());
428
+ },
429
+ transform() {
430
+ if (!WASM_EXPORTS["transform"])
431
+ throw new Error("Unable to call .transform on wasm module. Are you sure this is a data connector?");
432
+ return __liftString(WASM_EXPORTS.transform());
433
+ },
434
+ reset() {
435
+ if (WASM_EXPORTS["reset"]) WASM_EXPORTS.reset();
436
+ }
437
+ },
438
+ WASM_EXPORTS
439
+ );
440
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
441
+ function __lower(val) {
442
+ if (typeof val === "number") {
443
+ return val;
444
+ } else if (typeof val === "string") {
445
+ return __lowerString(val);
446
+ } else if (val instanceof ArrayBuffer) {
447
+ return __lowerBuffer(val);
448
+ } else {
449
+ return 0;
450
+ }
451
+ }
452
+ function __liftString(ptr) {
453
+ if (!ptr) return null;
454
+ const end = ptr + new Uint32Array(WASM_MEMORY.buffer)[ptr - 4 >>> 2] >>> 1;
455
+ const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
456
+ let start = ptr >>> 1;
457
+ let string = "";
458
+ while (end - start > 1024) string += String.fromCharCode(...memoryU16.subarray(start, start += 1024));
459
+ return string + String.fromCharCode(...memoryU16.subarray(start, end));
460
+ }
461
+ function __lowerString(value) {
462
+ if (value == null) return 0;
463
+ const length = value.length;
464
+ const ptr = WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << 1, 2) >>> 0);
465
+ const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
466
+ for (let i = 0; i < length; ++i) memoryU16[(ptr >>> 1) + i] = value.charCodeAt(i);
467
+ return ptr;
468
+ }
469
+ function __liftBuffer(ptr) {
470
+ if (!ptr) return null;
471
+ return WASM_MEMORY.buffer.slice(ptr, ptr + new Uint32Array(WASM_MEMORY.buffer)[ptr - 4 >>> 2]);
472
+ }
473
+ function __lowerBuffer(value) {
474
+ if (value == null) return 0;
475
+ const ptr = WASM_EXPORTS.__pin(WASM_EXPORTS.__new(value.byteLength, 1) >>> 0);
476
+ new Uint8Array(WASM_MEMORY.buffer).set(new Uint8Array(value), ptr);
477
+ return ptr;
478
+ }
479
+ function __liftArray(liftElement, align, ptr) {
480
+ if (!ptr) return null;
481
+ const dataStart = __getU32(ptr + 4);
482
+ const length = WASM_DV.getUint32(ptr + 12, true);
483
+ const values = new Array(length);
484
+ for (let i = 0; i < length; ++i) values[i] = liftElement(dataStart + (i << align >>> 0));
485
+ return values;
486
+ }
487
+ function __lowerStaticArray(lowerElement, id, align, values, typedConstructor = null) {
488
+ if (values == null) return 0;
489
+ const length = values.length;
490
+ const buffer = WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << align, id)) >>> 0;
491
+ if (typedConstructor) {
492
+ new typedConstructor(WASM_MEMORY.buffer, buffer, length).set(values);
493
+ } else {
494
+ for (let i = 0; i < length; i++) lowerElement(buffer + (i << align >>> 0), values[i]);
495
+ }
496
+ return buffer;
497
+ }
498
+ function __setU32(ptr, value) {
499
+ try {
500
+ WASM_DV.setUint32(ptr, value, true);
501
+ } catch {
502
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
503
+ WASM_DV.setUint32(ptr, value, true);
504
+ }
505
+ }
506
+ function __setF64(ptr, value) {
507
+ try {
508
+ WASM_DV.setFloat64(ptr, value, true);
509
+ } catch {
510
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
511
+ WASM_DV.setFloat64(ptr, value, true);
512
+ }
513
+ }
514
+ function __getU32(ptr) {
515
+ try {
516
+ return WASM_DV.getUint32(ptr, true);
517
+ } catch {
518
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
519
+ return WASM_DV.getUint32(ptr, true);
520
+ }
521
+ }
522
+ return handledExports;
523
+ }
524
+ async function getFetchOrThrow(runtime) {
525
+ if (!runtime.getFetch) {
526
+ throw new Error("Fetch is not available in this runtime.");
527
+ }
528
+ return runtime.getFetch();
529
+ }
530
+ async function getCcxtOrThrow(runtime) {
531
+ if (!runtime.getCcxt) {
532
+ throw new Error("ccxt is not available in this runtime.");
533
+ }
534
+ return runtime.getCcxt();
535
+ }
536
+ function modeToString(mode) {
537
+ if (mode == 1) return "cors";
538
+ if (mode == 2) return "no-cors";
539
+ if (mode == 3) return "same-origin";
540
+ if (mode == 4) return "navigate";
541
+ return null;
542
+ }
543
+
544
+ // src/index.ts
545
+ function loadWasmSync(input, imports = {}) {
546
+ return instantiate(new WebAssembly.Module(input), imports, {
547
+ getFetch: getRuntimeFetch,
548
+ getCcxt: getRuntimeCcxt
549
+ });
550
+ }
551
+ async function loadWasm(input, imports = {}) {
552
+ const module2 = typeof input === "string" ? await compileFromString(input) : await WebAssembly.compile(input);
553
+ return instantiate(module2, imports, {
554
+ getFetch: getRuntimeFetch,
555
+ getCcxt: getRuntimeCcxt
556
+ });
557
+ }
558
+ async function compileFromString(input) {
559
+ if (!isNodeRuntime()) {
560
+ return compileFromUrl(input);
561
+ }
562
+ if (isHttpUrl(input)) {
563
+ return compileFromUrl(input);
564
+ }
565
+ const fs = await importRuntimeModule("fs/promises");
566
+ return WebAssembly.compile(await fs.readFile(input));
567
+ }
568
+ async function compileFromUrl(url) {
569
+ const fetchImpl = await getRuntimeFetch();
570
+ const response = await fetchImpl(url);
571
+ if (typeof WebAssembly.compileStreaming === "function") {
572
+ try {
573
+ return await WebAssembly.compileStreaming(Promise.resolve(response.clone()));
574
+ } catch {
575
+ }
576
+ }
577
+ return WebAssembly.compile(await response.arrayBuffer());
578
+ }
579
+ async function getRuntimeFetch() {
580
+ if (typeof globalThis.fetch === "function") {
581
+ return globalThis.fetch.bind(globalThis);
582
+ }
583
+ if (!isNodeRuntime()) {
584
+ throw new Error("Fetch is not available in this browser runtime.");
585
+ }
586
+ throw new Error("Fetch is not available in this Node runtime. Node 18+ is required.");
587
+ }
588
+ async function getRuntimeCcxt() {
589
+ if (isNodeRuntime()) {
590
+ const ccxt2 = await importRuntimeModule("ccxt");
591
+ return ccxt2.default ?? ccxt2;
592
+ }
593
+ const ccxt = globalThis.ccxt;
594
+ if (!ccxt) {
595
+ throw new Error("ccxt is not available in this browser runtime.");
596
+ }
597
+ return ccxt;
598
+ }
599
+ function isNodeRuntime() {
600
+ return typeof process !== "undefined" && !!process.versions?.node;
601
+ }
602
+ function isHttpUrl(value) {
603
+ try {
604
+ const url = new URL(value);
605
+ return url.protocol === "http:" || url.protocol === "https:";
606
+ } catch {
607
+ return false;
608
+ }
609
+ }
610
+ function importRuntimeModule(specifier) {
611
+ if (isNodeRuntime() && typeof require === "function") {
612
+ return Promise.resolve(require(specifier));
613
+ }
614
+ return new Function("s", "return import(s)")(specifier);
615
+ }
616
+ // Annotate the CommonJS export names for ESM import in node:
617
+ 0 && (module.exports = {
618
+ Candle,
619
+ RawTradeData,
620
+ loadWasm,
621
+ loadWasmSync
622
+ });
623
+ //# sourceMappingURL=index.cjs.map