mtranserver 4.0.22 → 4.0.24

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/dist/index.js CHANGED
@@ -47,11 +47,33 @@ var __require = /* @__PURE__ */ createRequire(import.meta.url);
47
47
  var exports_config = {};
48
48
  __export(exports_config, {
49
49
  setConfig: () => setConfig,
50
- getConfig: () => getConfig
50
+ saveConfigFile: () => saveConfigFile,
51
+ resetConfig: () => resetConfig,
52
+ getConfig: () => getConfig,
53
+ clearConfigFile: () => clearConfigFile
51
54
  });
52
55
  import fs from "fs";
53
56
  import os from "os";
54
57
  import path from "path";
58
+ function getConfigFilePath(homeDir) {
59
+ return path.join(homeDir, "server.json");
60
+ }
61
+ function readConfigFile(homeDir) {
62
+ if (fileConfigCache)
63
+ return fileConfigCache;
64
+ const configPath = getConfigFilePath(homeDir);
65
+ try {
66
+ const raw = fs.readFileSync(configPath, "utf8");
67
+ const parsed = JSON.parse(raw);
68
+ if (parsed && typeof parsed === "object") {
69
+ fileConfigCache = parsed;
70
+ return fileConfigCache;
71
+ }
72
+ } catch {
73
+ return {};
74
+ }
75
+ return {};
76
+ }
55
77
  function getArgValue(flag) {
56
78
  const index = process.argv.indexOf(flag);
57
79
  if (index > -1 && index + 1 < process.argv.length) {
@@ -108,30 +130,31 @@ function getConfig() {
108
130
  return globalConfig;
109
131
  }
110
132
  const homeDir = path.join(os.homedir(), ".config", "mtran");
111
- const configDir = getString("--config-dir", "MT_CONFIG_DIR", path.join(homeDir, "server"));
133
+ const fileConfig = readConfigFile(homeDir);
134
+ const configDir = getString("--config-dir", "MT_CONFIG_DIR", fileConfig.configDir || path.join(homeDir, "server"));
112
135
  const localModelsDir = path.join(process.cwd(), "models");
113
136
  const defaultModelDir = fs.existsSync(localModelsDir) ? localModelsDir : path.join(homeDir, "models");
114
- const modelDir = getString("--model-dir", "MT_MODEL_DIR", defaultModelDir);
115
- const logDir = getString("--log-dir", "MT_LOG_DIR", path.join(homeDir, "logs"));
137
+ const modelDir = getString("--model-dir", "MT_MODEL_DIR", fileConfig.modelDir || defaultModelDir);
138
+ const logDir = getString("--log-dir", "MT_LOG_DIR", fileConfig.logDir || path.join(homeDir, "logs"));
116
139
  globalConfig = {
117
140
  homeDir,
118
141
  configDir,
119
142
  modelDir,
120
143
  logDir,
121
- logLevel: getString("--log-level", "MT_LOG_LEVEL", "warn"),
122
- host: getString("--host", "MT_HOST", "0.0.0.0"),
123
- port: getString("--port", "MT_PORT", "8989"),
124
- enableWebUI: getBool("--ui", "MT_ENABLE_UI", true),
125
- enableOfflineMode: getBool("--offline", "MT_OFFLINE", false),
126
- workerIdleTimeout: getInt("--worker-idle-timeout", "MT_WORKER_IDLE_TIMEOUT", 60),
127
- workersPerLanguage: getInt("--workers-per-language", "MT_WORKERS_PER_LANGUAGE", 1),
128
- maxLengthBreak: getInt("--max-length-break", "MT_MAX_LENGTH_BREAK", 128),
129
- apiToken: getString("--api-token", "MT_API_TOKEN", ""),
130
- logToFile: getBool("--log-to-file", "MT_LOG_TO_FILE", false),
131
- logConsole: getBool("--log-console", "MT_LOG_CONSOLE", true),
132
- logRequests: getBool("--log-requests", "MT_LOG_REQUESTS", false),
133
- checkUpdate: getBool("--check-update", "MT_CHECK_UPDATE", true),
134
- cacheSize: getInt("--cache-size", "MT_CACHE_SIZE", 1000)
144
+ logLevel: getString("--log-level", "MT_LOG_LEVEL", fileConfig.logLevel || "warn"),
145
+ host: getString("--host", "MT_HOST", fileConfig.host || "0.0.0.0"),
146
+ port: getString("--port", "MT_PORT", fileConfig.port || "8989"),
147
+ enableWebUI: getBool("--ui", "MT_ENABLE_UI", fileConfig.enableWebUI ?? true),
148
+ enableOfflineMode: getBool("--offline", "MT_OFFLINE", fileConfig.enableOfflineMode ?? false),
149
+ workerIdleTimeout: getInt("--worker-idle-timeout", "MT_WORKER_IDLE_TIMEOUT", fileConfig.workerIdleTimeout ?? 60),
150
+ workersPerLanguage: getInt("--workers-per-language", "MT_WORKERS_PER_LANGUAGE", fileConfig.workersPerLanguage ?? 1),
151
+ maxLengthBreak: getInt("--max-length-break", "MT_MAX_LENGTH_BREAK", fileConfig.maxLengthBreak ?? 128),
152
+ apiToken: getString("--api-token", "MT_API_TOKEN", fileConfig.apiToken || ""),
153
+ logToFile: getBool("--log-to-file", "MT_LOG_TO_FILE", fileConfig.logToFile ?? false),
154
+ logConsole: getBool("--log-console", "MT_LOG_CONSOLE", fileConfig.logConsole ?? true),
155
+ logRequests: getBool("--log-requests", "MT_LOG_REQUESTS", fileConfig.logRequests ?? false),
156
+ checkUpdate: getBool("--check-update", "MT_CHECK_UPDATE", fileConfig.checkUpdate ?? true),
157
+ cacheSize: getInt("--cache-size", "MT_CACHE_SIZE", fileConfig.cacheSize ?? 1000)
135
158
  };
136
159
  return globalConfig;
137
160
  }
@@ -139,617 +162,31 @@ function setConfig(config) {
139
162
  const current = getConfig();
140
163
  globalConfig = { ...current, ...config };
141
164
  }
142
- var globalConfig = null;
143
- var init_config = () => {};
144
-
145
- // node_modules/fzstd/esm/index.mjs
146
- function decompress(dat, buf) {
147
- var bufs = [], nb = +!buf;
148
- var bt = 0, ol = 0;
149
- for (;dat.length; ) {
150
- var st = rzfh(dat, nb || buf);
151
- if (typeof st == "object") {
152
- if (nb) {
153
- buf = null;
154
- if (st.w.length == st.u) {
155
- bufs.push(buf = st.w);
156
- ol += st.u;
157
- }
158
- } else {
159
- bufs.push(buf);
160
- st.e = 0;
161
- }
162
- for (;!st.l; ) {
163
- var blk = rzb(dat, st, buf);
164
- if (!blk)
165
- err(5);
166
- if (buf)
167
- st.e = st.y;
168
- else {
169
- bufs.push(blk);
170
- ol += blk.length;
171
- cpw(st.w, 0, blk.length);
172
- st.w.set(blk, st.w.length - blk.length);
173
- }
174
- }
175
- bt = st.b + st.c * 4;
176
- } else
177
- bt = st;
178
- dat = dat.subarray(bt);
179
- }
180
- return cct(bufs, ol);
165
+ function resetConfig() {
166
+ globalConfig = null;
167
+ fileConfigCache = null;
181
168
  }
182
- var ab, u8, u16, i16, i32, slc = function(v, s, e) {
183
- if (u8.prototype.slice)
184
- return u8.prototype.slice.call(v, s, e);
185
- if (s == null || s < 0)
186
- s = 0;
187
- if (e == null || e > v.length)
188
- e = v.length;
189
- var n = new u8(e - s);
190
- n.set(v.subarray(s, e));
191
- return n;
192
- }, fill = function(v, n, s, e) {
193
- if (u8.prototype.fill)
194
- return u8.prototype.fill.call(v, n, s, e);
195
- if (s == null || s < 0)
196
- s = 0;
197
- if (e == null || e > v.length)
198
- e = v.length;
199
- for (;s < e; ++s)
200
- v[s] = n;
201
- return v;
202
- }, cpw = function(v, t, s, e) {
203
- if (u8.prototype.copyWithin)
204
- return u8.prototype.copyWithin.call(v, t, s, e);
205
- if (s == null || s < 0)
206
- s = 0;
207
- if (e == null || e > v.length)
208
- e = v.length;
209
- while (s < e) {
210
- v[t++] = v[s++];
211
- }
212
- }, ec, err = function(ind, msg, nt) {
213
- var e = new Error(msg || ec[ind]);
214
- e.code = ind;
215
- if (Error.captureStackTrace)
216
- Error.captureStackTrace(e, err);
217
- if (!nt)
218
- throw e;
219
- return e;
220
- }, rb = function(d, b, n) {
221
- var i = 0, o = 0;
222
- for (;i < n; ++i)
223
- o |= d[b++] << (i << 3);
224
- return o;
225
- }, b4 = function(d, b) {
226
- return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
227
- }, rzfh = function(dat, w) {
228
- var n3 = dat[0] | dat[1] << 8 | dat[2] << 16;
229
- if (n3 == 3126568 && dat[3] == 253) {
230
- var flg = dat[4];
231
- var ss = flg >> 5 & 1, cc = flg >> 2 & 1, df = flg & 3, fcf = flg >> 6;
232
- if (flg & 8)
233
- err(0);
234
- var bt = 6 - ss;
235
- var db = df == 3 ? 4 : df;
236
- var di = rb(dat, bt, db);
237
- bt += db;
238
- var fsb = fcf ? 1 << fcf : ss;
239
- var fss = rb(dat, bt, fsb) + (fcf == 1 && 256);
240
- var ws = fss;
241
- if (!ss) {
242
- var wb = 1 << 10 + (dat[5] >> 3);
243
- ws = wb + (wb >> 3) * (dat[5] & 7);
244
- }
245
- if (ws > 2145386496)
246
- err(1);
247
- var buf = new u8((w == 1 ? fss || ws : w ? 0 : ws) + 12);
248
- buf[0] = 1, buf[4] = 4, buf[8] = 8;
249
- return {
250
- b: bt + fsb,
251
- y: 0,
252
- l: 0,
253
- d: di,
254
- w: w && w != 1 ? w : buf.subarray(12),
255
- e: ws,
256
- o: new i32(buf.buffer, 0, 3),
257
- u: fss,
258
- c: cc,
259
- m: Math.min(131072, ws)
260
- };
261
- } else if ((n3 >> 4 | dat[3] << 20) == 25481893) {
262
- return b4(dat, 4) + 8;
263
- }
264
- err(0);
265
- }, msb = function(val) {
266
- var bits = 0;
267
- for (;1 << bits <= val; ++bits)
268
- ;
269
- return bits - 1;
270
- }, rfse = function(dat, bt, mal) {
271
- var tpos = (bt << 3) + 4;
272
- var al = (dat[bt] & 15) + 5;
273
- if (al > mal)
274
- err(3);
275
- var sz = 1 << al;
276
- var probs = sz, sym = -1, re = -1, i = -1, ht = sz;
277
- var buf = new ab(512 + (sz << 2));
278
- var freq = new i16(buf, 0, 256);
279
- var dstate = new u16(buf, 0, 256);
280
- var nstate = new u16(buf, 512, sz);
281
- var bb1 = 512 + (sz << 1);
282
- var syms = new u8(buf, bb1, sz);
283
- var nbits = new u8(buf, bb1 + sz);
284
- while (sym < 255 && probs > 0) {
285
- var bits = msb(probs + 1);
286
- var cbt = tpos >> 3;
287
- var msk = (1 << bits + 1) - 1;
288
- var val = (dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16) >> (tpos & 7) & msk;
289
- var msk1fb = (1 << bits) - 1;
290
- var msv = msk - probs - 1;
291
- var sval = val & msk1fb;
292
- if (sval < msv)
293
- tpos += bits, val = sval;
294
- else {
295
- tpos += bits + 1;
296
- if (val > msk1fb)
297
- val -= msv;
298
- }
299
- freq[++sym] = --val;
300
- if (val == -1) {
301
- probs += val;
302
- syms[--ht] = sym;
303
- } else
304
- probs -= val;
305
- if (!val) {
306
- do {
307
- var rbt = tpos >> 3;
308
- re = (dat[rbt] | dat[rbt + 1] << 8) >> (tpos & 7) & 3;
309
- tpos += 2;
310
- sym += re;
311
- } while (re == 3);
312
- }
313
- }
314
- if (sym > 255 || probs)
315
- err(0);
316
- var sympos = 0;
317
- var sstep = (sz >> 1) + (sz >> 3) + 3;
318
- var smask = sz - 1;
319
- for (var s = 0;s <= sym; ++s) {
320
- var sf = freq[s];
321
- if (sf < 1) {
322
- dstate[s] = -sf;
323
- continue;
324
- }
325
- for (i = 0;i < sf; ++i) {
326
- syms[sympos] = s;
327
- do {
328
- sympos = sympos + sstep & smask;
329
- } while (sympos >= ht);
330
- }
331
- }
332
- if (sympos)
333
- err(0);
334
- for (i = 0;i < sz; ++i) {
335
- var ns = dstate[syms[i]]++;
336
- var nb = nbits[i] = al - msb(ns);
337
- nstate[i] = (ns << nb) - sz;
338
- }
339
- return [tpos + 7 >> 3, {
340
- b: al,
341
- s: syms,
342
- n: nbits,
343
- t: nstate
344
- }];
345
- }, rhu = function(dat, bt) {
346
- var i = 0, wc = -1;
347
- var buf = new u8(292), hb = dat[bt];
348
- var hw = buf.subarray(0, 256);
349
- var rc = buf.subarray(256, 268);
350
- var ri = new u16(buf.buffer, 268);
351
- if (hb < 128) {
352
- var _a = rfse(dat, bt + 1, 6), ebt = _a[0], fdt = _a[1];
353
- bt += hb;
354
- var epos = ebt << 3;
355
- var lb = dat[bt];
356
- if (!lb)
357
- err(0);
358
- var st1 = 0, st2 = 0, btr1 = fdt.b, btr2 = btr1;
359
- var fpos = (++bt << 3) - 8 + msb(lb);
360
- for (;; ) {
361
- fpos -= btr1;
362
- if (fpos < epos)
363
- break;
364
- var cbt = fpos >> 3;
365
- st1 += (dat[cbt] | dat[cbt + 1] << 8) >> (fpos & 7) & (1 << btr1) - 1;
366
- hw[++wc] = fdt.s[st1];
367
- fpos -= btr2;
368
- if (fpos < epos)
369
- break;
370
- cbt = fpos >> 3;
371
- st2 += (dat[cbt] | dat[cbt + 1] << 8) >> (fpos & 7) & (1 << btr2) - 1;
372
- hw[++wc] = fdt.s[st2];
373
- btr1 = fdt.n[st1];
374
- st1 = fdt.t[st1];
375
- btr2 = fdt.n[st2];
376
- st2 = fdt.t[st2];
377
- }
378
- if (++wc > 255)
379
- err(0);
380
- } else {
381
- wc = hb - 127;
382
- for (;i < wc; i += 2) {
383
- var byte = dat[++bt];
384
- hw[i] = byte >> 4;
385
- hw[i + 1] = byte & 15;
386
- }
387
- ++bt;
388
- }
389
- var wes = 0;
390
- for (i = 0;i < wc; ++i) {
391
- var wt = hw[i];
392
- if (wt > 11)
393
- err(0);
394
- wes += wt && 1 << wt - 1;
395
- }
396
- var mb = msb(wes) + 1;
397
- var ts = 1 << mb;
398
- var rem = ts - wes;
399
- if (rem & rem - 1)
400
- err(0);
401
- hw[wc++] = msb(rem) + 1;
402
- for (i = 0;i < wc; ++i) {
403
- var wt = hw[i];
404
- ++rc[hw[i] = wt && mb + 1 - wt];
405
- }
406
- var hbuf = new u8(ts << 1);
407
- var syms = hbuf.subarray(0, ts), nb = hbuf.subarray(ts);
408
- ri[mb] = 0;
409
- for (i = mb;i > 0; --i) {
410
- var pv = ri[i];
411
- fill(nb, i, pv, ri[i - 1] = pv + rc[i] * (1 << mb - i));
412
- }
413
- if (ri[0] != ts)
414
- err(0);
415
- for (i = 0;i < wc; ++i) {
416
- var bits = hw[i];
417
- if (bits) {
418
- var code = ri[bits];
419
- fill(syms, i, code, ri[bits] = code + (1 << mb - bits));
420
- }
421
- }
422
- return [bt, {
423
- n: nb,
424
- b: mb,
425
- s: syms
426
- }];
427
- }, dllt, dmlt, doct, b2bl = function(b, s) {
428
- var len = b.length, bl = new i32(len);
429
- for (var i = 0;i < len; ++i) {
430
- bl[i] = s;
431
- s += 1 << b[i];
432
- }
433
- return bl;
434
- }, llb, llbl, mlb, mlbl, dhu = function(dat, out, hu) {
435
- var len = dat.length, ss = out.length, lb = dat[len - 1], msk = (1 << hu.b) - 1, eb = -hu.b;
436
- if (!lb)
437
- err(0);
438
- var st = 0, btr = hu.b, pos = (len << 3) - 8 + msb(lb) - btr, i = -1;
439
- for (;pos > eb && i < ss; ) {
440
- var cbt = pos >> 3;
441
- var val = (dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16) >> (pos & 7);
442
- st = (st << btr | val) & msk;
443
- out[++i] = hu.s[st];
444
- pos -= btr = hu.n[st];
445
- }
446
- if (pos != eb || i + 1 != ss)
447
- err(0);
448
- }, dhu4 = function(dat, out, hu) {
449
- var bt = 6;
450
- var ss = out.length, sz1 = ss + 3 >> 2, sz2 = sz1 << 1, sz3 = sz1 + sz2;
451
- dhu(dat.subarray(bt, bt += dat[0] | dat[1] << 8), out.subarray(0, sz1), hu);
452
- dhu(dat.subarray(bt, bt += dat[2] | dat[3] << 8), out.subarray(sz1, sz2), hu);
453
- dhu(dat.subarray(bt, bt += dat[4] | dat[5] << 8), out.subarray(sz2, sz3), hu);
454
- dhu(dat.subarray(bt), out.subarray(sz3), hu);
455
- }, rzb = function(dat, st, out) {
456
- var _a;
457
- var bt = st.b;
458
- var b0 = dat[bt], btype = b0 >> 1 & 3;
459
- st.l = b0 & 1;
460
- var sz = b0 >> 3 | dat[bt + 1] << 5 | dat[bt + 2] << 13;
461
- var ebt = (bt += 3) + sz;
462
- if (btype == 1) {
463
- if (bt >= dat.length)
464
- return;
465
- st.b = bt + 1;
466
- if (out) {
467
- fill(out, dat[bt], st.y, st.y += sz);
468
- return out;
169
+ function saveConfigFile(config) {
170
+ const current = getConfig();
171
+ const next = { ...current, ...config };
172
+ const configPath = getConfigFilePath(current.homeDir);
173
+ fs.mkdirSync(current.homeDir, { recursive: true });
174
+ fs.writeFileSync(configPath, JSON.stringify(next, null, 2), "utf8");
175
+ fileConfigCache = next;
176
+ }
177
+ function clearConfigFile() {
178
+ const homeDir = path.join(os.homedir(), ".config", "mtran");
179
+ const configPath = getConfigFilePath(homeDir);
180
+ try {
181
+ if (fs.existsSync(configPath)) {
182
+ fs.unlinkSync(configPath);
469
183
  }
470
- return fill(new u8(sz), dat[bt]);
471
- }
472
- if (ebt > dat.length)
184
+ } catch {
473
185
  return;
474
- if (btype == 0) {
475
- st.b = ebt;
476
- if (out) {
477
- out.set(dat.subarray(bt, ebt), st.y);
478
- st.y += sz;
479
- return out;
480
- }
481
- return slc(dat, bt, ebt);
482
- }
483
- if (btype == 2) {
484
- var b3 = dat[bt], lbt = b3 & 3, sf = b3 >> 2 & 3;
485
- var lss = b3 >> 4, lcs = 0, s4 = 0;
486
- if (lbt < 2) {
487
- if (sf & 1)
488
- lss |= dat[++bt] << 4 | (sf & 2 && dat[++bt] << 12);
489
- else
490
- lss = b3 >> 3;
491
- } else {
492
- s4 = sf;
493
- if (sf < 2)
494
- lss |= (dat[++bt] & 63) << 4, lcs = dat[bt] >> 6 | dat[++bt] << 2;
495
- else if (sf == 2)
496
- lss |= dat[++bt] << 4 | (dat[++bt] & 3) << 12, lcs = dat[bt] >> 2 | dat[++bt] << 6;
497
- else
498
- lss |= dat[++bt] << 4 | (dat[++bt] & 63) << 12, lcs = dat[bt] >> 6 | dat[++bt] << 2 | dat[++bt] << 10;
499
- }
500
- ++bt;
501
- var buf = out ? out.subarray(st.y, st.y + st.m) : new u8(st.m);
502
- var spl = buf.length - lss;
503
- if (lbt == 0)
504
- buf.set(dat.subarray(bt, bt += lss), spl);
505
- else if (lbt == 1)
506
- fill(buf, dat[bt++], spl);
507
- else {
508
- var hu = st.h;
509
- if (lbt == 2) {
510
- var hud = rhu(dat, bt);
511
- lcs += bt - (bt = hud[0]);
512
- st.h = hu = hud[1];
513
- } else if (!hu)
514
- err(0);
515
- (s4 ? dhu4 : dhu)(dat.subarray(bt, bt += lcs), buf.subarray(spl), hu);
516
- }
517
- var ns = dat[bt++];
518
- if (ns) {
519
- if (ns == 255)
520
- ns = (dat[bt++] | dat[bt++] << 8) + 32512;
521
- else if (ns > 127)
522
- ns = ns - 128 << 8 | dat[bt++];
523
- var scm = dat[bt++];
524
- if (scm & 3)
525
- err(0);
526
- var dts = [dmlt, doct, dllt];
527
- for (var i = 2;i > -1; --i) {
528
- var md = scm >> (i << 1) + 2 & 3;
529
- if (md == 1) {
530
- var rbuf = new u8([0, 0, dat[bt++]]);
531
- dts[i] = {
532
- s: rbuf.subarray(2, 3),
533
- n: rbuf.subarray(0, 1),
534
- t: new u16(rbuf.buffer, 0, 1),
535
- b: 0
536
- };
537
- } else if (md == 2) {
538
- _a = rfse(dat, bt, 9 - (i & 1)), bt = _a[0], dts[i] = _a[1];
539
- } else if (md == 3) {
540
- if (!st.t)
541
- err(0);
542
- dts[i] = st.t[i];
543
- }
544
- }
545
- var _b = st.t = dts, mlt = _b[0], oct = _b[1], llt = _b[2];
546
- var lb = dat[ebt - 1];
547
- if (!lb)
548
- err(0);
549
- var spos = (ebt << 3) - 8 + msb(lb) - llt.b, cbt = spos >> 3, oubt = 0;
550
- var lst = (dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << llt.b) - 1;
551
- cbt = (spos -= oct.b) >> 3;
552
- var ost = (dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << oct.b) - 1;
553
- cbt = (spos -= mlt.b) >> 3;
554
- var mst = (dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << mlt.b) - 1;
555
- for (++ns;--ns; ) {
556
- var llc = llt.s[lst];
557
- var lbtr = llt.n[lst];
558
- var mlc = mlt.s[mst];
559
- var mbtr = mlt.n[mst];
560
- var ofc = oct.s[ost];
561
- var obtr = oct.n[ost];
562
- cbt = (spos -= ofc) >> 3;
563
- var ofp = 1 << ofc;
564
- var off = ofp + ((dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16 | dat[cbt + 3] << 24) >>> (spos & 7) & ofp - 1);
565
- cbt = (spos -= mlb[mlc]) >> 3;
566
- var ml = mlbl[mlc] + ((dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16) >> (spos & 7) & (1 << mlb[mlc]) - 1);
567
- cbt = (spos -= llb[llc]) >> 3;
568
- var ll = llbl[llc] + ((dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16) >> (spos & 7) & (1 << llb[llc]) - 1);
569
- cbt = (spos -= lbtr) >> 3;
570
- lst = llt.t[lst] + ((dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << lbtr) - 1);
571
- cbt = (spos -= mbtr) >> 3;
572
- mst = mlt.t[mst] + ((dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << mbtr) - 1);
573
- cbt = (spos -= obtr) >> 3;
574
- ost = oct.t[ost] + ((dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << obtr) - 1);
575
- if (off > 3) {
576
- st.o[2] = st.o[1];
577
- st.o[1] = st.o[0];
578
- st.o[0] = off -= 3;
579
- } else {
580
- var idx = off - (ll != 0);
581
- if (idx) {
582
- off = idx == 3 ? st.o[0] - 1 : st.o[idx];
583
- if (idx > 1)
584
- st.o[2] = st.o[1];
585
- st.o[1] = st.o[0];
586
- st.o[0] = off;
587
- } else
588
- off = st.o[0];
589
- }
590
- for (var i = 0;i < ll; ++i) {
591
- buf[oubt + i] = buf[spl + i];
592
- }
593
- oubt += ll, spl += ll;
594
- var stin = oubt - off;
595
- if (stin < 0) {
596
- var len = -stin;
597
- var bs = st.e + stin;
598
- if (len > ml)
599
- len = ml;
600
- for (var i = 0;i < len; ++i) {
601
- buf[oubt + i] = st.w[bs + i];
602
- }
603
- oubt += len, ml -= len, stin = 0;
604
- }
605
- for (var i = 0;i < ml; ++i) {
606
- buf[oubt + i] = buf[stin + i];
607
- }
608
- oubt += ml;
609
- }
610
- if (oubt != spl) {
611
- while (spl < buf.length) {
612
- buf[oubt++] = buf[spl++];
613
- }
614
- } else
615
- oubt = buf.length;
616
- if (out)
617
- st.y += oubt;
618
- else
619
- buf = slc(buf, 0, oubt);
620
- } else if (out) {
621
- st.y += lss;
622
- if (spl) {
623
- for (var i = 0;i < lss; ++i) {
624
- buf[i] = buf[spl + i];
625
- }
626
- }
627
- } else if (spl)
628
- buf = slc(buf, spl);
629
- st.b = ebt;
630
- return buf;
631
- }
632
- err(2);
633
- }, cct = function(bufs, ol) {
634
- if (bufs.length == 1)
635
- return bufs[0];
636
- var buf = new u8(ol);
637
- for (var i = 0, b = 0;i < bufs.length; ++i) {
638
- var chk = bufs[i];
639
- buf.set(chk, b);
640
- b += chk.length;
641
186
  }
642
- return buf;
643
- };
644
- var init_esm = __esm(() => {
645
- ab = ArrayBuffer;
646
- u8 = Uint8Array;
647
- u16 = Uint16Array;
648
- i16 = Int16Array;
649
- i32 = Int32Array;
650
- ec = [
651
- "invalid zstd data",
652
- "window size too large (>2046MB)",
653
- "invalid block type",
654
- "FSE accuracy too high",
655
- "match distance too far back",
656
- "unexpected EOF"
657
- ];
658
- dllt = rfse(/* @__PURE__ */ new u8([
659
- 81,
660
- 16,
661
- 99,
662
- 140,
663
- 49,
664
- 198,
665
- 24,
666
- 99,
667
- 12,
668
- 33,
669
- 196,
670
- 24,
671
- 99,
672
- 102,
673
- 102,
674
- 134,
675
- 70,
676
- 146,
677
- 4
678
- ]), 0, 6)[1];
679
- dmlt = rfse(/* @__PURE__ */ new u8([
680
- 33,
681
- 20,
682
- 196,
683
- 24,
684
- 99,
685
- 140,
686
- 33,
687
- 132,
688
- 16,
689
- 66,
690
- 8,
691
- 33,
692
- 132,
693
- 16,
694
- 66,
695
- 8,
696
- 33,
697
- 68,
698
- 68,
699
- 68,
700
- 68,
701
- 68,
702
- 68,
703
- 68,
704
- 68,
705
- 36,
706
- 9
707
- ]), 0, 6)[1];
708
- doct = rfse(/* @__PURE__ */ new u8([
709
- 32,
710
- 132,
711
- 16,
712
- 66,
713
- 102,
714
- 70,
715
- 68,
716
- 68,
717
- 68,
718
- 68,
719
- 36,
720
- 73,
721
- 2
722
- ]), 0, 5)[1];
723
- llb = /* @__PURE__ */ new u8((/* @__PURE__ */ new i32([
724
- 0,
725
- 0,
726
- 0,
727
- 0,
728
- 16843009,
729
- 50528770,
730
- 134678020,
731
- 202050057,
732
- 269422093
733
- ])).buffer, 0, 36);
734
- llbl = /* @__PURE__ */ b2bl(llb, 0);
735
- mlb = /* @__PURE__ */ new u8((/* @__PURE__ */ new i32([
736
- 0,
737
- 0,
738
- 0,
739
- 0,
740
- 0,
741
- 0,
742
- 0,
743
- 0,
744
- 16843009,
745
- 50528770,
746
- 117769220,
747
- 185207048,
748
- 252579084,
749
- 16
750
- ])).buffer, 0, 53);
751
- mlbl = /* @__PURE__ */ b2bl(mlb, 3);
752
- });
187
+ }
188
+ var globalConfig = null, fileConfigCache = null;
189
+ var init_config = () => {};
753
190
 
754
191
  // src/logger/index.ts
755
192
  var exports_logger = {};
@@ -796,8 +233,8 @@ function getLogStream() {
796
233
  if (!fs2.existsSync(config.logDir)) {
797
234
  try {
798
235
  fs2.mkdirSync(config.logDir, { recursive: true });
799
- } catch (err2) {
800
- console.error(`Failed to create log directory: ${config.logDir}`, err2);
236
+ } catch (err) {
237
+ console.error(`Failed to create log directory: ${config.logDir}`, err);
801
238
  return null;
802
239
  }
803
240
  }
@@ -805,8 +242,8 @@ function getLogStream() {
805
242
  try {
806
243
  logStream = fs2.createWriteStream(logPath, { flags: "a" });
807
244
  currentLogDate = today;
808
- } catch (err2) {
809
- console.error(`Failed to create log stream: ${logPath}`, err2);
245
+ } catch (err) {
246
+ console.error(`Failed to create log stream: ${logPath}`, err);
810
247
  return null;
811
248
  }
812
249
  }
@@ -942,6 +379,7 @@ var init_loader = __esm(() => {
942
379
  // src/core/factory.ts
943
380
  import fs3 from "fs/promises";
944
381
  import path3 from "path";
382
+ import { decompress } from "fzstd";
945
383
 
946
384
  class Downloader {
947
385
  timeout;
@@ -1008,7 +446,6 @@ function createResourceLoader() {
1008
446
  return new ResourceLoader(new NodeFileSystem);
1009
447
  }
1010
448
  var init_factory = __esm(() => {
1011
- init_esm();
1012
449
  init_loader();
1013
450
  });
1014
451
 
@@ -1085,8 +522,8 @@ async function initRecords() {
1085
522
  if (globalRecords) {
1086
523
  debug(`Loaded ${globalRecords.data.length} model records`);
1087
524
  }
1088
- } catch (err2) {
1089
- throw new Error(`Failed to load records in offline mode: ${err2}`);
525
+ } catch (err) {
526
+ throw new Error(`Failed to load records in offline mode: ${err}`);
1090
527
  }
1091
528
  return;
1092
529
  }
@@ -1102,9 +539,9 @@ async function initRecords() {
1102
539
  if (globalRecords) {
1103
540
  debug(`Loaded ${globalRecords.data.length} model records`);
1104
541
  }
1105
- } catch (err2) {
1106
- warn(`Failed to download records.json: ${err2}`);
1107
- throw err2;
542
+ } catch (err) {
543
+ warn(`Failed to download records.json: ${err}`);
544
+ throw err;
1108
545
  }
1109
546
  }
1110
547
  async function downloadModel(toLang, fromLang, version) {
@@ -1338,6 +775,9 @@ class TranslationEngine {
1338
775
  text = text.replace(/<([^a-zA-Z/!?][^>]*)>/g, "&lt;$1&gt;");
1339
776
  const unclosedTags = /<([a-zA-Z]+)(?:\s[^>]*)?>(?![\s\S]*<\/\1>)/g;
1340
777
  text = text.replace(unclosedTags, (match) => {
778
+ if (match.endsWith("/>")) {
779
+ return match;
780
+ }
1341
781
  return match.replace(/</g, "&lt;").replace(/>/g, "&gt;");
1342
782
  });
1343
783
  return text;
@@ -1474,7 +914,7 @@ class TranslationEngine {
1474
914
  const emojiRegex = /(\p{RI}\p{RI}|\p{Emoji_Presentation}|\p{Extended_Pictographic})/gu;
1475
915
  const replacements = [];
1476
916
  const cleanText = text.replace(emojiRegex, (match) => {
1477
- const placeholder = `<e${replacements.length}>`;
917
+ const placeholder = `[EE${replacements.length}]`;
1478
918
  replacements.push({ original: match, placeholder });
1479
919
  return placeholder;
1480
920
  });
@@ -1482,8 +922,10 @@ class TranslationEngine {
1482
922
  }
1483
923
  _restoreEmojis(text, replacements) {
1484
924
  let result = text;
1485
- for (const { original, placeholder } of replacements) {
1486
- result = result.split(placeholder).join(original);
925
+ for (let i = 0;i < replacements.length; i++) {
926
+ const { original } = replacements[i];
927
+ const pattern = new RegExp(`\\[EE${i}\\]`, "gi");
928
+ result = result.replace(pattern, original);
1487
929
  }
1488
930
  return result;
1489
931
  }
@@ -1496,7 +938,7 @@ class TranslationEngine {
1496
938
  const taggedText = text.replace(placeholderRegex, (match) => {
1497
939
  const index = replacements.length;
1498
940
  replacements.push(match);
1499
- return `<br data-mt="${index}">`;
941
+ return `<mt${index} />`;
1500
942
  });
1501
943
  return { taggedText, replacements, forceHtml: !htmlEnabled };
1502
944
  }
@@ -1505,7 +947,8 @@ class TranslationEngine {
1505
947
  return text;
1506
948
  }
1507
949
  let result = text;
1508
- result = result.replace(/<br\s+data-mt="(\d+)"\s*\/?>/gi, (_, index) => {
950
+ result = result.replace(/<\/mt\d+>/gi, "");
951
+ result = result.replace(/<mt(\d+)\s*\/?>/gi, (_, index) => {
1509
952
  const idx = Number(index);
1510
953
  return replacements[idx] ?? _;
1511
954
  });
@@ -1595,7 +1038,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
1595
1038
  setWindowTitle = (title) => document.title = title;
1596
1039
  } else {}
1597
1040
  var out = Module.print || console.log.bind(console);
1598
- var err2 = Module.printErr || console.warn.bind(console);
1041
+ var err = Module.printErr || console.warn.bind(console);
1599
1042
  Object.assign(Module, moduleOverrides);
1600
1043
  moduleOverrides = null;
1601
1044
  if (Module.arguments) {
@@ -1986,7 +1429,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
1986
1429
  }
1987
1430
  }
1988
1431
  what = "Aborted(" + what + ")";
1989
- err2(what);
1432
+ err(what);
1990
1433
  ABORT = true;
1991
1434
  EXITSTATUS = 1;
1992
1435
  what += ". Build with -s ASSERTIONS=1 for more info.";
@@ -2011,8 +1454,8 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2011
1454
  return readBinary(file);
2012
1455
  }
2013
1456
  throw "both async and sync fetching of the wasm failed";
2014
- } catch (err3) {
2015
- abort(err3);
1457
+ } catch (err2) {
1458
+ abort(err2);
2016
1459
  }
2017
1460
  }
2018
1461
  function getBinaryPromise() {
@@ -2060,7 +1503,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2060
1503
  }).then(function(instance) {
2061
1504
  return instance;
2062
1505
  }).then(receiver, function(reason) {
2063
- err2("failed to asynchronously prepare wasm: " + reason);
1506
+ err("failed to asynchronously prepare wasm: " + reason);
2064
1507
  abort(reason);
2065
1508
  });
2066
1509
  }
@@ -2071,8 +1514,8 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2071
1514
  }).then(function(response) {
2072
1515
  var result = WebAssembly.instantiateStreaming(response, info2);
2073
1516
  return result.then(receiveInstantiationResult, function(reason) {
2074
- err2("wasm streaming compile failed: " + reason);
2075
- err2("falling back to ArrayBuffer instantiation");
1517
+ err("wasm streaming compile failed: " + reason);
1518
+ err("falling back to ArrayBuffer instantiation");
2076
1519
  return instantiateArrayBuffer(receiveInstantiationResult);
2077
1520
  });
2078
1521
  });
@@ -2084,7 +1527,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2084
1527
  var exports2 = Module.instantiateWasm(info2, receiveInstance);
2085
1528
  return exports2;
2086
1529
  } catch (e) {
2087
- err2("Module.instantiateWasm callback failed with error: " + e);
1530
+ err("Module.instantiateWasm callback failed with error: " + e);
2088
1531
  return false;
2089
1532
  }
2090
1533
  }
@@ -2276,7 +1719,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2276
1719
  printChar(stream, curr) {
2277
1720
  var buffer2 = SYSCALLS.buffers[stream];
2278
1721
  if (curr === 0 || curr === 10) {
2279
- (stream === 1 ? out : err2)(UTF8ArrayToString(buffer2, 0));
1722
+ (stream === 1 ? out : err)(UTF8ArrayToString(buffer2, 0));
2280
1723
  buffer2.length = 0;
2281
1724
  } else {
2282
1725
  buffer2.push(curr);
@@ -3927,7 +3370,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
3927
3370
  return 0;
3928
3371
  }
3929
3372
  function _pclose() {
3930
- err2("missing function: pclose");
3373
+ err("missing function: pclose");
3931
3374
  abort(-1);
3932
3375
  }
3933
3376
  function _setTempRet0(val) {
@@ -4427,7 +3870,7 @@ var init_bergamot_translator = () => {};
4427
3870
 
4428
3871
  // src/lib/cld2/cld2.js
4429
3872
  var require_cld2 = __commonJS((exports, module) => {
4430
- var __dirname = "/home/xxnuo/projects/MTran/MTranServer/src/lib/cld2", __filename = "/home/xxnuo/projects/MTran/MTranServer/src/lib/cld2/cld2.js";
3873
+ var __dirname = "/Volumes/MacData/Users/xxnuo/projects/MTranServer/src/lib/cld2", __filename = "/Volumes/MacData/Users/xxnuo/projects/MTranServer/src/lib/cld2/cld2.js";
4431
3874
  var loadCLD2 = (() => {
4432
3875
  var _scriptName = globalThis.document?.currentScript?.src;
4433
3876
  return async function(moduleArg = {}) {
@@ -5098,7 +4541,7 @@ var require_cld2 = __commonJS((exports, module) => {
5098
4541
  if (E.preInit)
5099
4542
  for (typeof E.preInit == "function" && (E.preInit = [E.preInit]);0 < E.preInit.length; )
5100
4543
  E.preInit.shift()();
5101
- var Oa, Pa, Qa, Ra, Sa, Ta, Ua, Va, Wa, Xa, Ya, Za, $a, ab2, M, bb = { a: function(a, b, c) {
4544
+ var Oa, Pa, Qa, Ra, Sa, Ta, Ua, Va, Wa, Xa, Ya, Za, $a, ab, M, bb = { a: function(a, b, c) {
5102
4545
  var d = new Ga(a);
5103
4546
  L[d.B + 16 >> 2] = 0;
5104
4547
  L[d.B + 4 >> 2] = b;
@@ -5163,7 +4606,7 @@ var require_cld2 = __commonJS((exports, module) => {
5163
4606
  Ya = E._emscripten_bind_LanguageInfo_getIsReliable_0 = e.t;
5164
4607
  Za = E._emscripten_bind_LanguageInfo_getLanguageCode_0 = e.u;
5165
4608
  $a = E._emscripten_bind_LanguageInfo_get_languages_1 = e.v;
5166
- ab2 = E._emscripten_bind_LanguageInfo___destroy___0 = e.w;
4609
+ ab = E._emscripten_bind_LanguageInfo___destroy___0 = e.w;
5167
4610
  M = e.f;
5168
4611
  ya();
5169
4612
  return P;
@@ -5400,7 +4843,7 @@ var require_cld2 = __commonJS((exports, module) => {
5400
4843
  };
5401
4844
  Object.defineProperty(X.prototype, "languages", { get: X.prototype.$ });
5402
4845
  X.prototype.__destroy__ = function() {
5403
- ab2(this.B);
4846
+ ab(this.B);
5404
4847
  };
5405
4848
  S.alloc = S.alloc.bind(S);
5406
4849
  S.P = S.P.bind(S);
@@ -5908,1162 +5351,9 @@ var init_detector = __esm(() => {
5908
5351
  import_cld2 = __toESM(require_cld2(), 1);
5909
5352
  });
5910
5353
 
5911
- // node_modules/lru-cache/dist/esm/index.js
5912
- class Stack {
5913
- heap;
5914
- length;
5915
- static #constructing = false;
5916
- static create(max) {
5917
- const HeapCls = getUintArray(max);
5918
- if (!HeapCls)
5919
- return [];
5920
- Stack.#constructing = true;
5921
- const s = new Stack(max, HeapCls);
5922
- Stack.#constructing = false;
5923
- return s;
5924
- }
5925
- constructor(max, HeapCls) {
5926
- if (!Stack.#constructing) {
5927
- throw new TypeError("instantiate Stack using Stack.create(n)");
5928
- }
5929
- this.heap = new HeapCls(max);
5930
- this.length = 0;
5931
- }
5932
- push(n) {
5933
- this.heap[this.length++] = n;
5934
- }
5935
- pop() {
5936
- return this.heap[--this.length];
5937
- }
5938
- }
5939
- var defaultPerf, warned, PROCESS, emitWarning = (msg, type, code, fn) => {
5940
- typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
5941
- }, AC, AS, shouldWarn = (code) => !warned.has(code), TYPE, isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n), getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null, ZeroArray, LRUCache;
5942
- var init_esm2 = __esm(() => {
5943
- defaultPerf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
5944
- warned = new Set;
5945
- PROCESS = typeof process === "object" && !!process ? process : {};
5946
- AC = globalThis.AbortController;
5947
- AS = globalThis.AbortSignal;
5948
- if (typeof AC === "undefined") {
5949
- AS = class AbortSignal {
5950
- onabort;
5951
- _onabort = [];
5952
- reason;
5953
- aborted = false;
5954
- addEventListener(_, fn) {
5955
- this._onabort.push(fn);
5956
- }
5957
- };
5958
- AC = class AbortController2 {
5959
- constructor() {
5960
- warnACPolyfill();
5961
- }
5962
- signal = new AS;
5963
- abort(reason) {
5964
- if (this.signal.aborted)
5965
- return;
5966
- this.signal.reason = reason;
5967
- this.signal.aborted = true;
5968
- for (const fn of this.signal._onabort) {
5969
- fn(reason);
5970
- }
5971
- this.signal.onabort?.(reason);
5972
- }
5973
- };
5974
- let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
5975
- const warnACPolyfill = () => {
5976
- if (!printACPolyfillWarning)
5977
- return;
5978
- printACPolyfillWarning = false;
5979
- emitWarning("AbortController is not defined. If using lru-cache in " + "node 14, load an AbortController polyfill from the " + "`node-abort-controller` package. A minimal polyfill is " + "provided for use by LRUCache.fetch(), but it should not be " + "relied upon in other contexts (eg, passing it to other APIs that " + "use AbortController/AbortSignal might have undesirable effects). " + "You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
5980
- };
5981
- }
5982
- TYPE = Symbol("type");
5983
- ZeroArray = class ZeroArray extends Array {
5984
- constructor(size) {
5985
- super(size);
5986
- this.fill(0);
5987
- }
5988
- };
5989
- LRUCache = class LRUCache {
5990
- #max;
5991
- #maxSize;
5992
- #dispose;
5993
- #onInsert;
5994
- #disposeAfter;
5995
- #fetchMethod;
5996
- #memoMethod;
5997
- #perf;
5998
- get perf() {
5999
- return this.#perf;
6000
- }
6001
- ttl;
6002
- ttlResolution;
6003
- ttlAutopurge;
6004
- updateAgeOnGet;
6005
- updateAgeOnHas;
6006
- allowStale;
6007
- noDisposeOnSet;
6008
- noUpdateTTL;
6009
- maxEntrySize;
6010
- sizeCalculation;
6011
- noDeleteOnFetchRejection;
6012
- noDeleteOnStaleGet;
6013
- allowStaleOnFetchAbort;
6014
- allowStaleOnFetchRejection;
6015
- ignoreFetchAbort;
6016
- #size;
6017
- #calculatedSize;
6018
- #keyMap;
6019
- #keyList;
6020
- #valList;
6021
- #next;
6022
- #prev;
6023
- #head;
6024
- #tail;
6025
- #free;
6026
- #disposed;
6027
- #sizes;
6028
- #starts;
6029
- #ttls;
6030
- #autopurgeTimers;
6031
- #hasDispose;
6032
- #hasFetchMethod;
6033
- #hasDisposeAfter;
6034
- #hasOnInsert;
6035
- static unsafeExposeInternals(c) {
6036
- return {
6037
- starts: c.#starts,
6038
- ttls: c.#ttls,
6039
- autopurgeTimers: c.#autopurgeTimers,
6040
- sizes: c.#sizes,
6041
- keyMap: c.#keyMap,
6042
- keyList: c.#keyList,
6043
- valList: c.#valList,
6044
- next: c.#next,
6045
- prev: c.#prev,
6046
- get head() {
6047
- return c.#head;
6048
- },
6049
- get tail() {
6050
- return c.#tail;
6051
- },
6052
- free: c.#free,
6053
- isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
6054
- backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
6055
- moveToTail: (index) => c.#moveToTail(index),
6056
- indexes: (options) => c.#indexes(options),
6057
- rindexes: (options) => c.#rindexes(options),
6058
- isStale: (index) => c.#isStale(index)
6059
- };
6060
- }
6061
- get max() {
6062
- return this.#max;
6063
- }
6064
- get maxSize() {
6065
- return this.#maxSize;
6066
- }
6067
- get calculatedSize() {
6068
- return this.#calculatedSize;
6069
- }
6070
- get size() {
6071
- return this.#size;
6072
- }
6073
- get fetchMethod() {
6074
- return this.#fetchMethod;
6075
- }
6076
- get memoMethod() {
6077
- return this.#memoMethod;
6078
- }
6079
- get dispose() {
6080
- return this.#dispose;
6081
- }
6082
- get onInsert() {
6083
- return this.#onInsert;
6084
- }
6085
- get disposeAfter() {
6086
- return this.#disposeAfter;
6087
- }
6088
- constructor(options) {
6089
- const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, perf } = options;
6090
- if (perf !== undefined) {
6091
- if (typeof perf?.now !== "function") {
6092
- throw new TypeError("perf option must have a now() method if specified");
6093
- }
6094
- }
6095
- this.#perf = perf ?? defaultPerf;
6096
- if (max !== 0 && !isPosInt(max)) {
6097
- throw new TypeError("max option must be a nonnegative integer");
6098
- }
6099
- const UintArray = max ? getUintArray(max) : Array;
6100
- if (!UintArray) {
6101
- throw new Error("invalid max value: " + max);
6102
- }
6103
- this.#max = max;
6104
- this.#maxSize = maxSize;
6105
- this.maxEntrySize = maxEntrySize || this.#maxSize;
6106
- this.sizeCalculation = sizeCalculation;
6107
- if (this.sizeCalculation) {
6108
- if (!this.#maxSize && !this.maxEntrySize) {
6109
- throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
6110
- }
6111
- if (typeof this.sizeCalculation !== "function") {
6112
- throw new TypeError("sizeCalculation set to non-function");
6113
- }
6114
- }
6115
- if (memoMethod !== undefined && typeof memoMethod !== "function") {
6116
- throw new TypeError("memoMethod must be a function if defined");
6117
- }
6118
- this.#memoMethod = memoMethod;
6119
- if (fetchMethod !== undefined && typeof fetchMethod !== "function") {
6120
- throw new TypeError("fetchMethod must be a function if specified");
6121
- }
6122
- this.#fetchMethod = fetchMethod;
6123
- this.#hasFetchMethod = !!fetchMethod;
6124
- this.#keyMap = new Map;
6125
- this.#keyList = new Array(max).fill(undefined);
6126
- this.#valList = new Array(max).fill(undefined);
6127
- this.#next = new UintArray(max);
6128
- this.#prev = new UintArray(max);
6129
- this.#head = 0;
6130
- this.#tail = 0;
6131
- this.#free = Stack.create(max);
6132
- this.#size = 0;
6133
- this.#calculatedSize = 0;
6134
- if (typeof dispose === "function") {
6135
- this.#dispose = dispose;
6136
- }
6137
- if (typeof onInsert === "function") {
6138
- this.#onInsert = onInsert;
6139
- }
6140
- if (typeof disposeAfter === "function") {
6141
- this.#disposeAfter = disposeAfter;
6142
- this.#disposed = [];
6143
- } else {
6144
- this.#disposeAfter = undefined;
6145
- this.#disposed = undefined;
6146
- }
6147
- this.#hasDispose = !!this.#dispose;
6148
- this.#hasOnInsert = !!this.#onInsert;
6149
- this.#hasDisposeAfter = !!this.#disposeAfter;
6150
- this.noDisposeOnSet = !!noDisposeOnSet;
6151
- this.noUpdateTTL = !!noUpdateTTL;
6152
- this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
6153
- this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
6154
- this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
6155
- this.ignoreFetchAbort = !!ignoreFetchAbort;
6156
- if (this.maxEntrySize !== 0) {
6157
- if (this.#maxSize !== 0) {
6158
- if (!isPosInt(this.#maxSize)) {
6159
- throw new TypeError("maxSize must be a positive integer if specified");
6160
- }
6161
- }
6162
- if (!isPosInt(this.maxEntrySize)) {
6163
- throw new TypeError("maxEntrySize must be a positive integer if specified");
6164
- }
6165
- this.#initializeSizeTracking();
6166
- }
6167
- this.allowStale = !!allowStale;
6168
- this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
6169
- this.updateAgeOnGet = !!updateAgeOnGet;
6170
- this.updateAgeOnHas = !!updateAgeOnHas;
6171
- this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
6172
- this.ttlAutopurge = !!ttlAutopurge;
6173
- this.ttl = ttl || 0;
6174
- if (this.ttl) {
6175
- if (!isPosInt(this.ttl)) {
6176
- throw new TypeError("ttl must be a positive integer if specified");
6177
- }
6178
- this.#initializeTTLTracking();
6179
- }
6180
- if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
6181
- throw new TypeError("At least one of max, maxSize, or ttl is required");
6182
- }
6183
- if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
6184
- const code = "LRU_CACHE_UNBOUNDED";
6185
- if (shouldWarn(code)) {
6186
- warned.add(code);
6187
- const msg = "TTL caching without ttlAutopurge, max, or maxSize can " + "result in unbounded memory consumption.";
6188
- emitWarning(msg, "UnboundedCacheWarning", code, LRUCache);
6189
- }
6190
- }
6191
- }
6192
- getRemainingTTL(key) {
6193
- return this.#keyMap.has(key) ? Infinity : 0;
6194
- }
6195
- #initializeTTLTracking() {
6196
- const ttls = new ZeroArray(this.#max);
6197
- const starts = new ZeroArray(this.#max);
6198
- this.#ttls = ttls;
6199
- this.#starts = starts;
6200
- const purgeTimers = this.ttlAutopurge ? new Array(this.#max) : undefined;
6201
- this.#autopurgeTimers = purgeTimers;
6202
- this.#setItemTTL = (index, ttl, start = this.#perf.now()) => {
6203
- starts[index] = ttl !== 0 ? start : 0;
6204
- ttls[index] = ttl;
6205
- if (purgeTimers?.[index]) {
6206
- clearTimeout(purgeTimers[index]);
6207
- purgeTimers[index] = undefined;
6208
- }
6209
- if (ttl !== 0 && purgeTimers) {
6210
- const t = setTimeout(() => {
6211
- if (this.#isStale(index)) {
6212
- this.#delete(this.#keyList[index], "expire");
6213
- }
6214
- }, ttl + 1);
6215
- if (t.unref) {
6216
- t.unref();
6217
- }
6218
- purgeTimers[index] = t;
6219
- }
6220
- };
6221
- this.#updateItemAge = (index) => {
6222
- starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0;
6223
- };
6224
- this.#statusTTL = (status, index) => {
6225
- if (ttls[index]) {
6226
- const ttl = ttls[index];
6227
- const start = starts[index];
6228
- if (!ttl || !start)
6229
- return;
6230
- status.ttl = ttl;
6231
- status.start = start;
6232
- status.now = cachedNow || getNow();
6233
- const age = status.now - start;
6234
- status.remainingTTL = ttl - age;
6235
- }
6236
- };
6237
- let cachedNow = 0;
6238
- const getNow = () => {
6239
- const n = this.#perf.now();
6240
- if (this.ttlResolution > 0) {
6241
- cachedNow = n;
6242
- const t = setTimeout(() => cachedNow = 0, this.ttlResolution);
6243
- if (t.unref) {
6244
- t.unref();
6245
- }
6246
- }
6247
- return n;
6248
- };
6249
- this.getRemainingTTL = (key) => {
6250
- const index = this.#keyMap.get(key);
6251
- if (index === undefined) {
6252
- return 0;
6253
- }
6254
- const ttl = ttls[index];
6255
- const start = starts[index];
6256
- if (!ttl || !start) {
6257
- return Infinity;
6258
- }
6259
- const age = (cachedNow || getNow()) - start;
6260
- return ttl - age;
6261
- };
6262
- this.#isStale = (index) => {
6263
- const s = starts[index];
6264
- const t = ttls[index];
6265
- return !!t && !!s && (cachedNow || getNow()) - s > t;
6266
- };
6267
- }
6268
- #updateItemAge = () => {};
6269
- #statusTTL = () => {};
6270
- #setItemTTL = () => {};
6271
- #isStale = () => false;
6272
- #initializeSizeTracking() {
6273
- const sizes = new ZeroArray(this.#max);
6274
- this.#calculatedSize = 0;
6275
- this.#sizes = sizes;
6276
- this.#removeItemSize = (index) => {
6277
- this.#calculatedSize -= sizes[index];
6278
- sizes[index] = 0;
6279
- };
6280
- this.#requireSize = (k, v, size, sizeCalculation) => {
6281
- if (this.#isBackgroundFetch(v)) {
6282
- return 0;
6283
- }
6284
- if (!isPosInt(size)) {
6285
- if (sizeCalculation) {
6286
- if (typeof sizeCalculation !== "function") {
6287
- throw new TypeError("sizeCalculation must be a function");
6288
- }
6289
- size = sizeCalculation(v, k);
6290
- if (!isPosInt(size)) {
6291
- throw new TypeError("sizeCalculation return invalid (expect positive integer)");
6292
- }
6293
- } else {
6294
- throw new TypeError("invalid size value (must be positive integer). " + "When maxSize or maxEntrySize is used, sizeCalculation " + "or size must be set.");
6295
- }
6296
- }
6297
- return size;
6298
- };
6299
- this.#addItemSize = (index, size, status) => {
6300
- sizes[index] = size;
6301
- if (this.#maxSize) {
6302
- const maxSize = this.#maxSize - sizes[index];
6303
- while (this.#calculatedSize > maxSize) {
6304
- this.#evict(true);
6305
- }
6306
- }
6307
- this.#calculatedSize += sizes[index];
6308
- if (status) {
6309
- status.entrySize = size;
6310
- status.totalCalculatedSize = this.#calculatedSize;
6311
- }
6312
- };
6313
- }
6314
- #removeItemSize = (_i) => {};
6315
- #addItemSize = (_i, _s, _st) => {};
6316
- #requireSize = (_k, _v, size, sizeCalculation) => {
6317
- if (size || sizeCalculation) {
6318
- throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
6319
- }
6320
- return 0;
6321
- };
6322
- *#indexes({ allowStale = this.allowStale } = {}) {
6323
- if (this.#size) {
6324
- for (let i = this.#tail;; ) {
6325
- if (!this.#isValidIndex(i)) {
6326
- break;
6327
- }
6328
- if (allowStale || !this.#isStale(i)) {
6329
- yield i;
6330
- }
6331
- if (i === this.#head) {
6332
- break;
6333
- } else {
6334
- i = this.#prev[i];
6335
- }
6336
- }
6337
- }
6338
- }
6339
- *#rindexes({ allowStale = this.allowStale } = {}) {
6340
- if (this.#size) {
6341
- for (let i = this.#head;; ) {
6342
- if (!this.#isValidIndex(i)) {
6343
- break;
6344
- }
6345
- if (allowStale || !this.#isStale(i)) {
6346
- yield i;
6347
- }
6348
- if (i === this.#tail) {
6349
- break;
6350
- } else {
6351
- i = this.#next[i];
6352
- }
6353
- }
6354
- }
6355
- }
6356
- #isValidIndex(index) {
6357
- return index !== undefined && this.#keyMap.get(this.#keyList[index]) === index;
6358
- }
6359
- *entries() {
6360
- for (const i of this.#indexes()) {
6361
- if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6362
- yield [this.#keyList[i], this.#valList[i]];
6363
- }
6364
- }
6365
- }
6366
- *rentries() {
6367
- for (const i of this.#rindexes()) {
6368
- if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6369
- yield [this.#keyList[i], this.#valList[i]];
6370
- }
6371
- }
6372
- }
6373
- *keys() {
6374
- for (const i of this.#indexes()) {
6375
- const k = this.#keyList[i];
6376
- if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6377
- yield k;
6378
- }
6379
- }
6380
- }
6381
- *rkeys() {
6382
- for (const i of this.#rindexes()) {
6383
- const k = this.#keyList[i];
6384
- if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6385
- yield k;
6386
- }
6387
- }
6388
- }
6389
- *values() {
6390
- for (const i of this.#indexes()) {
6391
- const v = this.#valList[i];
6392
- if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6393
- yield this.#valList[i];
6394
- }
6395
- }
6396
- }
6397
- *rvalues() {
6398
- for (const i of this.#rindexes()) {
6399
- const v = this.#valList[i];
6400
- if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6401
- yield this.#valList[i];
6402
- }
6403
- }
6404
- }
6405
- [Symbol.iterator]() {
6406
- return this.entries();
6407
- }
6408
- [Symbol.toStringTag] = "LRUCache";
6409
- find(fn, getOptions = {}) {
6410
- for (const i of this.#indexes()) {
6411
- const v = this.#valList[i];
6412
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6413
- if (value === undefined)
6414
- continue;
6415
- if (fn(value, this.#keyList[i], this)) {
6416
- return this.get(this.#keyList[i], getOptions);
6417
- }
6418
- }
6419
- }
6420
- forEach(fn, thisp = this) {
6421
- for (const i of this.#indexes()) {
6422
- const v = this.#valList[i];
6423
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6424
- if (value === undefined)
6425
- continue;
6426
- fn.call(thisp, value, this.#keyList[i], this);
6427
- }
6428
- }
6429
- rforEach(fn, thisp = this) {
6430
- for (const i of this.#rindexes()) {
6431
- const v = this.#valList[i];
6432
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6433
- if (value === undefined)
6434
- continue;
6435
- fn.call(thisp, value, this.#keyList[i], this);
6436
- }
6437
- }
6438
- purgeStale() {
6439
- let deleted = false;
6440
- for (const i of this.#rindexes({ allowStale: true })) {
6441
- if (this.#isStale(i)) {
6442
- this.#delete(this.#keyList[i], "expire");
6443
- deleted = true;
6444
- }
6445
- }
6446
- return deleted;
6447
- }
6448
- info(key) {
6449
- const i = this.#keyMap.get(key);
6450
- if (i === undefined)
6451
- return;
6452
- const v = this.#valList[i];
6453
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6454
- if (value === undefined)
6455
- return;
6456
- const entry = { value };
6457
- if (this.#ttls && this.#starts) {
6458
- const ttl = this.#ttls[i];
6459
- const start = this.#starts[i];
6460
- if (ttl && start) {
6461
- const remain = ttl - (this.#perf.now() - start);
6462
- entry.ttl = remain;
6463
- entry.start = Date.now();
6464
- }
6465
- }
6466
- if (this.#sizes) {
6467
- entry.size = this.#sizes[i];
6468
- }
6469
- return entry;
6470
- }
6471
- dump() {
6472
- const arr = [];
6473
- for (const i of this.#indexes({ allowStale: true })) {
6474
- const key = this.#keyList[i];
6475
- const v = this.#valList[i];
6476
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6477
- if (value === undefined || key === undefined)
6478
- continue;
6479
- const entry = { value };
6480
- if (this.#ttls && this.#starts) {
6481
- entry.ttl = this.#ttls[i];
6482
- const age = this.#perf.now() - this.#starts[i];
6483
- entry.start = Math.floor(Date.now() - age);
6484
- }
6485
- if (this.#sizes) {
6486
- entry.size = this.#sizes[i];
6487
- }
6488
- arr.unshift([key, entry]);
6489
- }
6490
- return arr;
6491
- }
6492
- load(arr) {
6493
- this.clear();
6494
- for (const [key, entry] of arr) {
6495
- if (entry.start) {
6496
- const age = Date.now() - entry.start;
6497
- entry.start = this.#perf.now() - age;
6498
- }
6499
- this.set(key, entry.value, entry);
6500
- }
6501
- }
6502
- set(k, v, setOptions = {}) {
6503
- if (v === undefined) {
6504
- this.delete(k);
6505
- return this;
6506
- }
6507
- const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
6508
- let { noUpdateTTL = this.noUpdateTTL } = setOptions;
6509
- const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
6510
- if (this.maxEntrySize && size > this.maxEntrySize) {
6511
- if (status) {
6512
- status.set = "miss";
6513
- status.maxEntrySizeExceeded = true;
6514
- }
6515
- this.#delete(k, "set");
6516
- return this;
6517
- }
6518
- let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
6519
- if (index === undefined) {
6520
- index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
6521
- this.#keyList[index] = k;
6522
- this.#valList[index] = v;
6523
- this.#keyMap.set(k, index);
6524
- this.#next[this.#tail] = index;
6525
- this.#prev[index] = this.#tail;
6526
- this.#tail = index;
6527
- this.#size++;
6528
- this.#addItemSize(index, size, status);
6529
- if (status)
6530
- status.set = "add";
6531
- noUpdateTTL = false;
6532
- if (this.#hasOnInsert) {
6533
- this.#onInsert?.(v, k, "add");
6534
- }
6535
- } else {
6536
- this.#moveToTail(index);
6537
- const oldVal = this.#valList[index];
6538
- if (v !== oldVal) {
6539
- if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
6540
- oldVal.__abortController.abort(new Error("replaced"));
6541
- const { __staleWhileFetching: s } = oldVal;
6542
- if (s !== undefined && !noDisposeOnSet) {
6543
- if (this.#hasDispose) {
6544
- this.#dispose?.(s, k, "set");
6545
- }
6546
- if (this.#hasDisposeAfter) {
6547
- this.#disposed?.push([s, k, "set"]);
6548
- }
6549
- }
6550
- } else if (!noDisposeOnSet) {
6551
- if (this.#hasDispose) {
6552
- this.#dispose?.(oldVal, k, "set");
6553
- }
6554
- if (this.#hasDisposeAfter) {
6555
- this.#disposed?.push([oldVal, k, "set"]);
6556
- }
6557
- }
6558
- this.#removeItemSize(index);
6559
- this.#addItemSize(index, size, status);
6560
- this.#valList[index] = v;
6561
- if (status) {
6562
- status.set = "replace";
6563
- const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
6564
- if (oldValue !== undefined)
6565
- status.oldValue = oldValue;
6566
- }
6567
- } else if (status) {
6568
- status.set = "update";
6569
- }
6570
- if (this.#hasOnInsert) {
6571
- this.onInsert?.(v, k, v === oldVal ? "update" : "replace");
6572
- }
6573
- }
6574
- if (ttl !== 0 && !this.#ttls) {
6575
- this.#initializeTTLTracking();
6576
- }
6577
- if (this.#ttls) {
6578
- if (!noUpdateTTL) {
6579
- this.#setItemTTL(index, ttl, start);
6580
- }
6581
- if (status)
6582
- this.#statusTTL(status, index);
6583
- }
6584
- if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
6585
- const dt = this.#disposed;
6586
- let task;
6587
- while (task = dt?.shift()) {
6588
- this.#disposeAfter?.(...task);
6589
- }
6590
- }
6591
- return this;
6592
- }
6593
- pop() {
6594
- try {
6595
- while (this.#size) {
6596
- const val = this.#valList[this.#head];
6597
- this.#evict(true);
6598
- if (this.#isBackgroundFetch(val)) {
6599
- if (val.__staleWhileFetching) {
6600
- return val.__staleWhileFetching;
6601
- }
6602
- } else if (val !== undefined) {
6603
- return val;
6604
- }
6605
- }
6606
- } finally {
6607
- if (this.#hasDisposeAfter && this.#disposed) {
6608
- const dt = this.#disposed;
6609
- let task;
6610
- while (task = dt?.shift()) {
6611
- this.#disposeAfter?.(...task);
6612
- }
6613
- }
6614
- }
6615
- }
6616
- #evict(free) {
6617
- const head = this.#head;
6618
- const k = this.#keyList[head];
6619
- const v = this.#valList[head];
6620
- if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
6621
- v.__abortController.abort(new Error("evicted"));
6622
- } else if (this.#hasDispose || this.#hasDisposeAfter) {
6623
- if (this.#hasDispose) {
6624
- this.#dispose?.(v, k, "evict");
6625
- }
6626
- if (this.#hasDisposeAfter) {
6627
- this.#disposed?.push([v, k, "evict"]);
6628
- }
6629
- }
6630
- this.#removeItemSize(head);
6631
- if (this.#autopurgeTimers?.[head]) {
6632
- clearTimeout(this.#autopurgeTimers[head]);
6633
- this.#autopurgeTimers[head] = undefined;
6634
- }
6635
- if (free) {
6636
- this.#keyList[head] = undefined;
6637
- this.#valList[head] = undefined;
6638
- this.#free.push(head);
6639
- }
6640
- if (this.#size === 1) {
6641
- this.#head = this.#tail = 0;
6642
- this.#free.length = 0;
6643
- } else {
6644
- this.#head = this.#next[head];
6645
- }
6646
- this.#keyMap.delete(k);
6647
- this.#size--;
6648
- return head;
6649
- }
6650
- has(k, hasOptions = {}) {
6651
- const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
6652
- const index = this.#keyMap.get(k);
6653
- if (index !== undefined) {
6654
- const v = this.#valList[index];
6655
- if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === undefined) {
6656
- return false;
6657
- }
6658
- if (!this.#isStale(index)) {
6659
- if (updateAgeOnHas) {
6660
- this.#updateItemAge(index);
6661
- }
6662
- if (status) {
6663
- status.has = "hit";
6664
- this.#statusTTL(status, index);
6665
- }
6666
- return true;
6667
- } else if (status) {
6668
- status.has = "stale";
6669
- this.#statusTTL(status, index);
6670
- }
6671
- } else if (status) {
6672
- status.has = "miss";
6673
- }
6674
- return false;
6675
- }
6676
- peek(k, peekOptions = {}) {
6677
- const { allowStale = this.allowStale } = peekOptions;
6678
- const index = this.#keyMap.get(k);
6679
- if (index === undefined || !allowStale && this.#isStale(index)) {
6680
- return;
6681
- }
6682
- const v = this.#valList[index];
6683
- return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6684
- }
6685
- #backgroundFetch(k, index, options, context) {
6686
- const v = index === undefined ? undefined : this.#valList[index];
6687
- if (this.#isBackgroundFetch(v)) {
6688
- return v;
6689
- }
6690
- const ac = new AC;
6691
- const { signal } = options;
6692
- signal?.addEventListener("abort", () => ac.abort(signal.reason), {
6693
- signal: ac.signal
6694
- });
6695
- const fetchOpts = {
6696
- signal: ac.signal,
6697
- options,
6698
- context
6699
- };
6700
- const cb = (v2, updateCache = false) => {
6701
- const { aborted } = ac.signal;
6702
- const ignoreAbort = options.ignoreFetchAbort && v2 !== undefined;
6703
- if (options.status) {
6704
- if (aborted && !updateCache) {
6705
- options.status.fetchAborted = true;
6706
- options.status.fetchError = ac.signal.reason;
6707
- if (ignoreAbort)
6708
- options.status.fetchAbortIgnored = true;
6709
- } else {
6710
- options.status.fetchResolved = true;
6711
- }
6712
- }
6713
- if (aborted && !ignoreAbort && !updateCache) {
6714
- return fetchFail(ac.signal.reason);
6715
- }
6716
- const bf2 = p;
6717
- const vl = this.#valList[index];
6718
- if (vl === p || ignoreAbort && updateCache && vl === undefined) {
6719
- if (v2 === undefined) {
6720
- if (bf2.__staleWhileFetching !== undefined) {
6721
- this.#valList[index] = bf2.__staleWhileFetching;
6722
- } else {
6723
- this.#delete(k, "fetch");
6724
- }
6725
- } else {
6726
- if (options.status)
6727
- options.status.fetchUpdated = true;
6728
- this.set(k, v2, fetchOpts.options);
6729
- }
6730
- }
6731
- return v2;
6732
- };
6733
- const eb = (er) => {
6734
- if (options.status) {
6735
- options.status.fetchRejected = true;
6736
- options.status.fetchError = er;
6737
- }
6738
- return fetchFail(er);
6739
- };
6740
- const fetchFail = (er) => {
6741
- const { aborted } = ac.signal;
6742
- const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
6743
- const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
6744
- const noDelete = allowStale || options.noDeleteOnFetchRejection;
6745
- const bf2 = p;
6746
- if (this.#valList[index] === p) {
6747
- const del = !noDelete || bf2.__staleWhileFetching === undefined;
6748
- if (del) {
6749
- this.#delete(k, "fetch");
6750
- } else if (!allowStaleAborted) {
6751
- this.#valList[index] = bf2.__staleWhileFetching;
6752
- }
6753
- }
6754
- if (allowStale) {
6755
- if (options.status && bf2.__staleWhileFetching !== undefined) {
6756
- options.status.returnedStale = true;
6757
- }
6758
- return bf2.__staleWhileFetching;
6759
- } else if (bf2.__returned === bf2) {
6760
- throw er;
6761
- }
6762
- };
6763
- const pcall = (res, rej) => {
6764
- const fmp = this.#fetchMethod?.(k, v, fetchOpts);
6765
- if (fmp && fmp instanceof Promise) {
6766
- fmp.then((v2) => res(v2 === undefined ? undefined : v2), rej);
6767
- }
6768
- ac.signal.addEventListener("abort", () => {
6769
- if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
6770
- res(undefined);
6771
- if (options.allowStaleOnFetchAbort) {
6772
- res = (v2) => cb(v2, true);
6773
- }
6774
- }
6775
- });
6776
- };
6777
- if (options.status)
6778
- options.status.fetchDispatched = true;
6779
- const p = new Promise(pcall).then(cb, eb);
6780
- const bf = Object.assign(p, {
6781
- __abortController: ac,
6782
- __staleWhileFetching: v,
6783
- __returned: undefined
6784
- });
6785
- if (index === undefined) {
6786
- this.set(k, bf, { ...fetchOpts.options, status: undefined });
6787
- index = this.#keyMap.get(k);
6788
- } else {
6789
- this.#valList[index] = bf;
6790
- }
6791
- return bf;
6792
- }
6793
- #isBackgroundFetch(p) {
6794
- if (!this.#hasFetchMethod)
6795
- return false;
6796
- const b = p;
6797
- return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
6798
- }
6799
- async fetch(k, fetchOptions = {}) {
6800
- const {
6801
- allowStale = this.allowStale,
6802
- updateAgeOnGet = this.updateAgeOnGet,
6803
- noDeleteOnStaleGet = this.noDeleteOnStaleGet,
6804
- ttl = this.ttl,
6805
- noDisposeOnSet = this.noDisposeOnSet,
6806
- size = 0,
6807
- sizeCalculation = this.sizeCalculation,
6808
- noUpdateTTL = this.noUpdateTTL,
6809
- noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
6810
- allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
6811
- ignoreFetchAbort = this.ignoreFetchAbort,
6812
- allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
6813
- context,
6814
- forceRefresh = false,
6815
- status,
6816
- signal
6817
- } = fetchOptions;
6818
- if (!this.#hasFetchMethod) {
6819
- if (status)
6820
- status.fetch = "get";
6821
- return this.get(k, {
6822
- allowStale,
6823
- updateAgeOnGet,
6824
- noDeleteOnStaleGet,
6825
- status
6826
- });
6827
- }
6828
- const options = {
6829
- allowStale,
6830
- updateAgeOnGet,
6831
- noDeleteOnStaleGet,
6832
- ttl,
6833
- noDisposeOnSet,
6834
- size,
6835
- sizeCalculation,
6836
- noUpdateTTL,
6837
- noDeleteOnFetchRejection,
6838
- allowStaleOnFetchRejection,
6839
- allowStaleOnFetchAbort,
6840
- ignoreFetchAbort,
6841
- status,
6842
- signal
6843
- };
6844
- let index = this.#keyMap.get(k);
6845
- if (index === undefined) {
6846
- if (status)
6847
- status.fetch = "miss";
6848
- const p = this.#backgroundFetch(k, index, options, context);
6849
- return p.__returned = p;
6850
- } else {
6851
- const v = this.#valList[index];
6852
- if (this.#isBackgroundFetch(v)) {
6853
- const stale = allowStale && v.__staleWhileFetching !== undefined;
6854
- if (status) {
6855
- status.fetch = "inflight";
6856
- if (stale)
6857
- status.returnedStale = true;
6858
- }
6859
- return stale ? v.__staleWhileFetching : v.__returned = v;
6860
- }
6861
- const isStale = this.#isStale(index);
6862
- if (!forceRefresh && !isStale) {
6863
- if (status)
6864
- status.fetch = "hit";
6865
- this.#moveToTail(index);
6866
- if (updateAgeOnGet) {
6867
- this.#updateItemAge(index);
6868
- }
6869
- if (status)
6870
- this.#statusTTL(status, index);
6871
- return v;
6872
- }
6873
- const p = this.#backgroundFetch(k, index, options, context);
6874
- const hasStale = p.__staleWhileFetching !== undefined;
6875
- const staleVal = hasStale && allowStale;
6876
- if (status) {
6877
- status.fetch = isStale ? "stale" : "refresh";
6878
- if (staleVal && isStale)
6879
- status.returnedStale = true;
6880
- }
6881
- return staleVal ? p.__staleWhileFetching : p.__returned = p;
6882
- }
6883
- }
6884
- async forceFetch(k, fetchOptions = {}) {
6885
- const v = await this.fetch(k, fetchOptions);
6886
- if (v === undefined)
6887
- throw new Error("fetch() returned undefined");
6888
- return v;
6889
- }
6890
- memo(k, memoOptions = {}) {
6891
- const memoMethod = this.#memoMethod;
6892
- if (!memoMethod) {
6893
- throw new Error("no memoMethod provided to constructor");
6894
- }
6895
- const { context, forceRefresh, ...options } = memoOptions;
6896
- const v = this.get(k, options);
6897
- if (!forceRefresh && v !== undefined)
6898
- return v;
6899
- const vv = memoMethod(k, v, {
6900
- options,
6901
- context
6902
- });
6903
- this.set(k, vv, options);
6904
- return vv;
6905
- }
6906
- get(k, getOptions = {}) {
6907
- const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
6908
- const index = this.#keyMap.get(k);
6909
- if (index !== undefined) {
6910
- const value = this.#valList[index];
6911
- const fetching = this.#isBackgroundFetch(value);
6912
- if (status)
6913
- this.#statusTTL(status, index);
6914
- if (this.#isStale(index)) {
6915
- if (status)
6916
- status.get = "stale";
6917
- if (!fetching) {
6918
- if (!noDeleteOnStaleGet) {
6919
- this.#delete(k, "expire");
6920
- }
6921
- if (status && allowStale)
6922
- status.returnedStale = true;
6923
- return allowStale ? value : undefined;
6924
- } else {
6925
- if (status && allowStale && value.__staleWhileFetching !== undefined) {
6926
- status.returnedStale = true;
6927
- }
6928
- return allowStale ? value.__staleWhileFetching : undefined;
6929
- }
6930
- } else {
6931
- if (status)
6932
- status.get = "hit";
6933
- if (fetching) {
6934
- return value.__staleWhileFetching;
6935
- }
6936
- this.#moveToTail(index);
6937
- if (updateAgeOnGet) {
6938
- this.#updateItemAge(index);
6939
- }
6940
- return value;
6941
- }
6942
- } else if (status) {
6943
- status.get = "miss";
6944
- }
6945
- }
6946
- #connect(p, n) {
6947
- this.#prev[n] = p;
6948
- this.#next[p] = n;
6949
- }
6950
- #moveToTail(index) {
6951
- if (index !== this.#tail) {
6952
- if (index === this.#head) {
6953
- this.#head = this.#next[index];
6954
- } else {
6955
- this.#connect(this.#prev[index], this.#next[index]);
6956
- }
6957
- this.#connect(this.#tail, index);
6958
- this.#tail = index;
6959
- }
6960
- }
6961
- delete(k) {
6962
- return this.#delete(k, "delete");
6963
- }
6964
- #delete(k, reason) {
6965
- let deleted = false;
6966
- if (this.#size !== 0) {
6967
- const index = this.#keyMap.get(k);
6968
- if (index !== undefined) {
6969
- if (this.#autopurgeTimers?.[index]) {
6970
- clearTimeout(this.#autopurgeTimers?.[index]);
6971
- this.#autopurgeTimers[index] = undefined;
6972
- }
6973
- deleted = true;
6974
- if (this.#size === 1) {
6975
- this.#clear(reason);
6976
- } else {
6977
- this.#removeItemSize(index);
6978
- const v = this.#valList[index];
6979
- if (this.#isBackgroundFetch(v)) {
6980
- v.__abortController.abort(new Error("deleted"));
6981
- } else if (this.#hasDispose || this.#hasDisposeAfter) {
6982
- if (this.#hasDispose) {
6983
- this.#dispose?.(v, k, reason);
6984
- }
6985
- if (this.#hasDisposeAfter) {
6986
- this.#disposed?.push([v, k, reason]);
6987
- }
6988
- }
6989
- this.#keyMap.delete(k);
6990
- this.#keyList[index] = undefined;
6991
- this.#valList[index] = undefined;
6992
- if (index === this.#tail) {
6993
- this.#tail = this.#prev[index];
6994
- } else if (index === this.#head) {
6995
- this.#head = this.#next[index];
6996
- } else {
6997
- const pi = this.#prev[index];
6998
- this.#next[pi] = this.#next[index];
6999
- const ni = this.#next[index];
7000
- this.#prev[ni] = this.#prev[index];
7001
- }
7002
- this.#size--;
7003
- this.#free.push(index);
7004
- }
7005
- }
7006
- }
7007
- if (this.#hasDisposeAfter && this.#disposed?.length) {
7008
- const dt = this.#disposed;
7009
- let task;
7010
- while (task = dt?.shift()) {
7011
- this.#disposeAfter?.(...task);
7012
- }
7013
- }
7014
- return deleted;
7015
- }
7016
- clear() {
7017
- return this.#clear("delete");
7018
- }
7019
- #clear(reason) {
7020
- for (const index of this.#rindexes({ allowStale: true })) {
7021
- const v = this.#valList[index];
7022
- if (this.#isBackgroundFetch(v)) {
7023
- v.__abortController.abort(new Error("deleted"));
7024
- } else {
7025
- const k = this.#keyList[index];
7026
- if (this.#hasDispose) {
7027
- this.#dispose?.(v, k, reason);
7028
- }
7029
- if (this.#hasDisposeAfter) {
7030
- this.#disposed?.push([v, k, reason]);
7031
- }
7032
- }
7033
- }
7034
- this.#keyMap.clear();
7035
- this.#valList.fill(undefined);
7036
- this.#keyList.fill(undefined);
7037
- if (this.#ttls && this.#starts) {
7038
- this.#ttls.fill(0);
7039
- this.#starts.fill(0);
7040
- for (const t of this.#autopurgeTimers ?? []) {
7041
- if (t !== undefined)
7042
- clearTimeout(t);
7043
- }
7044
- this.#autopurgeTimers?.fill(undefined);
7045
- }
7046
- if (this.#sizes) {
7047
- this.#sizes.fill(0);
7048
- }
7049
- this.#head = 0;
7050
- this.#tail = 0;
7051
- this.#free.length = 0;
7052
- this.#calculatedSize = 0;
7053
- this.#size = 0;
7054
- if (this.#hasDisposeAfter && this.#disposed) {
7055
- const dt = this.#disposed;
7056
- let task;
7057
- while (task = dt?.shift()) {
7058
- this.#disposeAfter?.(...task);
7059
- }
7060
- }
7061
- }
7062
- };
7063
- });
7064
-
7065
5354
  // src/utils/cache.ts
