@tradejs/infra 1.0.5 → 1.0.8

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.
@@ -0,0 +1,636 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/userSettings.ts
31
+ var userSettings_exports = {};
32
+ __export(userSettings_exports, {
33
+ getUserRecord: () => getUserRecord,
34
+ getUserSettings: () => getUserSettings,
35
+ updateUserRecord: () => updateUserRecord
36
+ });
37
+ module.exports = __toCommonJS(userSettings_exports);
38
+
39
+ // src/aiLanguages.ts
40
+ var AI_RESPONSE_LANGUAGE_OPTIONS = [
41
+ { label: "English", value: "en", promptName: "English" },
42
+ { label: "Chinese", value: "zh", promptName: "Chinese" },
43
+ { label: "Hindi", value: "hi", promptName: "Hindi" },
44
+ { label: "Spanish", value: "es", promptName: "Spanish" },
45
+ { label: "French", value: "fr", promptName: "French" },
46
+ { label: "Arabic", value: "ar", promptName: "Arabic" },
47
+ { label: "Bengali", value: "bn", promptName: "Bengali" },
48
+ { label: "Portuguese", value: "pt", promptName: "Portuguese" },
49
+ { label: "Russian", value: "ru", promptName: "Russian" },
50
+ { label: "Urdu", value: "ur", promptName: "Urdu" },
51
+ { label: "Indonesian", value: "id", promptName: "Indonesian" },
52
+ { label: "German", value: "de", promptName: "German" },
53
+ { label: "Japanese", value: "ja", promptName: "Japanese" },
54
+ { label: "Swahili", value: "sw", promptName: "Swahili" },
55
+ { label: "Marathi", value: "mr", promptName: "Marathi" },
56
+ { label: "Telugu", value: "te", promptName: "Telugu" },
57
+ { label: "Turkish", value: "tr", promptName: "Turkish" },
58
+ { label: "Tamil", value: "ta", promptName: "Tamil" },
59
+ { label: "Vietnamese", value: "vi", promptName: "Vietnamese" },
60
+ { label: "Korean", value: "ko", promptName: "Korean" }
61
+ ];
62
+ var KNOWN_AI_RESPONSE_LANGUAGES = new Set(
63
+ AI_RESPONSE_LANGUAGE_OPTIONS.map((option) => option.value)
64
+ );
65
+ var DEFAULT_AI_RESPONSE_LANGUAGE = AI_RESPONSE_LANGUAGE_OPTIONS[0].value;
66
+ var normalizeAiResponseLanguage = (value) => {
67
+ if (typeof value !== "string") {
68
+ return DEFAULT_AI_RESPONSE_LANGUAGE;
69
+ }
70
+ const trimmed = value.trim().toLowerCase();
71
+ return KNOWN_AI_RESPONSE_LANGUAGES.has(trimmed) ? trimmed : DEFAULT_AI_RESPONSE_LANGUAGE;
72
+ };
73
+
74
+ // src/aiEndpoints.ts
75
+ var AI_CUSTOM_ENDPOINT_VALUE = "__custom__";
76
+ var AI_ENDPOINT_OPTIONS = [
77
+ {
78
+ label: "OpenAI",
79
+ value: "https://api.openai.com/v1"
80
+ },
81
+ {
82
+ label: "Claude",
83
+ value: "https://api.anthropic.com/v1"
84
+ },
85
+ {
86
+ label: "OpenRouter",
87
+ value: "https://openrouter.ai/api/v1"
88
+ },
89
+ {
90
+ label: "Gemini",
91
+ value: "https://generativelanguage.googleapis.com/v1beta/openai"
92
+ },
93
+ {
94
+ label: "Together AI",
95
+ value: "https://api.together.xyz/v1"
96
+ },
97
+ {
98
+ label: "Groq",
99
+ value: "https://api.groq.com/openai/v1"
100
+ },
101
+ {
102
+ label: "DeepInfra",
103
+ value: "https://api.deepinfra.com/v1/openai"
104
+ },
105
+ {
106
+ label: "xAI",
107
+ value: "https://api.x.ai/v1"
108
+ },
109
+ {
110
+ label: "Qwen (DashScope Intl)",
111
+ value: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
112
+ },
113
+ {
114
+ label: "Qwen (DashScope CN)",
115
+ value: "https://dashscope.aliyuncs.com/compatible-mode/v1"
116
+ },
117
+ {
118
+ label: "Qwen (DashScope US)",
119
+ value: "https://dashscope-us.aliyuncs.com/compatible-mode/v1"
120
+ },
121
+ {
122
+ label: "Perplexity",
123
+ value: "https://api.perplexity.ai"
124
+ },
125
+ {
126
+ label: "Fireworks",
127
+ value: "https://api.fireworks.ai/inference/v1"
128
+ },
129
+ {
130
+ label: "SambaNova",
131
+ value: "https://api.sambanova.ai/v1"
132
+ },
133
+ {
134
+ label: "Hyperbolic",
135
+ value: "https://api.hyperbolic.xyz/v1"
136
+ },
137
+ {
138
+ label: "Kimi",
139
+ value: "https://api.moonshot.ai/v1"
140
+ },
141
+ {
142
+ label: "ProxyAPI",
143
+ value: "https://openai.api.proxyapi.ru/v1"
144
+ },
145
+ {
146
+ label: "Custom",
147
+ value: AI_CUSTOM_ENDPOINT_VALUE
148
+ }
149
+ ];
150
+ var KNOWN_AI_ENDPOINTS = new Set(
151
+ AI_ENDPOINT_OPTIONS.map((option) => option.value).filter(
152
+ (value) => value !== AI_CUSTOM_ENDPOINT_VALUE
153
+ )
154
+ );
155
+ var normalizeUrl = (value) => value.replace(/\/+$/, "");
156
+ var isIpv4Address = (value) => /^(?:\d{1,3}\.){3}\d{1,3}$/.test(value.trim());
157
+ var parseIpv4Address = (value) => value.trim().split(".").map((part) => Number(part));
158
+ var isPrivateIpv4Address = (value) => {
159
+ if (!isIpv4Address(value)) {
160
+ return false;
161
+ }
162
+ const [a, b, c, d] = parseIpv4Address(value);
163
+ if ([a, b, c, d].some(
164
+ (part) => !Number.isInteger(part) || part < 0 || part > 255
165
+ )) {
166
+ return false;
167
+ }
168
+ return a === 10 || a === 127 || a === 0 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
169
+ };
170
+ var isPrivateHostname = (hostname) => {
171
+ const normalized = hostname.trim().toLowerCase();
172
+ if (!normalized) {
173
+ return true;
174
+ }
175
+ return normalized === "localhost" || normalized.endsWith(".localhost") || normalized.endsWith(".local") || normalized.endsWith(".internal") || normalized.endsWith(".lan") || normalized === "::1" || normalized === "[::1]" || isPrivateIpv4Address(normalized);
176
+ };
177
+ var isValidAiEndpointUrl = (value) => {
178
+ try {
179
+ const url = new URL(value);
180
+ return url.protocol === "https:" && !isPrivateHostname(url.hostname);
181
+ } catch {
182
+ return false;
183
+ }
184
+ };
185
+ var normalizeAiEndpoint = (value) => {
186
+ if (typeof value !== "string") {
187
+ return "";
188
+ }
189
+ const trimmed = normalizeUrl(value.trim());
190
+ if (!trimmed) {
191
+ return "";
192
+ }
193
+ if (KNOWN_AI_ENDPOINTS.has(trimmed)) {
194
+ return trimmed;
195
+ }
196
+ return isValidAiEndpointUrl(trimmed) ? trimmed : "";
197
+ };
198
+
199
+ // src/aiModels.ts
200
+ var OPENAI_ENDPOINT = "https://api.openai.com/v1";
201
+ var ANTHROPIC_ENDPOINT = "https://api.anthropic.com/v1";
202
+ var OPENROUTER_ENDPOINT = "https://openrouter.ai/api/v1";
203
+ var GEMINI_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/openai";
204
+ var TOGETHER_ENDPOINT = "https://api.together.xyz/v1";
205
+ var GROQ_ENDPOINT = "https://api.groq.com/openai/v1";
206
+ var XAI_ENDPOINT = "https://api.x.ai/v1";
207
+ var QWEN_INTL_ENDPOINT = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
208
+ var QWEN_CN_ENDPOINT = "https://dashscope.aliyuncs.com/compatible-mode/v1";
209
+ var QWEN_US_ENDPOINT = "https://dashscope-us.aliyuncs.com/compatible-mode/v1";
210
+ var PERPLEXITY_ENDPOINT = "https://api.perplexity.ai";
211
+ var KIMI_ENDPOINT = "https://api.moonshot.ai/v1";
212
+ var PROXY_API_ENDPOINT = "https://openai.api.proxyapi.ru/v1";
213
+ var AI_MODEL_OPTIONS_BY_ENDPOINT = {
214
+ [OPENAI_ENDPOINT]: [
215
+ { label: "GPT-5 mini", value: "gpt-5-mini" },
216
+ { label: "GPT-5", value: "gpt-5" },
217
+ { label: "GPT-5.2", value: "gpt-5.2" },
218
+ { label: "GPT-4.1", value: "gpt-4.1" },
219
+ { label: "GPT-4o", value: "gpt-4o" }
220
+ ],
221
+ [ANTHROPIC_ENDPOINT]: [
222
+ { label: "Claude Sonnet 4", value: "claude-sonnet-4-20250514" },
223
+ { label: "Claude Opus 4.1", value: "claude-opus-4-1-20250805" },
224
+ { label: "Claude Opus 4", value: "claude-opus-4-20250514" },
225
+ { label: "Claude 3.7 Sonnet", value: "claude-3-7-sonnet-20250219" },
226
+ { label: "Claude 3.5 Haiku", value: "claude-3-5-haiku-20241022" }
227
+ ],
228
+ [OPENROUTER_ENDPOINT]: [
229
+ { label: "OpenAI GPT-5", value: "openai/gpt-5" },
230
+ { label: "Anthropic Claude Sonnet 4", value: "anthropic/claude-sonnet-4" },
231
+ { label: "Google Gemini 2.5 Pro", value: "google/gemini-2.5-pro" },
232
+ { label: "OpenAI GPT-5 mini", value: "openai/gpt-5-mini" },
233
+ {
234
+ label: "DeepSeek V3.1",
235
+ value: "deepseek/deepseek-chat-v3.1"
236
+ }
237
+ ],
238
+ [GEMINI_ENDPOINT]: [
239
+ { label: "Gemini 2.5 Pro", value: "gemini-2.5-pro" },
240
+ { label: "Gemini 2.5 Flash", value: "gemini-2.5-flash" },
241
+ { label: "Gemini 2.5 Flash-Lite", value: "gemini-2.5-flash-lite" },
242
+ { label: "Gemini 2.0 Flash", value: "gemini-2.0-flash" },
243
+ { label: "Gemini 2.0 Flash-Lite", value: "gemini-2.0-flash-lite" }
244
+ ],
245
+ [TOGETHER_ENDPOINT]: [
246
+ { label: "DeepSeek V3.1", value: "deepseek-ai/DeepSeek-V3.1" },
247
+ {
248
+ label: "Qwen3 Coder 480B",
249
+ value: "Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8"
250
+ },
251
+ {
252
+ label: "Llama 4 Maverick",
253
+ value: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8"
254
+ },
255
+ { label: "DeepSeek V3", value: "deepseek-ai/DeepSeek-V3" },
256
+ {
257
+ label: "Llama 3.3 70B Turbo",
258
+ value: "meta-llama/Llama-3.3-70B-Instruct-Turbo"
259
+ }
260
+ ],
261
+ [GROQ_ENDPOINT]: [
262
+ { label: "GPT-OSS 120B", value: "openai/gpt-oss-120b" },
263
+ {
264
+ label: "Llama 4 Scout",
265
+ value: "meta-llama/llama-4-scout-17b-16e-instruct"
266
+ },
267
+ { label: "Qwen3 32B", value: "qwen/qwen3-32b" },
268
+ { label: "Llama 3.3 70B", value: "llama-3.3-70b-versatile" },
269
+ { label: "Llama 3.1 8B Instant", value: "llama-3.1-8b-instant" }
270
+ ],
271
+ [XAI_ENDPOINT]: [
272
+ { label: "Grok 4 Fast Reasoning", value: "grok-4-fast-reasoning" },
273
+ { label: "Grok 4 Fast Non-Reasoning", value: "grok-4-fast-non-reasoning" },
274
+ { label: "Grok Code Fast 1", value: "grok-code-fast-1" },
275
+ { label: "Grok 4", value: "grok-4-0709" },
276
+ { label: "Grok 3 Mini", value: "grok-3-mini" }
277
+ ],
278
+ [QWEN_INTL_ENDPOINT]: [
279
+ { label: "Qwen Plus Latest", value: "qwen-plus-latest" },
280
+ { label: "Qwen Turbo Latest", value: "qwen-turbo-latest" },
281
+ { label: "Qwen Max Latest", value: "qwen-max-latest" },
282
+ { label: "Qwen3 Coder Plus", value: "qwen3-coder-plus" },
283
+ { label: "Qwen3 Coder Next", value: "qwen3-coder-next" }
284
+ ],
285
+ [QWEN_CN_ENDPOINT]: [
286
+ { label: "Qwen Plus Latest", value: "qwen-plus-latest" },
287
+ { label: "Qwen Turbo Latest", value: "qwen-turbo-latest" },
288
+ { label: "Qwen Max Latest", value: "qwen-max-latest" },
289
+ { label: "Qwen3 Coder Plus", value: "qwen3-coder-plus" },
290
+ { label: "Qwen3 Coder Next", value: "qwen3-coder-next" }
291
+ ],
292
+ [QWEN_US_ENDPOINT]: [
293
+ { label: "Qwen Plus Latest", value: "qwen-plus-latest" },
294
+ { label: "Qwen Turbo Latest", value: "qwen-turbo-latest" },
295
+ { label: "Qwen Max Latest", value: "qwen-max-latest" },
296
+ { label: "Qwen3 Coder Plus", value: "qwen3-coder-plus" },
297
+ { label: "Qwen3 Coder Next", value: "qwen3-coder-next" }
298
+ ],
299
+ [PERPLEXITY_ENDPOINT]: [
300
+ { label: "Sonar Pro", value: "sonar-pro" },
301
+ { label: "Sonar", value: "sonar" },
302
+ { label: "Sonar Reasoning Pro", value: "sonar-reasoning-pro" },
303
+ { label: "Sonar Deep Research", value: "sonar-deep-research" }
304
+ ],
305
+ [KIMI_ENDPOINT]: [
306
+ { label: "Kimi K2.5", value: "kimi-k2.5" },
307
+ { label: "Kimi K2 Thinking", value: "kimi-k2-thinking" },
308
+ { label: "Kimi K2 Turbo Preview", value: "kimi-k2-turbo-preview" },
309
+ { label: "Kimi K2 0905 Preview", value: "kimi-k2-0905-preview" },
310
+ { label: "Kimi K2", value: "kimi-k2" }
311
+ ],
312
+ [PROXY_API_ENDPOINT]: [
313
+ {
314
+ label: "Anthropic Claude Sonnet 4",
315
+ value: "anthropic/claude-sonnet-4-20250514"
316
+ },
317
+ { label: "Gemini 2.5 Flash", value: "gemini/gemini-2.5-flash" },
318
+ { label: "OpenAI GPT-5 mini", value: "openai/gpt-5-mini" },
319
+ { label: "OpenAI GPT-4o", value: "openai/gpt-4o" },
320
+ {
321
+ label: "OpenRouter DeepSeek Chat V3.1",
322
+ value: "openrouter/deepseek/deepseek-chat-v3.1"
323
+ }
324
+ ]
325
+ };
326
+ var DEFAULT_AI_MODEL_BY_ENDPOINT = Object.fromEntries(
327
+ Object.entries(AI_MODEL_OPTIONS_BY_ENDPOINT).map(([endpoint, options]) => [
328
+ endpoint,
329
+ options[0]?.value ?? ""
330
+ ])
331
+ );
332
+ var normalizeModel = (value) => value.trim();
333
+ var getDefaultAiModelForEndpoint = (endpoint) => DEFAULT_AI_MODEL_BY_ENDPOINT[endpoint] ?? "";
334
+ var normalizeAiModel = (value, endpoint) => {
335
+ if (typeof value === "string") {
336
+ const trimmed = normalizeModel(value);
337
+ if (trimmed) {
338
+ return trimmed;
339
+ }
340
+ }
341
+ return getDefaultAiModelForEndpoint(endpoint);
342
+ };
343
+
344
+ // src/redis.ts
345
+ var import_ioredis = __toESM(require("ioredis"));
346
+ var TTL_1D = 86400;
347
+ var SCREENSHOT_TOKEN_TTL_SECONDS = 15 * 60;
348
+ var toJson = (value) => JSON.stringify(value);
349
+ var logger = {
350
+ log: (level, message, ...args) => {
351
+ const method = level === "error" ? "error" : level === "warn" ? "warn" : "log";
352
+ console[method](`[infra:redis] ${message}`, ...args);
353
+ }
354
+ };
355
+ var redisConnectionWarningShown = false;
356
+ var redisUnavailable = false;
357
+ var isRedisConnectivityError = (error) => /ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|MaxRetriesPerRequestError|Connection is closed|Stream isn't writeable/i.test(
358
+ error.message
359
+ );
360
+ var toNonNegativeInt = (value, fallback) => {
361
+ const parsed = Number.parseInt(String(value ?? ""), 10);
362
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
363
+ };
364
+ var toPositiveInt = (value, fallback) => {
365
+ const parsed = Number.parseInt(String(value ?? ""), 10);
366
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
367
+ };
368
+ var markRedisUnavailable = (error) => {
369
+ redisUnavailable = true;
370
+ if (redisConnectionWarningShown) return;
371
+ redisConnectionWarningShown = true;
372
+ logger.log(
373
+ "warn",
374
+ "Redis is unavailable: %s. Cache-dependent features are temporarily disabled.",
375
+ error.message
376
+ );
377
+ };
378
+ var getRedis = () => {
379
+ if (!global.__redis__) {
380
+ const host = process.env.REDIS_HOST || "127.0.0.1";
381
+ const port = toPositiveInt(process.env.REDIS_PORT, 6379);
382
+ const connectTimeout = toPositiveInt(
383
+ process.env.REDIS_CONNECT_TIMEOUT_MS,
384
+ 3e3
385
+ );
386
+ const maxRetriesPerRequest = toNonNegativeInt(
387
+ process.env.REDIS_MAX_RETRIES_PER_REQUEST,
388
+ 1
389
+ );
390
+ global.__redis__ = new import_ioredis.default({
391
+ host,
392
+ port,
393
+ connectTimeout,
394
+ maxRetriesPerRequest,
395
+ enableOfflineQueue: false,
396
+ retryStrategy: (attempt) => Math.min(attempt * 200, 2e3)
397
+ });
398
+ global.__redis__.on("error", (error) => {
399
+ if (isRedisConnectivityError(error)) {
400
+ markRedisUnavailable(error);
401
+ return;
402
+ }
403
+ logger.log("error", "Redis client error: %s", String(error));
404
+ });
405
+ global.__redis__.on("ready", () => {
406
+ redisUnavailable = false;
407
+ if (redisConnectionWarningShown) {
408
+ redisConnectionWarningShown = false;
409
+ logger.log("info", "Redis connection restored");
410
+ }
411
+ });
412
+ }
413
+ return global.__redis__;
414
+ };
415
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
416
+ var getRedisStatus = (redis) => String(redis.status ?? "ready");
417
+ var waitForRedisReady = async (redis) => {
418
+ if (getRedisStatus(redis) === "ready") {
419
+ return true;
420
+ }
421
+ const readyTimeoutMs = toPositiveInt(
422
+ process.env.REDIS_READY_TIMEOUT_MS,
423
+ toPositiveInt(process.env.REDIS_CONNECT_TIMEOUT_MS, 3e3)
424
+ );
425
+ const startedAt = Date.now();
426
+ while (Date.now() - startedAt < readyTimeoutMs) {
427
+ if (getRedisStatus(redis) === "ready") {
428
+ return true;
429
+ }
430
+ if (getRedisStatus(redis) === "end") {
431
+ return false;
432
+ }
433
+ await sleep(50);
434
+ }
435
+ return getRedisStatus(redis) === "ready";
436
+ };
437
+ var getReadyRedis = async () => {
438
+ if (redisUnavailable) return null;
439
+ const redis = getRedis();
440
+ const ready = await waitForRedisReady(redis);
441
+ if (ready) {
442
+ return redis;
443
+ }
444
+ markRedisUnavailable(
445
+ new Error(`Redis is not ready (status=${getRedisStatus(redis)})`)
446
+ );
447
+ return null;
448
+ };
449
+ var toResultString = (result) => {
450
+ if (result == null) return null;
451
+ if (typeof result === "string") return result;
452
+ if (Buffer.isBuffer(result)) return result.toString("utf8");
453
+ return String(result);
454
+ };
455
+ var DEFAULT_OPTIONS = {
456
+ expire: TTL_1D
457
+ };
458
+ var parseJsonOrDeleteKey = async (redis, key, raw, fallback) => {
459
+ try {
460
+ return JSON.parse(raw);
461
+ } catch (e) {
462
+ logger.log("error", "failed JSON.parse(%s): %s", key, String(e));
463
+ await redis.del(key);
464
+ return fallback;
465
+ }
466
+ };
467
+ var getData = async (key, fallback = []) => {
468
+ if (redisUnavailable) return fallback;
469
+ const redis = await getReadyRedis();
470
+ if (!redis) return fallback;
471
+ try {
472
+ const rawJson = await redis.call("JSON.GET", key);
473
+ const raw = toResultString(rawJson);
474
+ if (raw == null) return fallback;
475
+ return parseJsonOrDeleteKey(redis, key, raw, fallback);
476
+ } catch (e) {
477
+ if (e instanceof Error && isRedisConnectivityError(e)) {
478
+ markRedisUnavailable(e);
479
+ return fallback;
480
+ }
481
+ logger.log(
482
+ "error",
483
+ "failed JSON.GET %s: %s (fallback to GET)",
484
+ key,
485
+ String(e)
486
+ );
487
+ }
488
+ try {
489
+ const raw = await redis.get(key);
490
+ if (raw == null) return fallback;
491
+ return parseJsonOrDeleteKey(redis, key, raw, fallback);
492
+ } catch (e) {
493
+ if (e instanceof Error && isRedisConnectivityError(e)) {
494
+ markRedisUnavailable(e);
495
+ return fallback;
496
+ }
497
+ logger.log("error", "failed GET %s: %s", key, String(e));
498
+ return fallback;
499
+ }
500
+ };
501
+ var setData = async (key, data, options = {}) => {
502
+ if (redisUnavailable) return;
503
+ const { expire } = { ...DEFAULT_OPTIONS, ...options };
504
+ const redis = await getReadyRedis();
505
+ if (!redis) return;
506
+ const value = toJson(data);
507
+ try {
508
+ await redis.call("JSON.SET", key, "$", value);
509
+ if (expire) {
510
+ await redis.expire(key, expire);
511
+ }
512
+ } catch (e) {
513
+ if (e instanceof Error && isRedisConnectivityError(e)) {
514
+ markRedisUnavailable(e);
515
+ return;
516
+ }
517
+ logger.log(
518
+ "error",
519
+ "failed JSON.SET %s: %s (fallback to SET)",
520
+ key,
521
+ String(e)
522
+ );
523
+ try {
524
+ if (expire) {
525
+ await redis.set(key, value, "EX", expire);
526
+ } else {
527
+ await redis.set(key, value);
528
+ }
529
+ } catch (e2) {
530
+ if (e2 instanceof Error && isRedisConnectivityError(e2)) {
531
+ markRedisUnavailable(e2);
532
+ return;
533
+ }
534
+ logger.log("error", "failed SET %s: %s", key, String(e2));
535
+ }
536
+ }
537
+ };
538
+ var redisKeys = {
539
+ users: () => "users:index:",
540
+ user: (userName) => `users:index:${userName}`,
541
+ bots: (userName) => `users:${userName}:bots`,
542
+ botsPrefix: () => "users:",
543
+ bot: (userName, botId) => `users:${userName}:bots:${botId}`,
544
+ backtestConfig: (userName, config) => `users:${userName}:backtests:configs:${config}`,
545
+ strategies: (userName) => `users:${userName}:strategies`,
546
+ strategyConfig: (userName, strategyName) => `users:${userName}:strategies:${strategyName}:config`,
547
+ strategyResults: (userName, strategyName) => `users:${userName}:strategies:${strategyName}:results`,
548
+ tests: (userName, strategyName) => strategyName ? `users:${userName}:tests:${strategyName}` : `users:${userName}:tests:`,
549
+ testOrders: (userName, strategyName, testName) => `users:${userName}:tests:${strategyName}:${testName}:orders`,
550
+ testConfig: (userName, strategyName, testName) => `users:${userName}:tests:${strategyName}:${testName}:config`,
551
+ testStat: (userName, strategyName, testName) => `users:${userName}:tests:${strategyName}:${testName}:stat`,
552
+ testSummaries: (userName) => `users:${userName}:tests:index:summary`,
553
+ cacheChunk: (userName, chunkId) => `users:${userName}:cache:tests:chunks:${chunkId}`,
554
+ cacheOrders: (userName, orderLogId) => `users:${userName}:cache:tests:orders:${orderLogId}`,
555
+ cachePositions: (userName, orderLogId) => `users:${userName}:cache:tests:positions:${orderLogId}`,
556
+ signal: (symbol, signalId) => `signals:${symbol}:${signalId}`,
557
+ signalsBySymbol: (symbol) => `signals:${symbol}:`,
558
+ storeSignal: (symbol, signalId) => `store:signals:${symbol}:${signalId}`,
559
+ runtimeSignals: (userName) => `users:${userName}:runtime:signals:`,
560
+ runtimeSignal: (userName, signalId) => `users:${userName}:runtime:signals:${signalId}`,
561
+ runtimeSignalEvaluations: (userName) => `users:${userName}:runtime:signal-evaluations:`,
562
+ runtimeSignalEvaluation: (userName, evaluationId) => `users:${userName}:runtime:signal-evaluations:${evaluationId}`,
563
+ runtimeTrades: (userName) => `users:${userName}:runtime:trade-records:`,
564
+ runtimeTrade: (userName, orderId) => `users:${userName}:runtime:trade-records:${orderId}`,
565
+ runtimeActiveTrades: (userName) => `users:${userName}:runtime:active-trades:`,
566
+ runtimeActiveTrade: (userName, symbol) => `users:${userName}:runtime:active-trades:${symbol}`,
567
+ aiChatHistory: (userName, symbolKey) => `users:${userName}:ai:chats:${symbolKey}`,
568
+ analysis: (symbol, signalId) => `analysis:${symbol}:${signalId}`,
569
+ screenshotSessionToken: (token) => `auth:screenshot:${token}`,
570
+ backtestResults: (userName, config, timestamp) => `users:${userName}:backtests:results:${config}:${timestamp}`,
571
+ researchRuns: (userName) => `users:${userName}:research:runs:`,
572
+ researchRun: (userName, runId) => `users:${userName}:research:runs:${runId}`,
573
+ researchLatestRun: (userName, strategyName) => `users:${userName}:research:latest:${strategyName}`,
574
+ mlSignalsByStrategy: (strategyName) => `ml:${strategyName}:signals:`,
575
+ mlSignals: () => "ml:",
576
+ mlSignal: (strategyName, signalId) => `ml:${strategyName}:signals:${signalId}`,
577
+ mlResultsByStrategy: (strategyName) => `ml:${strategyName}:results:`,
578
+ mlResults: () => "ml:",
579
+ mlResult: (strategyName, signalId) => `ml:${strategyName}:results:${signalId}`
580
+ };
581
+
582
+ // src/userSettings.ts
583
+ var readString = (value) => typeof value === "string" ? value.trim() : "";
584
+ var readUserString = (record, key) => readString(record?.[key]);
585
+ var getUserRecord = async (userName) => {
586
+ const user = await getData(redisKeys.user(userName), null);
587
+ if (!user || typeof user !== "object") {
588
+ return null;
589
+ }
590
+ return user;
591
+ };
592
+ var getUserSettings = async (userName) => {
593
+ const record = await getUserRecord(userName);
594
+ const aiApiEndpoint = normalizeAiEndpoint(
595
+ readUserString(record, "AI_API_ENDPOINT")
596
+ );
597
+ return {
598
+ userName,
599
+ BYBIT_API_KEY: readUserString(record, "BYBIT_API_KEY"),
600
+ BYBIT_API_SECRET: readUserString(record, "BYBIT_API_SECRET"),
601
+ COINALYZE_API_KEY: readUserString(record, "COINALYZE_API_KEY"),
602
+ AI_API_KEY: readUserString(record, "AI_API_KEY"),
603
+ AI_API_ENDPOINT: aiApiEndpoint,
604
+ AI_MODEL: normalizeAiModel(
605
+ readUserString(record, "AI_MODEL"),
606
+ aiApiEndpoint
607
+ ),
608
+ AI_RESPONSE_LANGUAGE: normalizeAiResponseLanguage(
609
+ readUserString(record, "AI_RESPONSE_LANGUAGE")
610
+ ) || DEFAULT_AI_RESPONSE_LANGUAGE,
611
+ TG_BOT_TOKEN: readUserString(record, "TG_BOT_TOKEN"),
612
+ TG_CHAT_ID: readUserString(record, "TG_CHAT_ID")
613
+ };
614
+ };
615
+ var updateUserRecord = async (userName, patch) => {
616
+ const existing = await getUserRecord(userName) ?? {};
617
+ const merged = {
618
+ ...existing,
619
+ ...patch,
620
+ userName,
621
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
622
+ };
623
+ const next = Object.fromEntries(
624
+ Object.entries(merged).filter(([, value]) => value !== void 0)
625
+ );
626
+ await setData(redisKeys.user(userName), next, {
627
+ expire: 0
628
+ });
629
+ return next;
630
+ };
631
+ // Annotate the CommonJS export names for ESM import in node:
632
+ 0 && (module.exports = {
633
+ getUserRecord,
634
+ getUserSettings,
635
+ updateUserRecord
636
+ });