7066
5355
  import crypto3 from "crypto";
5356
+ import { LRUCache } from "lru-cache";
7067
5357
  function getCacheKey(args) {
7068
5358
  const hash = crypto3.createHash("sha1");
7069
5359
  for (const arg of args) {
@@ -7088,7 +5378,6 @@ function writeCache(result, args) {
7088
5378
  }
7089
5379
  var config, cache;
7090
5380
  var init_cache = __esm(() => {
7091
- init_esm2();
7092
5381
  init_config();
7093
5382
  config = getConfig();
7094
5383
  cache = new LRUCache({
@@ -7504,6 +5793,8 @@ init_models();
7504
5793
  init_utils();
7505
5794
  export {
7506
5795
  setConfig,
5796
+ saveConfigFile,
5797
+ resetConfig,
7507
5798
  initRecords,
7508
5799
  hasLanguagePair,
7509
5800
  globalRecords,
@@ -7515,9 +5806,10 @@ export {
7515
5806
  getConfig,
7516
5807
  getAvailableMemoryMB,
7517
5808
  downloadModel,
5809
+ clearConfigFile,
7518
5810
  NormalizeLanguageCode,
7519
5811
  MTran
7520
5812
  };
7521
5813
 
7522
- //# debugId=9A82A5A57D5AF8B364756E2164756E21
5814
+ //# debugId=60A982E574DB9BFD64756E2164756E21
7523
5815
  //# sourceMappingURL=index.js.map