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/main.js CHANGED
@@ -44,320 +44,37 @@ var __legacyMetadataTS = (k, v) => {
44
44
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
45
45
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
46
46
 
47
- // node_modules/swagger-ui-dist/absolute-path.js
48
- var require_absolute_path = __commonJS((exports, module) => {
49
- var __dirname = "/home/xxnuo/projects/MTran/MTranServer/node_modules/swagger-ui-dist";
50
- var getAbsoluteFSPath = function() {
51
- if (typeof module !== "undefined" && module.exports) {
52
- return __require("path").resolve(__dirname);
53
- }
54
- throw new Error("getAbsoluteFSPath can only be called within a Nodejs environment");
55
- };
56
- module.exports = getAbsoluteFSPath;
57
- });
58
-
59
- // node_modules/swagger-ui-express/index.js
60
- var require_swagger_ui_express = __commonJS((exports, module) => {
61
- var express = __require("express");
62
- var getAbsoluteSwaggerFsPath = require_absolute_path();
63
- var favIconHtml = '<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />' + '<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />';
64
- var swaggerInit = "";
65
- function trimQuery(q) {
66
- return q && q.split("?")[0];
67
- }
68
- var htmlTplString = `
69
- <!-- HTML for static distribution bundle build -->
70
- <!DOCTYPE html>
71
- <html lang="en">
72
- <head>
73
- <meta charset="UTF-8">
74
- <% robotsMetaString %>
75
- <title><% title %></title>
76
- <link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
77
- <% favIconString %>
78
- <style>
79
- html
80
- {
81
- box-sizing: border-box;
82
- overflow: -moz-scrollbars-vertical;
83
- overflow-y: scroll;
84
- }
85
- *,
86
- *:before,
87
- *:after
88
- {
89
- box-sizing: inherit;
90
- }
91
-
92
- body {
93
- margin:0;
94
- background: #fafafa;
95
- }
96
- </style>
97
- </head>
98
-
99
- <body>
100
-
101
- <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position:absolute;width:0;height:0">
102
- <defs>
103
- <symbol viewBox="0 0 20 20" id="unlocked">
104
- <path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z"></path>
105
- </symbol>
106
-
107
- <symbol viewBox="0 0 20 20" id="locked">
108
- <path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z"/>
109
- </symbol>
110
-
111
- <symbol viewBox="0 0 20 20" id="close">
112
- <path d="M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z"/>
113
- </symbol>
114
-
115
- <symbol viewBox="0 0 20 20" id="large-arrow">
116
- <path d="M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z"/>
117
- </symbol>
118
-
119
- <symbol viewBox="0 0 20 20" id="large-arrow-down">
120
- <path d="M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z"/>
121
- </symbol>
122
-
123
-
124
- <symbol viewBox="0 0 24 24" id="jump-to">
125
- <path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/>
126
- </symbol>
127
-
128
- <symbol viewBox="0 0 24 24" id="expand">
129
- <path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/>
130
- </symbol>
131
-
132
- </defs>
133
- </svg>
134
-
135
- <div id="swagger-ui"></div>
136
-
137
- <script src="./swagger-ui-bundle.js"> </script>
138
- <script src="./swagger-ui-standalone-preset.js"> </script>
139
- <script src="./swagger-ui-init.js"> </script>
140
- <% customJs %>
141
- <% customJsStr %>
142
- <% customCssUrl %>
143
- <style>
144
- <% customCss %>
145
- </style>
146
- </body>
147
-
148
- </html>
149
- `;
150
- var jsTplString = `
151
- window.onload = function() {
152
- // Build a system
153
- var url = window.location.search.match(/url=([^&]+)/);
154
- if (url && url.length > 1) {
155
- url = decodeURIComponent(url[1]);
156
- } else {
157
- url = window.location.origin;
158
- }
159
- <% swaggerOptions %>
160
- url = options.swaggerUrl || url
161
- var urls = options.swaggerUrls
162
- var customOptions = options.customOptions
163
- var spec1 = options.swaggerDoc
164
- var swaggerOptions = {
165
- spec: spec1,
166
- url: url,
167
- urls: urls,
168
- dom_id: '#swagger-ui',
169
- deepLinking: true,
170
- presets: [
171
- SwaggerUIBundle.presets.apis,
172
- SwaggerUIStandalonePreset
173
- ],
174
- plugins: [
175
- SwaggerUIBundle.plugins.DownloadUrl
176
- ],
177
- layout: "StandaloneLayout"
178
- }
179
- for (var attrname in customOptions) {
180
- swaggerOptions[attrname] = customOptions[attrname];
181
- }
182
- var ui = SwaggerUIBundle(swaggerOptions)
183
-
184
- if (customOptions.oauth) {
185
- ui.initOAuth(customOptions.oauth)
186
- }
187
-
188
- if (customOptions.preauthorizeApiKey) {
189
- const key = customOptions.preauthorizeApiKey.authDefinitionKey;
190
- const value = customOptions.preauthorizeApiKey.apiKeyValue;
191
- if (!!key && !!value) {
192
- const pid = setInterval(() => {
193
- const authorized = ui.preauthorizeApiKey(key, value);
194
- if(!!authorized) clearInterval(pid);
195
- }, 500)
196
-
197
- }
198
- }
199
-
200
- if (customOptions.authAction) {
201
- ui.authActions.authorize(customOptions.authAction)
202
- }
203
-
204
- window.ui = ui
205
- }
206
- `;
207
- function toExternalScriptTag(url) {
208
- return `<script src='${url}'></script>`;
209
- }
210
- function toInlineScriptTag(jsCode) {
211
- return `<script>${jsCode}</script>`;
212
- }
213
- function toExternalStylesheetTag(url) {
214
- return `<link href='${url}' rel='stylesheet'>`;
215
- }
216
- function toTags(customCode, toScript) {
217
- if (typeof customCode === "string") {
218
- return toScript(customCode);
219
- } else if (Array.isArray(customCode)) {
220
- return customCode.map(toScript).join(`
221
- `);
222
- } else {
223
- return "";
224
- }
225
- }
226
- var generateHTML = function(swaggerDoc, opts, options, customCss, customfavIcon, swaggerUrl, customSiteTitle, _htmlTplString, _jsTplString) {
227
- var isExplorer;
228
- var customJs;
229
- var customJsStr;
230
- var swaggerUrls;
231
- var customCssUrl;
232
- var customRobots;
233
- if (opts && typeof opts === "object") {
234
- options = opts.swaggerOptions;
235
- customCss = opts.customCss;
236
- customJs = opts.customJs;
237
- customJsStr = opts.customJsStr;
238
- customfavIcon = opts.customfavIcon;
239
- customRobots = opts.customRobots;
240
- swaggerUrl = opts.swaggerUrl;
241
- swaggerUrls = opts.swaggerUrls;
242
- isExplorer = opts.explorer || !!swaggerUrls;
243
- customSiteTitle = opts.customSiteTitle;
244
- customCssUrl = opts.customCssUrl;
245
- } else {
246
- isExplorer = opts;
247
- }
248
- options = options || {};
249
- var explorerString = isExplorer ? "" : ".swagger-ui .topbar .download-url-wrapper { display: none }";
250
- customCss = explorerString + " " + customCss || explorerString;
251
- customfavIcon = customfavIcon || false;
252
- customSiteTitle = customSiteTitle || "Swagger UI";
253
- _htmlTplString = _htmlTplString || htmlTplString;
254
- _jsTplString = _jsTplString || jsTplString;
255
- var robotsMetaString = customRobots ? '<meta name="robots" content="' + customRobots + '" />' : "";
256
- var favIconString = customfavIcon ? '<link rel="icon" href="' + customfavIcon + '" />' : favIconHtml;
257
- var htmlWithCustomCss = _htmlTplString.toString().replace("<% customCss %>", customCss);
258
- var htmlWithCustomRobots = htmlWithCustomCss.replace("<% robotsMetaString %>", robotsMetaString);
259
- var htmlWithFavIcon = htmlWithCustomRobots.replace("<% favIconString %>", favIconString);
260
- var htmlWithCustomJsUrl = htmlWithFavIcon.replace("<% customJs %>", toTags(customJs, toExternalScriptTag));
261
- var htmlWithCustomJs = htmlWithCustomJsUrl.replace("<% customJsStr %>", toTags(customJsStr, toInlineScriptTag));
262
- var htmlWithCustomCssUrl = htmlWithCustomJs.replace("<% customCssUrl %>", toTags(customCssUrl, toExternalStylesheetTag));
263
- var initOptions = {
264
- swaggerDoc: swaggerDoc || undefined,
265
- customOptions: options,
266
- swaggerUrl: swaggerUrl || undefined,
267
- swaggerUrls: swaggerUrls || undefined
268
- };
269
- swaggerInit = _jsTplString.toString().replace("<% swaggerOptions %>", stringify(initOptions));
270
- return htmlWithCustomCssUrl.replace("<% title %>", customSiteTitle);
271
- };
272
- var setup = function(swaggerDoc, opts, options, customCss, customfavIcon, swaggerUrl, customSiteTitle) {
273
- var html = generateHTML(swaggerDoc, opts, options, customCss, customfavIcon, swaggerUrl, customSiteTitle, htmlTplString, jsTplString);
274
- return function(req, res) {
275
- if (req.swaggerDoc) {
276
- var reqHtml = generateHTML(req.swaggerDoc, opts, options, customCss, customfavIcon, swaggerUrl, customSiteTitle, htmlTplString, jsTplString);
277
- res.send(reqHtml);
278
- } else {
279
- res.send(html);
280
- }
281
- };
282
- };
283
- function swaggerInitFn(req, res, next) {
284
- if (trimQuery(req.url).endsWith("/package.json")) {
285
- res.sendStatus(404);
286
- } else if (trimQuery(req.url).endsWith("/swagger-ui-init.js")) {
287
- res.set("Content-Type", "application/javascript");
288
- res.send(swaggerInit);
289
- } else {
290
- next();
291
- }
292
- }
293
- var swaggerInitFunction = function(swaggerDoc, opts) {
294
- var swaggerInitFile = jsTplString.toString().replace("<% swaggerOptions %>", stringify(opts));
295
- return function(req, res, next) {
296
- if (trimQuery(req.url).endsWith("/package.json")) {
297
- res.sendStatus(404);
298
- } else if (trimQuery(req.url).endsWith("/swagger-ui-init.js")) {
299
- if (req.swaggerDoc) {
300
- opts.swaggerDoc = req.swaggerDoc;
301
- swaggerInitFile = jsTplString.toString().replace("<% swaggerOptions %>", stringify(opts));
302
- }
303
- res.set("Content-Type", "application/javascript");
304
- res.send(swaggerInitFile);
305
- } else {
306
- next();
307
- }
308
- };
309
- };
310
- var swaggerAssetMiddleware = (options) => {
311
- var opts = options || {};
312
- opts.index = false;
313
- return express.static(getAbsoluteSwaggerFsPath(), opts);
314
- };
315
- var serveFiles = function(swaggerDoc, opts) {
316
- opts = opts || {};
317
- var initOptions = {
318
- swaggerDoc: swaggerDoc || undefined,
319
- customOptions: opts.swaggerOptions || {},
320
- swaggerUrl: opts.swaggerUrl || {},
321
- swaggerUrls: opts.swaggerUrls || undefined
322
- };
323
- var swaggerInitWithOpts = swaggerInitFunction(swaggerDoc, initOptions);
324
- return [swaggerInitWithOpts, swaggerAssetMiddleware()];
325
- };
326
- var serve = [swaggerInitFn, swaggerAssetMiddleware()];
327
- var serveWithOptions = (options) => [swaggerInitFn, swaggerAssetMiddleware(options)];
328
- var stringify = function(obj, prop) {
329
- var placeholder = "____FUNCTIONPLACEHOLDER____";
330
- var fns = [];
331
- var json = JSON.stringify(obj, function(key, value) {
332
- if (typeof value === "function") {
333
- fns.push(value);
334
- return placeholder;
335
- }
336
- return value;
337
- }, 2);
338
- json = json.replace(new RegExp('"' + placeholder + '"', "g"), function(_) {
339
- return fns.shift();
340
- });
341
- return "var options = " + json + ";";
342
- };
343
- module.exports = {
344
- setup,
345
- serve,
346
- serveWithOptions,
347
- generateHTML,
348
- serveFiles
349
- };
350
- });
351
-
352
47
  // src/config/index.ts
353
48
  var exports_config = {};
354
49
  __export(exports_config, {
355
50
  setConfig: () => setConfig,
356
- getConfig: () => getConfig
51
+ saveConfigFile: () => saveConfigFile,
52
+ resetConfig: () => resetConfig,
53
+ getConfig: () => getConfig,
54
+ clearConfigFile: () => clearConfigFile
357
55
  });
358
56
  import fs from "fs";
359
57
  import os from "os";
360
58
  import path from "path";
59
+ function getConfigFilePath(homeDir) {
60
+ return path.join(homeDir, "server.json");
61
+ }
62
+ function readConfigFile(homeDir) {
63
+ if (fileConfigCache)
64
+ return fileConfigCache;
65
+ const configPath = getConfigFilePath(homeDir);
66
+ try {
67
+ const raw = fs.readFileSync(configPath, "utf8");
68
+ const parsed = JSON.parse(raw);
69
+ if (parsed && typeof parsed === "object") {
70
+ fileConfigCache = parsed;
71
+ return fileConfigCache;
72
+ }
73
+ } catch {
74
+ return {};
75
+ }
76
+ return {};
77
+ }
361
78
  function getArgValue(flag) {
362
79
  const index = process.argv.indexOf(flag);
363
80
  if (index > -1 && index + 1 < process.argv.length) {
@@ -414,30 +131,31 @@ function getConfig() {
414
131
  return globalConfig;
415
132
  }
416
133
  const homeDir = path.join(os.homedir(), ".config", "mtran");
417
- const configDir = getString("--config-dir", "MT_CONFIG_DIR", path.join(homeDir, "server"));
134
+ const fileConfig = readConfigFile(homeDir);
135
+ const configDir = getString("--config-dir", "MT_CONFIG_DIR", fileConfig.configDir || path.join(homeDir, "server"));
418
136
  const localModelsDir = path.join(process.cwd(), "models");
419
137
  const defaultModelDir = fs.existsSync(localModelsDir) ? localModelsDir : path.join(homeDir, "models");
420
- const modelDir = getString("--model-dir", "MT_MODEL_DIR", defaultModelDir);
421
- const logDir = getString("--log-dir", "MT_LOG_DIR", path.join(homeDir, "logs"));
138
+ const modelDir = getString("--model-dir", "MT_MODEL_DIR", fileConfig.modelDir || defaultModelDir);
139
+ const logDir = getString("--log-dir", "MT_LOG_DIR", fileConfig.logDir || path.join(homeDir, "logs"));
422
140
  globalConfig = {
423
141
  homeDir,
424
142
  configDir,
425
143
  modelDir,
426
144
  logDir,
427
- logLevel: getString("--log-level", "MT_LOG_LEVEL", "warn"),
428
- host: getString("--host", "MT_HOST", "0.0.0.0"),
429
- port: getString("--port", "MT_PORT", "8989"),
430
- enableWebUI: getBool("--ui", "MT_ENABLE_UI", true),
431
- enableOfflineMode: getBool("--offline", "MT_OFFLINE", false),
432
- workerIdleTimeout: getInt("--worker-idle-timeout", "MT_WORKER_IDLE_TIMEOUT", 60),
433
- workersPerLanguage: getInt("--workers-per-language", "MT_WORKERS_PER_LANGUAGE", 1),
434
- maxLengthBreak: getInt("--max-length-break", "MT_MAX_LENGTH_BREAK", 128),
435
- apiToken: getString("--api-token", "MT_API_TOKEN", ""),
436
- logToFile: getBool("--log-to-file", "MT_LOG_TO_FILE", false),
437
- logConsole: getBool("--log-console", "MT_LOG_CONSOLE", true),
438
- logRequests: getBool("--log-requests", "MT_LOG_REQUESTS", false),
439
- checkUpdate: getBool("--check-update", "MT_CHECK_UPDATE", true),
440
- cacheSize: getInt("--cache-size", "MT_CACHE_SIZE", 1000)
145
+ logLevel: getString("--log-level", "MT_LOG_LEVEL", fileConfig.logLevel || "warn"),
146
+ host: getString("--host", "MT_HOST", fileConfig.host || "0.0.0.0"),
147
+ port: getString("--port", "MT_PORT", fileConfig.port || "8989"),
148
+ enableWebUI: getBool("--ui", "MT_ENABLE_UI", fileConfig.enableWebUI ?? true),
149
+ enableOfflineMode: getBool("--offline", "MT_OFFLINE", fileConfig.enableOfflineMode ?? false),
150
+ workerIdleTimeout: getInt("--worker-idle-timeout", "MT_WORKER_IDLE_TIMEOUT", fileConfig.workerIdleTimeout ?? 60),
151
+ workersPerLanguage: getInt("--workers-per-language", "MT_WORKERS_PER_LANGUAGE", fileConfig.workersPerLanguage ?? 1),
152
+ maxLengthBreak: getInt("--max-length-break", "MT_MAX_LENGTH_BREAK", fileConfig.maxLengthBreak ?? 128),
153
+ apiToken: getString("--api-token", "MT_API_TOKEN", fileConfig.apiToken || ""),
154
+ logToFile: getBool("--log-to-file", "MT_LOG_TO_FILE", fileConfig.logToFile ?? false),
155
+ logConsole: getBool("--log-console", "MT_LOG_CONSOLE", fileConfig.logConsole ?? true),
156
+ logRequests: getBool("--log-requests", "MT_LOG_REQUESTS", fileConfig.logRequests ?? false),
157
+ checkUpdate: getBool("--check-update", "MT_CHECK_UPDATE", fileConfig.checkUpdate ?? true),
158
+ cacheSize: getInt("--cache-size", "MT_CACHE_SIZE", fileConfig.cacheSize ?? 1000)
441
159
  };
442
160
  return globalConfig;
443
161
  }
@@ -445,7 +163,30 @@ function setConfig(config) {
445
163
  const current = getConfig();
446
164
  globalConfig = { ...current, ...config };
447
165
  }
448
- var globalConfig = null;
166
+ function resetConfig() {
167
+ globalConfig = null;
168
+ fileConfigCache = null;
169
+ }
170
+ function saveConfigFile(config) {
171
+ const current = getConfig();
172
+ const next = { ...current, ...config };
173
+ const configPath = getConfigFilePath(current.homeDir);
174
+ fs.mkdirSync(current.homeDir, { recursive: true });
175
+ fs.writeFileSync(configPath, JSON.stringify(next, null, 2), "utf8");
176
+ fileConfigCache = next;
177
+ }
178
+ function clearConfigFile() {
179
+ const homeDir = path.join(os.homedir(), ".config", "mtran");
180
+ const configPath = getConfigFilePath(homeDir);
181
+ try {
182
+ if (fs.existsSync(configPath)) {
183
+ fs.unlinkSync(configPath);
184
+ }
185
+ } catch {
186
+ return;
187
+ }
188
+ }
189
+ var globalConfig = null, fileConfigCache = null;
449
190
  var init_config = () => {};
450
191
 
451
192
  // src/logger/index.ts
@@ -580,615 +321,6 @@ var init_logger = __esm(() => {
580
321
  };
581
322
  });
582
323
 
583
- // node_modules/fzstd/esm/index.mjs
584
- function decompress(dat, buf) {
585
- var bufs = [], nb = +!buf;
586
- var bt = 0, ol = 0;
587
- for (;dat.length; ) {
588
- var st = rzfh(dat, nb || buf);
589
- if (typeof st == "object") {
590
- if (nb) {
591
- buf = null;
592
- if (st.w.length == st.u) {
593
- bufs.push(buf = st.w);
594
- ol += st.u;
595
- }
596
- } else {
597
- bufs.push(buf);
598
- st.e = 0;
599
- }
600
- for (;!st.l; ) {
601
- var blk = rzb(dat, st, buf);
602
- if (!blk)
603
- err(5);
604
- if (buf)
605
- st.e = st.y;
606
- else {
607
- bufs.push(blk);
608
- ol += blk.length;
609
- cpw(st.w, 0, blk.length);
610
- st.w.set(blk, st.w.length - blk.length);
611
- }
612
- }
613
- bt = st.b + st.c * 4;
614
- } else
615
- bt = st;
616
- dat = dat.subarray(bt);
617
- }
618
- return cct(bufs, ol);
619
- }
620
- var ab, u8, u16, i16, i32, slc = function(v, s, e) {
621
- if (u8.prototype.slice)
622
- return u8.prototype.slice.call(v, s, e);
623
- if (s == null || s < 0)
624
- s = 0;
625
- if (e == null || e > v.length)
626
- e = v.length;
627
- var n = new u8(e - s);
628
- n.set(v.subarray(s, e));
629
- return n;
630
- }, fill = function(v, n, s, e) {
631
- if (u8.prototype.fill)
632
- return u8.prototype.fill.call(v, n, s, e);
633
- if (s == null || s < 0)
634
- s = 0;
635
- if (e == null || e > v.length)
636
- e = v.length;
637
- for (;s < e; ++s)
638
- v[s] = n;
639
- return v;
640
- }, cpw = function(v, t, s, e) {
641
- if (u8.prototype.copyWithin)
642
- return u8.prototype.copyWithin.call(v, t, s, e);
643
- if (s == null || s < 0)
644
- s = 0;
645
- if (e == null || e > v.length)
646
- e = v.length;
647
- while (s < e) {
648
- v[t++] = v[s++];
649
- }
650
- }, ec, err = function(ind, msg, nt) {
651
- var e = new Error(msg || ec[ind]);
652
- e.code = ind;
653
- if (Error.captureStackTrace)
654
- Error.captureStackTrace(e, err);
655
- if (!nt)
656
- throw e;
657
- return e;
658
- }, rb = function(d, b, n) {
659
- var i = 0, o = 0;
660
- for (;i < n; ++i)
661
- o |= d[b++] << (i << 3);
662
- return o;
663
- }, b4 = function(d, b) {
664
- return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
665
- }, rzfh = function(dat, w) {
666
- var n3 = dat[0] | dat[1] << 8 | dat[2] << 16;
667
- if (n3 == 3126568 && dat[3] == 253) {
668
- var flg = dat[4];
669
- var ss = flg >> 5 & 1, cc = flg >> 2 & 1, df = flg & 3, fcf = flg >> 6;
670
- if (flg & 8)
671
- err(0);
672
- var bt = 6 - ss;
673
- var db = df == 3 ? 4 : df;
674
- var di = rb(dat, bt, db);
675
- bt += db;
676
- var fsb = fcf ? 1 << fcf : ss;
677
- var fss = rb(dat, bt, fsb) + (fcf == 1 && 256);
678
- var ws = fss;
679
- if (!ss) {
680
- var wb = 1 << 10 + (dat[5] >> 3);
681
- ws = wb + (wb >> 3) * (dat[5] & 7);
682
- }
683
- if (ws > 2145386496)
684
- err(1);
685
- var buf = new u8((w == 1 ? fss || ws : w ? 0 : ws) + 12);
686
- buf[0] = 1, buf[4] = 4, buf[8] = 8;
687
- return {
688
- b: bt + fsb,
689
- y: 0,
690
- l: 0,
691
- d: di,
692
- w: w && w != 1 ? w : buf.subarray(12),
693
- e: ws,
694
- o: new i32(buf.buffer, 0, 3),
695
- u: fss,
696
- c: cc,
697
- m: Math.min(131072, ws)
698
- };
699
- } else if ((n3 >> 4 | dat[3] << 20) == 25481893) {
700
- return b4(dat, 4) + 8;
701
- }
702
- err(0);
703
- }, msb = function(val) {
704
- var bits = 0;
705
- for (;1 << bits <= val; ++bits)
706
- ;
707
- return bits - 1;
708
- }, rfse = function(dat, bt, mal) {
709
- var tpos = (bt << 3) + 4;
710
- var al = (dat[bt] & 15) + 5;
711
- if (al > mal)
712
- err(3);
713
- var sz = 1 << al;
714
- var probs = sz, sym = -1, re = -1, i = -1, ht = sz;
715
- var buf = new ab(512 + (sz << 2));
716
- var freq = new i16(buf, 0, 256);
717
- var dstate = new u16(buf, 0, 256);
718
- var nstate = new u16(buf, 512, sz);
719
- var bb1 = 512 + (sz << 1);
720
- var syms = new u8(buf, bb1, sz);
721
- var nbits = new u8(buf, bb1 + sz);
722
- while (sym < 255 && probs > 0) {
723
- var bits = msb(probs + 1);
724
- var cbt = tpos >> 3;
725
- var msk = (1 << bits + 1) - 1;
726
- var val = (dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16) >> (tpos & 7) & msk;
727
- var msk1fb = (1 << bits) - 1;
728
- var msv = msk - probs - 1;
729
- var sval = val & msk1fb;
730
- if (sval < msv)
731
- tpos += bits, val = sval;
732
- else {
733
- tpos += bits + 1;
734
- if (val > msk1fb)
735
- val -= msv;
736
- }
737
- freq[++sym] = --val;
738
- if (val == -1) {
739
- probs += val;
740
- syms[--ht] = sym;
741
- } else
742
- probs -= val;
743
- if (!val) {
744
- do {
745
- var rbt = tpos >> 3;
746
- re = (dat[rbt] | dat[rbt + 1] << 8) >> (tpos & 7) & 3;
747
- tpos += 2;
748
- sym += re;
749
- } while (re == 3);
750
- }
751
- }
752
- if (sym > 255 || probs)
753
- err(0);
754
- var sympos = 0;
755
- var sstep = (sz >> 1) + (sz >> 3) + 3;
756
- var smask = sz - 1;
757
- for (var s = 0;s <= sym; ++s) {
758
- var sf = freq[s];
759
- if (sf < 1) {
760
- dstate[s] = -sf;
761
- continue;
762
- }
763
- for (i = 0;i < sf; ++i) {
764
- syms[sympos] = s;
765
- do {
766
- sympos = sympos + sstep & smask;
767
- } while (sympos >= ht);
768
- }
769
- }
770
- if (sympos)
771
- err(0);
772
- for (i = 0;i < sz; ++i) {
773
- var ns = dstate[syms[i]]++;
774
- var nb = nbits[i] = al - msb(ns);
775
- nstate[i] = (ns << nb) - sz;
776
- }
777
- return [tpos + 7 >> 3, {
778
- b: al,
779
- s: syms,
780
- n: nbits,
781
- t: nstate
782
- }];
783
- }, rhu = function(dat, bt) {
784
- var i = 0, wc = -1;
785
- var buf = new u8(292), hb = dat[bt];
786
- var hw = buf.subarray(0, 256);
787
- var rc = buf.subarray(256, 268);
788
- var ri = new u16(buf.buffer, 268);
789
- if (hb < 128) {
790
- var _a = rfse(dat, bt + 1, 6), ebt = _a[0], fdt = _a[1];
791
- bt += hb;
792
- var epos = ebt << 3;
793
- var lb = dat[bt];
794
- if (!lb)
795
- err(0);
796
- var st1 = 0, st2 = 0, btr1 = fdt.b, btr2 = btr1;
797
- var fpos = (++bt << 3) - 8 + msb(lb);
798
- for (;; ) {
799
- fpos -= btr1;
800
- if (fpos < epos)
801
- break;
802
- var cbt = fpos >> 3;
803
- st1 += (dat[cbt] | dat[cbt + 1] << 8) >> (fpos & 7) & (1 << btr1) - 1;
804
- hw[++wc] = fdt.s[st1];
805
- fpos -= btr2;
806
- if (fpos < epos)
807
- break;
808
- cbt = fpos >> 3;
809
- st2 += (dat[cbt] | dat[cbt + 1] << 8) >> (fpos & 7) & (1 << btr2) - 1;
810
- hw[++wc] = fdt.s[st2];
811
- btr1 = fdt.n[st1];
812
- st1 = fdt.t[st1];
813
- btr2 = fdt.n[st2];
814
- st2 = fdt.t[st2];
815
- }
816
- if (++wc > 255)
817
- err(0);
818
- } else {
819
- wc = hb - 127;
820
- for (;i < wc; i += 2) {
821
- var byte = dat[++bt];
822
- hw[i] = byte >> 4;
823
- hw[i + 1] = byte & 15;
824
- }
825
- ++bt;
826
- }
827
- var wes = 0;
828
- for (i = 0;i < wc; ++i) {
829
- var wt = hw[i];
830
- if (wt > 11)
831
- err(0);
832
- wes += wt && 1 << wt - 1;
833
- }
834
- var mb = msb(wes) + 1;
835
- var ts = 1 << mb;
836
- var rem = ts - wes;
837
- if (rem & rem - 1)
838
- err(0);
839
- hw[wc++] = msb(rem) + 1;
840
- for (i = 0;i < wc; ++i) {
841
- var wt = hw[i];
842
- ++rc[hw[i] = wt && mb + 1 - wt];
843
- }
844
- var hbuf = new u8(ts << 1);
845
- var syms = hbuf.subarray(0, ts), nb = hbuf.subarray(ts);
846
- ri[mb] = 0;
847
- for (i = mb;i > 0; --i) {
848
- var pv = ri[i];
849
- fill(nb, i, pv, ri[i - 1] = pv + rc[i] * (1 << mb - i));
850
- }
851
- if (ri[0] != ts)
852
- err(0);
853
- for (i = 0;i < wc; ++i) {
854
- var bits = hw[i];
855
- if (bits) {
856
- var code = ri[bits];
857
- fill(syms, i, code, ri[bits] = code + (1 << mb - bits));
858
- }
859
- }
860
- return [bt, {
861
- n: nb,
862
- b: mb,
863
- s: syms
864
- }];
865
- }, dllt, dmlt, doct, b2bl = function(b, s) {
866
- var len = b.length, bl = new i32(len);
867
- for (var i = 0;i < len; ++i) {
868
- bl[i] = s;
869
- s += 1 << b[i];
870
- }
871
- return bl;
872
- }, llb, llbl, mlb, mlbl, dhu = function(dat, out, hu) {
873
- var len = dat.length, ss = out.length, lb = dat[len - 1], msk = (1 << hu.b) - 1, eb = -hu.b;
874
- if (!lb)
875
- err(0);
876
- var st = 0, btr = hu.b, pos = (len << 3) - 8 + msb(lb) - btr, i = -1;
877
- for (;pos > eb && i < ss; ) {
878
- var cbt = pos >> 3;
879
- var val = (dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16) >> (pos & 7);
880
- st = (st << btr | val) & msk;
881
- out[++i] = hu.s[st];
882
- pos -= btr = hu.n[st];
883
- }
884
- if (pos != eb || i + 1 != ss)
885
- err(0);
886
- }, dhu4 = function(dat, out, hu) {
887
- var bt = 6;
888
- var ss = out.length, sz1 = ss + 3 >> 2, sz2 = sz1 << 1, sz3 = sz1 + sz2;
889
- dhu(dat.subarray(bt, bt += dat[0] | dat[1] << 8), out.subarray(0, sz1), hu);
890
- dhu(dat.subarray(bt, bt += dat[2] | dat[3] << 8), out.subarray(sz1, sz2), hu);
891
- dhu(dat.subarray(bt, bt += dat[4] | dat[5] << 8), out.subarray(sz2, sz3), hu);
892
- dhu(dat.subarray(bt), out.subarray(sz3), hu);
893
- }, rzb = function(dat, st, out) {
894
- var _a;
895
- var bt = st.b;
896
- var b0 = dat[bt], btype = b0 >> 1 & 3;
897
- st.l = b0 & 1;
898
- var sz = b0 >> 3 | dat[bt + 1] << 5 | dat[bt + 2] << 13;
899
- var ebt = (bt += 3) + sz;
900
- if (btype == 1) {
901
- if (bt >= dat.length)
902
- return;
903
- st.b = bt + 1;
904
- if (out) {
905
- fill(out, dat[bt], st.y, st.y += sz);
906
- return out;
907
- }
908
- return fill(new u8(sz), dat[bt]);
909
- }
910
- if (ebt > dat.length)
911
- return;
912
- if (btype == 0) {
913
- st.b = ebt;
914
- if (out) {
915
- out.set(dat.subarray(bt, ebt), st.y);
916
- st.y += sz;
917
- return out;
918
- }
919
- return slc(dat, bt, ebt);
920
- }
921
- if (btype == 2) {
922
- var b3 = dat[bt], lbt = b3 & 3, sf = b3 >> 2 & 3;
923
- var lss = b3 >> 4, lcs = 0, s4 = 0;
924
- if (lbt < 2) {
925
- if (sf & 1)
926
- lss |= dat[++bt] << 4 | (sf & 2 && dat[++bt] << 12);
927
- else
928
- lss = b3 >> 3;
929
- } else {
930
- s4 = sf;
931
- if (sf < 2)
932
- lss |= (dat[++bt] & 63) << 4, lcs = dat[bt] >> 6 | dat[++bt] << 2;
933
- else if (sf == 2)
934
- lss |= dat[++bt] << 4 | (dat[++bt] & 3) << 12, lcs = dat[bt] >> 2 | dat[++bt] << 6;
935
- else
936
- lss |= dat[++bt] << 4 | (dat[++bt] & 63) << 12, lcs = dat[bt] >> 6 | dat[++bt] << 2 | dat[++bt] << 10;
937
- }
938
- ++bt;
939
- var buf = out ? out.subarray(st.y, st.y + st.m) : new u8(st.m);
940
- var spl = buf.length - lss;
941
- if (lbt == 0)
942
- buf.set(dat.subarray(bt, bt += lss), spl);
943
- else if (lbt == 1)
944
- fill(buf, dat[bt++], spl);
945
- else {
946
- var hu = st.h;
947
- if (lbt == 2) {
948
- var hud = rhu(dat, bt);
949
- lcs += bt - (bt = hud[0]);
950
- st.h = hu = hud[1];
951
- } else if (!hu)
952
- err(0);
953
- (s4 ? dhu4 : dhu)(dat.subarray(bt, bt += lcs), buf.subarray(spl), hu);
954
- }
955
- var ns = dat[bt++];
956
- if (ns) {
957
- if (ns == 255)
958
- ns = (dat[bt++] | dat[bt++] << 8) + 32512;
959
- else if (ns > 127)
960
- ns = ns - 128 << 8 | dat[bt++];
961
- var scm = dat[bt++];
962
- if (scm & 3)
963
- err(0);
964
- var dts = [dmlt, doct, dllt];
965
- for (var i = 2;i > -1; --i) {
966
- var md = scm >> (i << 1) + 2 & 3;
967
- if (md == 1) {
968
- var rbuf = new u8([0, 0, dat[bt++]]);
969
- dts[i] = {
970
- s: rbuf.subarray(2, 3),
971
- n: rbuf.subarray(0, 1),
972
- t: new u16(rbuf.buffer, 0, 1),
973
- b: 0
974
- };
975
- } else if (md == 2) {
976
- _a = rfse(dat, bt, 9 - (i & 1)), bt = _a[0], dts[i] = _a[1];
977
- } else if (md == 3) {
978
- if (!st.t)
979
- err(0);
980
- dts[i] = st.t[i];
981
- }
982
- }
983
- var _b = st.t = dts, mlt = _b[0], oct = _b[1], llt = _b[2];
984
- var lb = dat[ebt - 1];
985
- if (!lb)
986
- err(0);
987
- var spos = (ebt << 3) - 8 + msb(lb) - llt.b, cbt = spos >> 3, oubt = 0;
988
- var lst = (dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << llt.b) - 1;
989
- cbt = (spos -= oct.b) >> 3;
990
- var ost = (dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << oct.b) - 1;
991
- cbt = (spos -= mlt.b) >> 3;
992
- var mst = (dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << mlt.b) - 1;
993
- for (++ns;--ns; ) {
994
- var llc = llt.s[lst];
995
- var lbtr = llt.n[lst];
996
- var mlc = mlt.s[mst];
997
- var mbtr = mlt.n[mst];
998
- var ofc = oct.s[ost];
999
- var obtr = oct.n[ost];
1000
- cbt = (spos -= ofc) >> 3;
1001
- var ofp = 1 << ofc;
1002
- var off = ofp + ((dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16 | dat[cbt + 3] << 24) >>> (spos & 7) & ofp - 1);
1003
- cbt = (spos -= mlb[mlc]) >> 3;
1004
- var ml = mlbl[mlc] + ((dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16) >> (spos & 7) & (1 << mlb[mlc]) - 1);
1005
- cbt = (spos -= llb[llc]) >> 3;
1006
- var ll = llbl[llc] + ((dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16) >> (spos & 7) & (1 << llb[llc]) - 1);
1007
- cbt = (spos -= lbtr) >> 3;
1008
- lst = llt.t[lst] + ((dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << lbtr) - 1);
1009
- cbt = (spos -= mbtr) >> 3;
1010
- mst = mlt.t[mst] + ((dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << mbtr) - 1);
1011
- cbt = (spos -= obtr) >> 3;
1012
- ost = oct.t[ost] + ((dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << obtr) - 1);
1013
- if (off > 3) {
1014
- st.o[2] = st.o[1];
1015
- st.o[1] = st.o[0];
1016
- st.o[0] = off -= 3;
1017
- } else {
1018
- var idx = off - (ll != 0);
1019
- if (idx) {
1020
- off = idx == 3 ? st.o[0] - 1 : st.o[idx];
1021
- if (idx > 1)
1022
- st.o[2] = st.o[1];
1023
- st.o[1] = st.o[0];
1024
- st.o[0] = off;
1025
- } else
1026
- off = st.o[0];
1027
- }
1028
- for (var i = 0;i < ll; ++i) {
1029
- buf[oubt + i] = buf[spl + i];
1030
- }
1031
- oubt += ll, spl += ll;
1032
- var stin = oubt - off;
1033
- if (stin < 0) {
1034
- var len = -stin;
1035
- var bs = st.e + stin;
1036
- if (len > ml)
1037
- len = ml;
1038
- for (var i = 0;i < len; ++i) {
1039
- buf[oubt + i] = st.w[bs + i];
1040
- }
1041
- oubt += len, ml -= len, stin = 0;
1042
- }
1043
- for (var i = 0;i < ml; ++i) {
1044
- buf[oubt + i] = buf[stin + i];
1045
- }
1046
- oubt += ml;
1047
- }
1048
- if (oubt != spl) {
1049
- while (spl < buf.length) {
1050
- buf[oubt++] = buf[spl++];
1051
- }
1052
- } else
1053
- oubt = buf.length;
1054
- if (out)
1055
- st.y += oubt;
1056
- else
1057
- buf = slc(buf, 0, oubt);
1058
- } else if (out) {
1059
- st.y += lss;
1060
- if (spl) {
1061
- for (var i = 0;i < lss; ++i) {
1062
- buf[i] = buf[spl + i];
1063
- }
1064
- }
1065
- } else if (spl)
1066
- buf = slc(buf, spl);
1067
- st.b = ebt;
1068
- return buf;
1069
- }
1070
- err(2);
1071
- }, cct = function(bufs, ol) {
1072
- if (bufs.length == 1)
1073
- return bufs[0];
1074
- var buf = new u8(ol);
1075
- for (var i = 0, b = 0;i < bufs.length; ++i) {
1076
- var chk = bufs[i];
1077
- buf.set(chk, b);
1078
- b += chk.length;
1079
- }
1080
- return buf;
1081
- };
1082
- var init_esm = __esm(() => {
1083
- ab = ArrayBuffer;
1084
- u8 = Uint8Array;
1085
- u16 = Uint16Array;
1086
- i16 = Int16Array;
1087
- i32 = Int32Array;
1088
- ec = [
1089
- "invalid zstd data",
1090
- "window size too large (>2046MB)",
1091
- "invalid block type",
1092
- "FSE accuracy too high",
1093
- "match distance too far back",
1094
- "unexpected EOF"
1095
- ];
1096
- dllt = rfse(/* @__PURE__ */ new u8([
1097
- 81,
1098
- 16,
1099
- 99,
1100
- 140,
1101
- 49,
1102
- 198,
1103
- 24,
1104
- 99,
1105
- 12,
1106
- 33,
1107
- 196,
1108
- 24,
1109
- 99,
1110
- 102,
1111
- 102,
1112
- 134,
1113
- 70,
1114
- 146,
1115
- 4
1116
- ]), 0, 6)[1];
1117
- dmlt = rfse(/* @__PURE__ */ new u8([
1118
- 33,
1119
- 20,
1120
- 196,
1121
- 24,
1122
- 99,
1123
- 140,
1124
- 33,
1125
- 132,
1126
- 16,
1127
- 66,
1128
- 8,
1129
- 33,
1130
- 132,
1131
- 16,
1132
- 66,
1133
- 8,
1134
- 33,
1135
- 68,
1136
- 68,
1137
- 68,
1138
- 68,
1139
- 68,
1140
- 68,
1141
- 68,
1142
- 68,
1143
- 36,
1144
- 9
1145
- ]), 0, 6)[1];
1146
- doct = rfse(/* @__PURE__ */ new u8([
1147
- 32,
1148
- 132,
1149
- 16,
1150
- 66,
1151
- 102,
1152
- 70,
1153
- 68,
1154
- 68,
1155
- 68,
1156
- 68,
1157
- 36,
1158
- 73,
1159
- 2
1160
- ]), 0, 5)[1];
1161
- llb = /* @__PURE__ */ new u8((/* @__PURE__ */ new i32([
1162
- 0,
1163
- 0,
1164
- 0,
1165
- 0,
1166
- 16843009,
1167
- 50528770,
1168
- 134678020,
1169
- 202050057,
1170
- 269422093
1171
- ])).buffer, 0, 36);
1172
- llbl = /* @__PURE__ */ b2bl(llb, 0);
1173
- mlb = /* @__PURE__ */ new u8((/* @__PURE__ */ new i32([
1174
- 0,
1175
- 0,
1176
- 0,
1177
- 0,
1178
- 0,
1179
- 0,
1180
- 0,
1181
- 0,
1182
- 16843009,
1183
- 50528770,
1184
- 117769220,
1185
- 185207048,
1186
- 252579084,
1187
- 16
1188
- ])).buffer, 0, 53);
1189
- mlbl = /* @__PURE__ */ b2bl(mlb, 3);
1190
- });
1191
-
1192
324
  // src/core/loader.ts
1193
325
  class ResourceLoader {
1194
326
  fileSystem;
@@ -1248,6 +380,7 @@ var init_loader = __esm(() => {
1248
380
  // src/core/factory.ts
1249
381
  import fs3 from "fs/promises";
1250
382
  import path3 from "path";
383
+ import { decompress } from "fzstd";
1251
384
 
1252
385
  class Downloader {
1253
386
  timeout;
@@ -1314,7 +447,6 @@ function createResourceLoader() {
1314
447
  return new ResourceLoader(new NodeFileSystem);
1315
448
  }
1316
449
  var init_factory = __esm(() => {
1317
- init_esm();
1318
450
  init_loader();
1319
451
  });
1320
452
 
@@ -1391,8 +523,8 @@ async function initRecords() {
1391
523
  if (globalRecords) {
1392
524
  debug(`Loaded ${globalRecords.data.length} model records`);
1393
525
  }
1394
- } catch (err2) {
1395
- throw new Error(`Failed to load records in offline mode: ${err2}`);
526
+ } catch (err) {
527
+ throw new Error(`Failed to load records in offline mode: ${err}`);
1396
528
  }
1397
529
  return;
1398
530
  }
@@ -1408,9 +540,9 @@ async function initRecords() {
1408
540
  if (globalRecords) {
1409
541
  debug(`Loaded ${globalRecords.data.length} model records`);
1410
542
  }
1411
- } catch (err2) {
1412
- warn(`Failed to download records.json: ${err2}`);
1413
- throw err2;
543
+ } catch (err) {
544
+ warn(`Failed to download records.json: ${err}`);
545
+ throw err;
1414
546
  }
1415
547
  }
1416
548
  async function downloadModel(toLang, fromLang, version) {
@@ -1644,6 +776,9 @@ class TranslationEngine {
1644
776
  text = text.replace(/<([^a-zA-Z/!?][^>]*)>/g, "&lt;$1&gt;");
1645
777
  const unclosedTags = /<([a-zA-Z]+)(?:\s[^>]*)?>(?![\s\S]*<\/\1>)/g;
1646
778
  text = text.replace(unclosedTags, (match) => {
779
+ if (match.endsWith("/>")) {
780
+ return match;
781
+ }
1647
782
  return match.replace(/</g, "&lt;").replace(/>/g, "&gt;");
1648
783
  });
1649
784
  return text;
@@ -1780,7 +915,7 @@ class TranslationEngine {
1780
915
  const emojiRegex = /(\p{RI}\p{RI}|\p{Emoji_Presentation}|\p{Extended_Pictographic})/gu;
1781
916
  const replacements = [];
1782
917
  const cleanText = text.replace(emojiRegex, (match) => {
1783
- const placeholder = `<e${replacements.length}>`;
918
+ const placeholder = `[EE${replacements.length}]`;
1784
919
  replacements.push({ original: match, placeholder });
1785
920
  return placeholder;
1786
921
  });
@@ -1788,8 +923,10 @@ class TranslationEngine {
1788
923
  }
1789
924
  _restoreEmojis(text, replacements) {
1790
925
  let result = text;
1791
- for (const { original, placeholder } of replacements) {
1792
- result = result.split(placeholder).join(original);
926
+ for (let i = 0;i < replacements.length; i++) {
927
+ const { original } = replacements[i];
928
+ const pattern = new RegExp(`\\[EE${i}\\]`, "gi");
929
+ result = result.replace(pattern, original);
1793
930
  }
1794
931
  return result;
1795
932
  }
@@ -1802,7 +939,7 @@ class TranslationEngine {
1802
939
  const taggedText = text.replace(placeholderRegex, (match) => {
1803
940
  const index = replacements.length;
1804
941
  replacements.push(match);
1805
- return `<br data-mt="${index}">`;
942
+ return `<mt${index} />`;
1806
943
  });
1807
944
  return { taggedText, replacements, forceHtml: !htmlEnabled };
1808
945
  }
@@ -1811,7 +948,8 @@ class TranslationEngine {
1811
948
  return text;
1812
949
  }
1813
950
  let result = text;
1814
- result = result.replace(/<br\s+data-mt="(\d+)"\s*\/?>/gi, (_, index) => {
951
+ result = result.replace(/<\/mt\d+>/gi, "");
952
+ result = result.replace(/<mt(\d+)\s*\/?>/gi, (_, index) => {
1815
953
  const idx = Number(index);
1816
954
  return replacements[idx] ?? _;
1817
955
  });
@@ -1901,7 +1039,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
1901
1039
  setWindowTitle = (title) => document.title = title;
1902
1040
  } else {}
1903
1041
  var out = Module.print || console.log.bind(console);
1904
- var err2 = Module.printErr || console.warn.bind(console);
1042
+ var err = Module.printErr || console.warn.bind(console);
1905
1043
  Object.assign(Module, moduleOverrides);
1906
1044
  moduleOverrides = null;
1907
1045
  if (Module.arguments) {
@@ -2292,7 +1430,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2292
1430
  }
2293
1431
  }
2294
1432
  what = "Aborted(" + what + ")";
2295
- err2(what);
1433
+ err(what);
2296
1434
  ABORT = true;
2297
1435
  EXITSTATUS = 1;
2298
1436
  what += ". Build with -s ASSERTIONS=1 for more info.";
@@ -2317,8 +1455,8 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2317
1455
  return readBinary(file);
2318
1456
  }
2319
1457
  throw "both async and sync fetching of the wasm failed";
2320
- } catch (err3) {
2321
- abort(err3);
1458
+ } catch (err2) {
1459
+ abort(err2);
2322
1460
  }
2323
1461
  }
2324
1462
  function getBinaryPromise() {
@@ -2366,7 +1504,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2366
1504
  }).then(function(instance) {
2367
1505
  return instance;
2368
1506
  }).then(receiver, function(reason) {
2369
- err2("failed to asynchronously prepare wasm: " + reason);
1507
+ err("failed to asynchronously prepare wasm: " + reason);
2370
1508
  abort(reason);
2371
1509
  });
2372
1510
  }
@@ -2377,8 +1515,8 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2377
1515
  }).then(function(response) {
2378
1516
  var result = WebAssembly.instantiateStreaming(response, info2);
2379
1517
  return result.then(receiveInstantiationResult, function(reason) {
2380
- err2("wasm streaming compile failed: " + reason);
2381
- err2("falling back to ArrayBuffer instantiation");
1518
+ err("wasm streaming compile failed: " + reason);
1519
+ err("falling back to ArrayBuffer instantiation");
2382
1520
  return instantiateArrayBuffer(receiveInstantiationResult);
2383
1521
  });
2384
1522
  });
@@ -2390,7 +1528,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2390
1528
  var exports2 = Module.instantiateWasm(info2, receiveInstance);
2391
1529
  return exports2;
2392
1530
  } catch (e) {
2393
- err2("Module.instantiateWasm callback failed with error: " + e);
1531
+ err("Module.instantiateWasm callback failed with error: " + e);
2394
1532
  return false;
2395
1533
  }
2396
1534
  }
@@ -2582,7 +1720,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
2582
1720
  printChar(stream, curr) {
2583
1721
  var buffer2 = SYSCALLS.buffers[stream];
2584
1722
  if (curr === 0 || curr === 10) {
2585
- (stream === 1 ? out : err2)(UTF8ArrayToString(buffer2, 0));
1723
+ (stream === 1 ? out : err)(UTF8ArrayToString(buffer2, 0));
2586
1724
  buffer2.length = 0;
2587
1725
  } else {
2588
1726
  buffer2.push(curr);
@@ -4233,7 +3371,7 @@ var require_bergamot_translator = __commonJS((exports, module) => {
4233
3371
  return 0;
4234
3372
  }
4235
3373
  function _pclose() {
4236
- err2("missing function: pclose");
3374
+ err("missing function: pclose");
4237
3375
  abort(-1);
4238
3376
  }
4239
3377
  function _setTempRet0(val) {
@@ -4733,7 +3871,7 @@ var init_bergamot_translator = () => {};
4733
3871
 
4734
3872
  // src/lib/cld2/cld2.js
4735
3873
  var require_cld2 = __commonJS((exports, module) => {
4736
- var __dirname = "/home/xxnuo/projects/MTran/MTranServer/src/lib/cld2", __filename = "/home/xxnuo/projects/MTran/MTranServer/src/lib/cld2/cld2.js";
3874
+ var __dirname = "/Volumes/MacData/Users/xxnuo/projects/MTranServer/src/lib/cld2", __filename = "/Volumes/MacData/Users/xxnuo/projects/MTranServer/src/lib/cld2/cld2.js";
4737
3875
  var loadCLD2 = (() => {
4738
3876
  var _scriptName = globalThis.document?.currentScript?.src;
4739
3877
  return async function(moduleArg = {}) {
@@ -5404,7 +4542,7 @@ var require_cld2 = __commonJS((exports, module) => {
5404
4542
  if (E.preInit)
5405
4543
  for (typeof E.preInit == "function" && (E.preInit = [E.preInit]);0 < E.preInit.length; )
5406
4544
  E.preInit.shift()();
5407
- var Oa, Pa, Qa, Ra, Sa, Ta, Ua, Va, Wa, Xa, Ya, Za, $a, ab2, M, bb = { a: function(a, b, c) {
4545
+ var Oa, Pa, Qa, Ra, Sa, Ta, Ua, Va, Wa, Xa, Ya, Za, $a, ab, M, bb = { a: function(a, b, c) {
5408
4546
  var d = new Ga(a);
5409
4547
  L[d.B + 16 >> 2] = 0;
5410
4548
  L[d.B + 4 >> 2] = b;
@@ -5469,7 +4607,7 @@ var require_cld2 = __commonJS((exports, module) => {
5469
4607
  Ya = E._emscripten_bind_LanguageInfo_getIsReliable_0 = e.t;
5470
4608
  Za = E._emscripten_bind_LanguageInfo_getLanguageCode_0 = e.u;
5471
4609
  $a = E._emscripten_bind_LanguageInfo_get_languages_1 = e.v;
5472
- ab2 = E._emscripten_bind_LanguageInfo___destroy___0 = e.w;
4610
+ ab = E._emscripten_bind_LanguageInfo___destroy___0 = e.w;
5473
4611
  M = e.f;
5474
4612
  ya();
5475
4613
  return P;
@@ -5706,7 +4844,7 @@ var require_cld2 = __commonJS((exports, module) => {
5706
4844
  };
5707
4845
  Object.defineProperty(X.prototype, "languages", { get: X.prototype.$ });
5708
4846
  X.prototype.__destroy__ = function() {
5709
- ab2(this.B);
4847
+ ab(this.B);
5710
4848
  };
5711
4849
  S.alloc = S.alloc.bind(S);
5712
4850
  S.P = S.P.bind(S);
@@ -6214,1162 +5352,9 @@ var init_detector = __esm(() => {
6214
5352
  import_cld2 = __toESM(require_cld2(), 1);
6215
5353
  });
6216
5354
 
6217
- // node_modules/lru-cache/dist/esm/index.js
6218
- class Stack {
6219
- heap;
6220
- length;
6221
- static #constructing = false;
6222
- static create(max) {
6223
- const HeapCls = getUintArray(max);
6224
- if (!HeapCls)
6225
- return [];
6226
- Stack.#constructing = true;
6227
- const s = new Stack(max, HeapCls);
6228
- Stack.#constructing = false;
6229
- return s;
6230
- }
6231
- constructor(max, HeapCls) {
6232
- if (!Stack.#constructing) {
6233
- throw new TypeError("instantiate Stack using Stack.create(n)");
6234
- }
6235
- this.heap = new HeapCls(max);
6236
- this.length = 0;
6237
- }
6238
- push(n) {
6239
- this.heap[this.length++] = n;
6240
- }
6241
- pop() {
6242
- return this.heap[--this.length];
6243
- }
6244
- }
6245
- var defaultPerf, warned, PROCESS, emitWarning = (msg, type, code, fn) => {
6246
- typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
6247
- }, 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;
6248
- var init_esm2 = __esm(() => {
6249
- defaultPerf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
6250
- warned = new Set;
6251
- PROCESS = typeof process === "object" && !!process ? process : {};
6252
- AC = globalThis.AbortController;
6253
- AS = globalThis.AbortSignal;
6254
- if (typeof AC === "undefined") {
6255
- AS = class AbortSignal {
6256
- onabort;
6257
- _onabort = [];
6258
- reason;
6259
- aborted = false;
6260
- addEventListener(_, fn) {
6261
- this._onabort.push(fn);
6262
- }
6263
- };
6264
- AC = class AbortController2 {
6265
- constructor() {
6266
- warnACPolyfill();
6267
- }
6268
- signal = new AS;
6269
- abort(reason) {
6270
- if (this.signal.aborted)
6271
- return;
6272
- this.signal.reason = reason;
6273
- this.signal.aborted = true;
6274
- for (const fn of this.signal._onabort) {
6275
- fn(reason);
6276
- }
6277
- this.signal.onabort?.(reason);
6278
- }
6279
- };
6280
- let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
6281
- const warnACPolyfill = () => {
6282
- if (!printACPolyfillWarning)
6283
- return;
6284
- printACPolyfillWarning = false;
6285
- 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);
6286
- };
6287
- }
6288
- TYPE = Symbol("type");
6289
- ZeroArray = class ZeroArray extends Array {
6290
- constructor(size) {
6291
- super(size);
6292
- this.fill(0);
6293
- }
6294
- };
6295
- LRUCache = class LRUCache {
6296
- #max;
6297
- #maxSize;
6298
- #dispose;
6299
- #onInsert;
6300
- #disposeAfter;
6301
- #fetchMethod;
6302
- #memoMethod;
6303
- #perf;
6304
- get perf() {
6305
- return this.#perf;
6306
- }
6307
- ttl;
6308
- ttlResolution;
6309
- ttlAutopurge;
6310
- updateAgeOnGet;
6311
- updateAgeOnHas;
6312
- allowStale;
6313
- noDisposeOnSet;
6314
- noUpdateTTL;
6315
- maxEntrySize;
6316
- sizeCalculation;
6317
- noDeleteOnFetchRejection;
6318
- noDeleteOnStaleGet;
6319
- allowStaleOnFetchAbort;
6320
- allowStaleOnFetchRejection;
6321
- ignoreFetchAbort;
6322
- #size;
6323
- #calculatedSize;
6324
- #keyMap;
6325
- #keyList;
6326
- #valList;
6327
- #next;
6328
- #prev;
6329
- #head;
6330
- #tail;
6331
- #free;
6332
- #disposed;
6333
- #sizes;
6334
- #starts;
6335
- #ttls;
6336
- #autopurgeTimers;
6337
- #hasDispose;
6338
- #hasFetchMethod;
6339
- #hasDisposeAfter;
6340
- #hasOnInsert;
6341
- static unsafeExposeInternals(c) {
6342
- return {
6343
- starts: c.#starts,
6344
- ttls: c.#ttls,
6345
- autopurgeTimers: c.#autopurgeTimers,
6346
- sizes: c.#sizes,
6347
- keyMap: c.#keyMap,
6348
- keyList: c.#keyList,
6349
- valList: c.#valList,
6350
- next: c.#next,
6351
- prev: c.#prev,
6352
- get head() {
6353
- return c.#head;
6354
- },
6355
- get tail() {
6356
- return c.#tail;
6357
- },
6358
- free: c.#free,
6359
- isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
6360
- backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
6361
- moveToTail: (index) => c.#moveToTail(index),
6362
- indexes: (options) => c.#indexes(options),
6363
- rindexes: (options) => c.#rindexes(options),
6364
- isStale: (index) => c.#isStale(index)
6365
- };
6366
- }
6367
- get max() {
6368
- return this.#max;
6369
- }
6370
- get maxSize() {
6371
- return this.#maxSize;
6372
- }
6373
- get calculatedSize() {
6374
- return this.#calculatedSize;
6375
- }
6376
- get size() {
6377
- return this.#size;
6378
- }
6379
- get fetchMethod() {
6380
- return this.#fetchMethod;
6381
- }
6382
- get memoMethod() {
6383
- return this.#memoMethod;
6384
- }
6385
- get dispose() {
6386
- return this.#dispose;
6387
- }
6388
- get onInsert() {
6389
- return this.#onInsert;
6390
- }
6391
- get disposeAfter() {
6392
- return this.#disposeAfter;
6393
- }
6394
- constructor(options) {
6395
- 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;
6396
- if (perf !== undefined) {
6397
- if (typeof perf?.now !== "function") {
6398
- throw new TypeError("perf option must have a now() method if specified");
6399
- }
6400
- }
6401
- this.#perf = perf ?? defaultPerf;
6402
- if (max !== 0 && !isPosInt(max)) {
6403
- throw new TypeError("max option must be a nonnegative integer");
6404
- }
6405
- const UintArray = max ? getUintArray(max) : Array;
6406
- if (!UintArray) {
6407
- throw new Error("invalid max value: " + max);
6408
- }
6409
- this.#max = max;
6410
- this.#maxSize = maxSize;
6411
- this.maxEntrySize = maxEntrySize || this.#maxSize;
6412
- this.sizeCalculation = sizeCalculation;
6413
- if (this.sizeCalculation) {
6414
- if (!this.#maxSize && !this.maxEntrySize) {
6415
- throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
6416
- }
6417
- if (typeof this.sizeCalculation !== "function") {
6418
- throw new TypeError("sizeCalculation set to non-function");
6419
- }
6420
- }
6421
- if (memoMethod !== undefined && typeof memoMethod !== "function") {
6422
- throw new TypeError("memoMethod must be a function if defined");
6423
- }
6424
- this.#memoMethod = memoMethod;
6425
- if (fetchMethod !== undefined && typeof fetchMethod !== "function") {
6426
- throw new TypeError("fetchMethod must be a function if specified");
6427
- }
6428
- this.#fetchMethod = fetchMethod;
6429
- this.#hasFetchMethod = !!fetchMethod;
6430
- this.#keyMap = new Map;
6431
- this.#keyList = new Array(max).fill(undefined);
6432
- this.#valList = new Array(max).fill(undefined);
6433
- this.#next = new UintArray(max);
6434
- this.#prev = new UintArray(max);
6435
- this.#head = 0;
6436
- this.#tail = 0;
6437
- this.#free = Stack.create(max);
6438
- this.#size = 0;
6439
- this.#calculatedSize = 0;
6440
- if (typeof dispose === "function") {
6441
- this.#dispose = dispose;
6442
- }
6443
- if (typeof onInsert === "function") {
6444
- this.#onInsert = onInsert;
6445
- }
6446
- if (typeof disposeAfter === "function") {
6447
- this.#disposeAfter = disposeAfter;
6448
- this.#disposed = [];
6449
- } else {
6450
- this.#disposeAfter = undefined;
6451
- this.#disposed = undefined;
6452
- }
6453
- this.#hasDispose = !!this.#dispose;
6454
- this.#hasOnInsert = !!this.#onInsert;
6455
- this.#hasDisposeAfter = !!this.#disposeAfter;
6456
- this.noDisposeOnSet = !!noDisposeOnSet;
6457
- this.noUpdateTTL = !!noUpdateTTL;
6458
- this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
6459
- this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
6460
- this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
6461
- this.ignoreFetchAbort = !!ignoreFetchAbort;
6462
- if (this.maxEntrySize !== 0) {
6463
- if (this.#maxSize !== 0) {
6464
- if (!isPosInt(this.#maxSize)) {
6465
- throw new TypeError("maxSize must be a positive integer if specified");
6466
- }
6467
- }
6468
- if (!isPosInt(this.maxEntrySize)) {
6469
- throw new TypeError("maxEntrySize must be a positive integer if specified");
6470
- }
6471
- this.#initializeSizeTracking();
6472
- }
6473
- this.allowStale = !!allowStale;
6474
- this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
6475
- this.updateAgeOnGet = !!updateAgeOnGet;
6476
- this.updateAgeOnHas = !!updateAgeOnHas;
6477
- this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
6478
- this.ttlAutopurge = !!ttlAutopurge;
6479
- this.ttl = ttl || 0;
6480
- if (this.ttl) {
6481
- if (!isPosInt(this.ttl)) {
6482
- throw new TypeError("ttl must be a positive integer if specified");
6483
- }
6484
- this.#initializeTTLTracking();
6485
- }
6486
- if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
6487
- throw new TypeError("At least one of max, maxSize, or ttl is required");
6488
- }
6489
- if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
6490
- const code = "LRU_CACHE_UNBOUNDED";
6491
- if (shouldWarn(code)) {
6492
- warned.add(code);
6493
- const msg = "TTL caching without ttlAutopurge, max, or maxSize can " + "result in unbounded memory consumption.";
6494
- emitWarning(msg, "UnboundedCacheWarning", code, LRUCache);
6495
- }
6496
- }
6497
- }
6498
- getRemainingTTL(key) {
6499
- return this.#keyMap.has(key) ? Infinity : 0;
6500
- }
6501
- #initializeTTLTracking() {
6502
- const ttls = new ZeroArray(this.#max);
6503
- const starts = new ZeroArray(this.#max);
6504
- this.#ttls = ttls;
6505
- this.#starts = starts;
6506
- const purgeTimers = this.ttlAutopurge ? new Array(this.#max) : undefined;
6507
- this.#autopurgeTimers = purgeTimers;
6508
- this.#setItemTTL = (index, ttl, start = this.#perf.now()) => {
6509
- starts[index] = ttl !== 0 ? start : 0;
6510
- ttls[index] = ttl;
6511
- if (purgeTimers?.[index]) {
6512
- clearTimeout(purgeTimers[index]);
6513
- purgeTimers[index] = undefined;
6514
- }
6515
- if (ttl !== 0 && purgeTimers) {
6516
- const t = setTimeout(() => {
6517
- if (this.#isStale(index)) {
6518
- this.#delete(this.#keyList[index], "expire");
6519
- }
6520
- }, ttl + 1);
6521
- if (t.unref) {
6522
- t.unref();
6523
- }
6524
- purgeTimers[index] = t;
6525
- }
6526
- };
6527
- this.#updateItemAge = (index) => {
6528
- starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0;
6529
- };
6530
- this.#statusTTL = (status, index) => {
6531
- if (ttls[index]) {
6532
- const ttl = ttls[index];
6533
- const start = starts[index];
6534
- if (!ttl || !start)
6535
- return;
6536
- status.ttl = ttl;
6537
- status.start = start;
6538
- status.now = cachedNow || getNow();
6539
- const age = status.now - start;
6540
- status.remainingTTL = ttl - age;
6541
- }
6542
- };
6543
- let cachedNow = 0;
6544
- const getNow = () => {
6545
- const n = this.#perf.now();
6546
- if (this.ttlResolution > 0) {
6547
- cachedNow = n;
6548
- const t = setTimeout(() => cachedNow = 0, this.ttlResolution);
6549
- if (t.unref) {
6550
- t.unref();
6551
- }
6552
- }
6553
- return n;
6554
- };
6555
- this.getRemainingTTL = (key) => {
6556
- const index = this.#keyMap.get(key);
6557
- if (index === undefined) {
6558
- return 0;
6559
- }
6560
- const ttl = ttls[index];
6561
- const start = starts[index];
6562
- if (!ttl || !start) {
6563
- return Infinity;
6564
- }
6565
- const age = (cachedNow || getNow()) - start;
6566
- return ttl - age;
6567
- };
6568
- this.#isStale = (index) => {
6569
- const s = starts[index];
6570
- const t = ttls[index];
6571
- return !!t && !!s && (cachedNow || getNow()) - s > t;
6572
- };
6573
- }
6574
- #updateItemAge = () => {};
6575
- #statusTTL = () => {};
6576
- #setItemTTL = () => {};
6577
- #isStale = () => false;
6578
- #initializeSizeTracking() {
6579
- const sizes = new ZeroArray(this.#max);
6580
- this.#calculatedSize = 0;
6581
- this.#sizes = sizes;
6582
- this.#removeItemSize = (index) => {
6583
- this.#calculatedSize -= sizes[index];
6584
- sizes[index] = 0;
6585
- };
6586
- this.#requireSize = (k, v, size, sizeCalculation) => {
6587
- if (this.#isBackgroundFetch(v)) {
6588
- return 0;
6589
- }
6590
- if (!isPosInt(size)) {
6591
- if (sizeCalculation) {
6592
- if (typeof sizeCalculation !== "function") {
6593
- throw new TypeError("sizeCalculation must be a function");
6594
- }
6595
- size = sizeCalculation(v, k);
6596
- if (!isPosInt(size)) {
6597
- throw new TypeError("sizeCalculation return invalid (expect positive integer)");
6598
- }
6599
- } else {
6600
- throw new TypeError("invalid size value (must be positive integer). " + "When maxSize or maxEntrySize is used, sizeCalculation " + "or size must be set.");
6601
- }
6602
- }
6603
- return size;
6604
- };
6605
- this.#addItemSize = (index, size, status) => {
6606
- sizes[index] = size;
6607
- if (this.#maxSize) {
6608
- const maxSize = this.#maxSize - sizes[index];
6609
- while (this.#calculatedSize > maxSize) {
6610
- this.#evict(true);
6611
- }
6612
- }
6613
- this.#calculatedSize += sizes[index];
6614
- if (status) {
6615
- status.entrySize = size;
6616
- status.totalCalculatedSize = this.#calculatedSize;
6617
- }
6618
- };
6619
- }
6620
- #removeItemSize = (_i) => {};
6621
- #addItemSize = (_i, _s, _st) => {};
6622
- #requireSize = (_k, _v, size, sizeCalculation) => {
6623
- if (size || sizeCalculation) {
6624
- throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
6625
- }
6626
- return 0;
6627
- };
6628
- *#indexes({ allowStale = this.allowStale } = {}) {
6629
- if (this.#size) {
6630
- for (let i = this.#tail;; ) {
6631
- if (!this.#isValidIndex(i)) {
6632
- break;
6633
- }
6634
- if (allowStale || !this.#isStale(i)) {
6635
- yield i;
6636
- }
6637
- if (i === this.#head) {
6638
- break;
6639
- } else {
6640
- i = this.#prev[i];
6641
- }
6642
- }
6643
- }
6644
- }
6645
- *#rindexes({ allowStale = this.allowStale } = {}) {
6646
- if (this.#size) {
6647
- for (let i = this.#head;; ) {
6648
- if (!this.#isValidIndex(i)) {
6649
- break;
6650
- }
6651
- if (allowStale || !this.#isStale(i)) {
6652
- yield i;
6653
- }
6654
- if (i === this.#tail) {
6655
- break;
6656
- } else {
6657
- i = this.#next[i];
6658
- }
6659
- }
6660
- }
6661
- }
6662
- #isValidIndex(index) {
6663
- return index !== undefined && this.#keyMap.get(this.#keyList[index]) === index;
6664
- }
6665
- *entries() {
6666
- for (const i of this.#indexes()) {
6667
- if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6668
- yield [this.#keyList[i], this.#valList[i]];
6669
- }
6670
- }
6671
- }
6672
- *rentries() {
6673
- for (const i of this.#rindexes()) {
6674
- if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6675
- yield [this.#keyList[i], this.#valList[i]];
6676
- }
6677
- }
6678
- }
6679
- *keys() {
6680
- for (const i of this.#indexes()) {
6681
- const k = this.#keyList[i];
6682
- if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6683
- yield k;
6684
- }
6685
- }
6686
- }
6687
- *rkeys() {
6688
- for (const i of this.#rindexes()) {
6689
- const k = this.#keyList[i];
6690
- if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6691
- yield k;
6692
- }
6693
- }
6694
- }
6695
- *values() {
6696
- for (const i of this.#indexes()) {
6697
- const v = this.#valList[i];
6698
- if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6699
- yield this.#valList[i];
6700
- }
6701
- }
6702
- }
6703
- *rvalues() {
6704
- for (const i of this.#rindexes()) {
6705
- const v = this.#valList[i];
6706
- if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
6707
- yield this.#valList[i];
6708
- }
6709
- }
6710
- }
6711
- [Symbol.iterator]() {
6712
- return this.entries();
6713
- }
6714
- [Symbol.toStringTag] = "LRUCache";
6715
- find(fn, getOptions = {}) {
6716
- for (const i of this.#indexes()) {
6717
- const v = this.#valList[i];
6718
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6719
- if (value === undefined)
6720
- continue;
6721
- if (fn(value, this.#keyList[i], this)) {
6722
- return this.get(this.#keyList[i], getOptions);
6723
- }
6724
- }
6725
- }
6726
- forEach(fn, thisp = this) {
6727
- for (const i of this.#indexes()) {
6728
- const v = this.#valList[i];
6729
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6730
- if (value === undefined)
6731
- continue;
6732
- fn.call(thisp, value, this.#keyList[i], this);
6733
- }
6734
- }
6735
- rforEach(fn, thisp = this) {
6736
- for (const i of this.#rindexes()) {
6737
- const v = this.#valList[i];
6738
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6739
- if (value === undefined)
6740
- continue;
6741
- fn.call(thisp, value, this.#keyList[i], this);
6742
- }
6743
- }
6744
- purgeStale() {
6745
- let deleted = false;
6746
- for (const i of this.#rindexes({ allowStale: true })) {
6747
- if (this.#isStale(i)) {
6748
- this.#delete(this.#keyList[i], "expire");
6749
- deleted = true;
6750
- }
6751
- }
6752
- return deleted;
6753
- }
6754
- info(key) {
6755
- const i = this.#keyMap.get(key);
6756
- if (i === undefined)
6757
- return;
6758
- const v = this.#valList[i];
6759
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6760
- if (value === undefined)
6761
- return;
6762
- const entry = { value };
6763
- if (this.#ttls && this.#starts) {
6764
- const ttl = this.#ttls[i];
6765
- const start = this.#starts[i];
6766
- if (ttl && start) {
6767
- const remain = ttl - (this.#perf.now() - start);
6768
- entry.ttl = remain;
6769
- entry.start = Date.now();
6770
- }
6771
- }
6772
- if (this.#sizes) {
6773
- entry.size = this.#sizes[i];
6774
- }
6775
- return entry;
6776
- }
6777
- dump() {
6778
- const arr = [];
6779
- for (const i of this.#indexes({ allowStale: true })) {
6780
- const key = this.#keyList[i];
6781
- const v = this.#valList[i];
6782
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6783
- if (value === undefined || key === undefined)
6784
- continue;
6785
- const entry = { value };
6786
- if (this.#ttls && this.#starts) {
6787
- entry.ttl = this.#ttls[i];
6788
- const age = this.#perf.now() - this.#starts[i];
6789
- entry.start = Math.floor(Date.now() - age);
6790
- }
6791
- if (this.#sizes) {
6792
- entry.size = this.#sizes[i];
6793
- }
6794
- arr.unshift([key, entry]);
6795
- }
6796
- return arr;
6797
- }
6798
- load(arr) {
6799
- this.clear();
6800
- for (const [key, entry] of arr) {
6801
- if (entry.start) {
6802
- const age = Date.now() - entry.start;
6803
- entry.start = this.#perf.now() - age;
6804
- }
6805
- this.set(key, entry.value, entry);
6806
- }
6807
- }
6808
- set(k, v, setOptions = {}) {
6809
- if (v === undefined) {
6810
- this.delete(k);
6811
- return this;
6812
- }
6813
- const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
6814
- let { noUpdateTTL = this.noUpdateTTL } = setOptions;
6815
- const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
6816
- if (this.maxEntrySize && size > this.maxEntrySize) {
6817
- if (status) {
6818
- status.set = "miss";
6819
- status.maxEntrySizeExceeded = true;
6820
- }
6821
- this.#delete(k, "set");
6822
- return this;
6823
- }
6824
- let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
6825
- if (index === undefined) {
6826
- index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
6827
- this.#keyList[index] = k;
6828
- this.#valList[index] = v;
6829
- this.#keyMap.set(k, index);
6830
- this.#next[this.#tail] = index;
6831
- this.#prev[index] = this.#tail;
6832
- this.#tail = index;
6833
- this.#size++;
6834
- this.#addItemSize(index, size, status);
6835
- if (status)
6836
- status.set = "add";
6837
- noUpdateTTL = false;
6838
- if (this.#hasOnInsert) {
6839
- this.#onInsert?.(v, k, "add");
6840
- }
6841
- } else {
6842
- this.#moveToTail(index);
6843
- const oldVal = this.#valList[index];
6844
- if (v !== oldVal) {
6845
- if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
6846
- oldVal.__abortController.abort(new Error("replaced"));
6847
- const { __staleWhileFetching: s } = oldVal;
6848
- if (s !== undefined && !noDisposeOnSet) {
6849
- if (this.#hasDispose) {
6850
- this.#dispose?.(s, k, "set");
6851
- }
6852
- if (this.#hasDisposeAfter) {
6853
- this.#disposed?.push([s, k, "set"]);
6854
- }
6855
- }
6856
- } else if (!noDisposeOnSet) {
6857
- if (this.#hasDispose) {
6858
- this.#dispose?.(oldVal, k, "set");
6859
- }
6860
- if (this.#hasDisposeAfter) {
6861
- this.#disposed?.push([oldVal, k, "set"]);
6862
- }
6863
- }
6864
- this.#removeItemSize(index);
6865
- this.#addItemSize(index, size, status);
6866
- this.#valList[index] = v;
6867
- if (status) {
6868
- status.set = "replace";
6869
- const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
6870
- if (oldValue !== undefined)
6871
- status.oldValue = oldValue;
6872
- }
6873
- } else if (status) {
6874
- status.set = "update";
6875
- }
6876
- if (this.#hasOnInsert) {
6877
- this.onInsert?.(v, k, v === oldVal ? "update" : "replace");
6878
- }
6879
- }
6880
- if (ttl !== 0 && !this.#ttls) {
6881
- this.#initializeTTLTracking();
6882
- }
6883
- if (this.#ttls) {
6884
- if (!noUpdateTTL) {
6885
- this.#setItemTTL(index, ttl, start);
6886
- }
6887
- if (status)
6888
- this.#statusTTL(status, index);
6889
- }
6890
- if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
6891
- const dt = this.#disposed;
6892
- let task;
6893
- while (task = dt?.shift()) {
6894
- this.#disposeAfter?.(...task);
6895
- }
6896
- }
6897
- return this;
6898
- }
6899
- pop() {
6900
- try {
6901
- while (this.#size) {
6902
- const val = this.#valList[this.#head];
6903
- this.#evict(true);
6904
- if (this.#isBackgroundFetch(val)) {
6905
- if (val.__staleWhileFetching) {
6906
- return val.__staleWhileFetching;
6907
- }
6908
- } else if (val !== undefined) {
6909
- return val;
6910
- }
6911
- }
6912
- } finally {
6913
- if (this.#hasDisposeAfter && this.#disposed) {
6914
- const dt = this.#disposed;
6915
- let task;
6916
- while (task = dt?.shift()) {
6917
- this.#disposeAfter?.(...task);
6918
- }
6919
- }
6920
- }
6921
- }
6922
- #evict(free) {
6923
- const head = this.#head;
6924
- const k = this.#keyList[head];
6925
- const v = this.#valList[head];
6926
- if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
6927
- v.__abortController.abort(new Error("evicted"));
6928
- } else if (this.#hasDispose || this.#hasDisposeAfter) {
6929
- if (this.#hasDispose) {
6930
- this.#dispose?.(v, k, "evict");
6931
- }
6932
- if (this.#hasDisposeAfter) {
6933
- this.#disposed?.push([v, k, "evict"]);
6934
- }
6935
- }
6936
- this.#removeItemSize(head);
6937
- if (this.#autopurgeTimers?.[head]) {
6938
- clearTimeout(this.#autopurgeTimers[head]);
6939
- this.#autopurgeTimers[head] = undefined;
6940
- }
6941
- if (free) {
6942
- this.#keyList[head] = undefined;
6943
- this.#valList[head] = undefined;
6944
- this.#free.push(head);
6945
- }
6946
- if (this.#size === 1) {
6947
- this.#head = this.#tail = 0;
6948
- this.#free.length = 0;
6949
- } else {
6950
- this.#head = this.#next[head];
6951
- }
6952
- this.#keyMap.delete(k);
6953
- this.#size--;
6954
- return head;
6955
- }
6956
- has(k, hasOptions = {}) {
6957
- const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
6958
- const index = this.#keyMap.get(k);
6959
- if (index !== undefined) {
6960
- const v = this.#valList[index];
6961
- if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === undefined) {
6962
- return false;
6963
- }
6964
- if (!this.#isStale(index)) {
6965
- if (updateAgeOnHas) {
6966
- this.#updateItemAge(index);
6967
- }
6968
- if (status) {
6969
- status.has = "hit";
6970
- this.#statusTTL(status, index);
6971
- }
6972
- return true;
6973
- } else if (status) {
6974
- status.has = "stale";
6975
- this.#statusTTL(status, index);
6976
- }
6977
- } else if (status) {
6978
- status.has = "miss";
6979
- }
6980
- return false;
6981
- }
6982
- peek(k, peekOptions = {}) {
6983
- const { allowStale = this.allowStale } = peekOptions;
6984
- const index = this.#keyMap.get(k);
6985
- if (index === undefined || !allowStale && this.#isStale(index)) {
6986
- return;
6987
- }
6988
- const v = this.#valList[index];
6989
- return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
6990
- }
6991
- #backgroundFetch(k, index, options, context) {
6992
- const v = index === undefined ? undefined : this.#valList[index];
6993
- if (this.#isBackgroundFetch(v)) {
6994
- return v;
6995
- }
6996
- const ac = new AC;
6997
- const { signal } = options;
6998
- signal?.addEventListener("abort", () => ac.abort(signal.reason), {
6999
- signal: ac.signal
7000
- });
7001
- const fetchOpts = {
7002
- signal: ac.signal,
7003
- options,
7004
- context
7005
- };
7006
- const cb = (v2, updateCache = false) => {
7007
- const { aborted } = ac.signal;
7008
- const ignoreAbort = options.ignoreFetchAbort && v2 !== undefined;
7009
- if (options.status) {
7010
- if (aborted && !updateCache) {
7011
- options.status.fetchAborted = true;
7012
- options.status.fetchError = ac.signal.reason;
7013
- if (ignoreAbort)
7014
- options.status.fetchAbortIgnored = true;
7015
- } else {
7016
- options.status.fetchResolved = true;
7017
- }
7018
- }
7019
- if (aborted && !ignoreAbort && !updateCache) {
7020
- return fetchFail(ac.signal.reason);
7021
- }
7022
- const bf2 = p;
7023
- const vl = this.#valList[index];
7024
- if (vl === p || ignoreAbort && updateCache && vl === undefined) {
7025
- if (v2 === undefined) {
7026
- if (bf2.__staleWhileFetching !== undefined) {
7027
- this.#valList[index] = bf2.__staleWhileFetching;
7028
- } else {
7029
- this.#delete(k, "fetch");
7030
- }
7031
- } else {
7032
- if (options.status)
7033
- options.status.fetchUpdated = true;
7034
- this.set(k, v2, fetchOpts.options);
7035
- }
7036
- }
7037
- return v2;
7038
- };
7039
- const eb = (er) => {
7040
- if (options.status) {
7041
- options.status.fetchRejected = true;
7042
- options.status.fetchError = er;
7043
- }
7044
- return fetchFail(er);
7045
- };
7046
- const fetchFail = (er) => {
7047
- const { aborted } = ac.signal;
7048
- const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
7049
- const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
7050
- const noDelete = allowStale || options.noDeleteOnFetchRejection;
7051
- const bf2 = p;
7052
- if (this.#valList[index] === p) {
7053
- const del = !noDelete || bf2.__staleWhileFetching === undefined;
7054
- if (del) {
7055
- this.#delete(k, "fetch");
7056
- } else if (!allowStaleAborted) {
7057
- this.#valList[index] = bf2.__staleWhileFetching;
7058
- }
7059
- }
7060
- if (allowStale) {
7061
- if (options.status && bf2.__staleWhileFetching !== undefined) {
7062
- options.status.returnedStale = true;
7063
- }
7064
- return bf2.__staleWhileFetching;
7065
- } else if (bf2.__returned === bf2) {
7066
- throw er;
7067
- }
7068
- };
7069
- const pcall = (res, rej) => {
7070
- const fmp = this.#fetchMethod?.(k, v, fetchOpts);
7071
- if (fmp && fmp instanceof Promise) {
7072
- fmp.then((v2) => res(v2 === undefined ? undefined : v2), rej);
7073
- }
7074
- ac.signal.addEventListener("abort", () => {
7075
- if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
7076
- res(undefined);
7077
- if (options.allowStaleOnFetchAbort) {
7078
- res = (v2) => cb(v2, true);
7079
- }
7080
- }
7081
- });
7082
- };
7083
- if (options.status)
7084
- options.status.fetchDispatched = true;
7085
- const p = new Promise(pcall).then(cb, eb);
7086
- const bf = Object.assign(p, {
7087
- __abortController: ac,
7088
- __staleWhileFetching: v,
7089
- __returned: undefined
7090
- });
7091
- if (index === undefined) {
7092
- this.set(k, bf, { ...fetchOpts.options, status: undefined });
7093
- index = this.#keyMap.get(k);
7094
- } else {
7095
- this.#valList[index] = bf;
7096
- }
7097
- return bf;
7098
- }
7099
- #isBackgroundFetch(p) {
7100
- if (!this.#hasFetchMethod)
7101
- return false;
7102
- const b = p;
7103
- return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
7104
- }
7105
- async fetch(k, fetchOptions = {}) {
7106
- const {
7107
- allowStale = this.allowStale,
7108
- updateAgeOnGet = this.updateAgeOnGet,
7109
- noDeleteOnStaleGet = this.noDeleteOnStaleGet,
7110
- ttl = this.ttl,
7111
- noDisposeOnSet = this.noDisposeOnSet,
7112
- size = 0,
7113
- sizeCalculation = this.sizeCalculation,
7114
- noUpdateTTL = this.noUpdateTTL,
7115
- noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
7116
- allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
7117
- ignoreFetchAbort = this.ignoreFetchAbort,
7118
- allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
7119
- context,
7120
- forceRefresh = false,
7121
- status,
7122
- signal
7123
- } = fetchOptions;
7124
- if (!this.#hasFetchMethod) {
7125
- if (status)
7126
- status.fetch = "get";
7127
- return this.get(k, {
7128
- allowStale,
7129
- updateAgeOnGet,
7130
- noDeleteOnStaleGet,
7131
- status
7132
- });
7133
- }
7134
- const options = {
7135
- allowStale,
7136
- updateAgeOnGet,
7137
- noDeleteOnStaleGet,
7138
- ttl,
7139
- noDisposeOnSet,
7140
- size,
7141
- sizeCalculation,
7142
- noUpdateTTL,
7143
- noDeleteOnFetchRejection,
7144
- allowStaleOnFetchRejection,
7145
- allowStaleOnFetchAbort,
7146
- ignoreFetchAbort,
7147
- status,
7148
- signal
7149
- };
7150
- let index = this.#keyMap.get(k);
7151
- if (index === undefined) {
7152
- if (status)
7153
- status.fetch = "miss";
7154
- const p = this.#backgroundFetch(k, index, options, context);
7155
- return p.__returned = p;
7156
- } else {
7157
- const v = this.#valList[index];
7158
- if (this.#isBackgroundFetch(v)) {
7159
- const stale = allowStale && v.__staleWhileFetching !== undefined;
7160
- if (status) {
7161
- status.fetch = "inflight";
7162
- if (stale)
7163
- status.returnedStale = true;
7164
- }
7165
- return stale ? v.__staleWhileFetching : v.__returned = v;
7166
- }
7167
- const isStale = this.#isStale(index);
7168
- if (!forceRefresh && !isStale) {
7169
- if (status)
7170
- status.fetch = "hit";
7171
- this.#moveToTail(index);
7172
- if (updateAgeOnGet) {
7173
- this.#updateItemAge(index);
7174
- }
7175
- if (status)
7176
- this.#statusTTL(status, index);
7177
- return v;
7178
- }
7179
- const p = this.#backgroundFetch(k, index, options, context);
7180
- const hasStale = p.__staleWhileFetching !== undefined;
7181
- const staleVal = hasStale && allowStale;
7182
- if (status) {
7183
- status.fetch = isStale ? "stale" : "refresh";
7184
- if (staleVal && isStale)
7185
- status.returnedStale = true;
7186
- }
7187
- return staleVal ? p.__staleWhileFetching : p.__returned = p;
7188
- }
7189
- }
7190
- async forceFetch(k, fetchOptions = {}) {
7191
- const v = await this.fetch(k, fetchOptions);
7192
- if (v === undefined)
7193
- throw new Error("fetch() returned undefined");
7194
- return v;
7195
- }
7196
- memo(k, memoOptions = {}) {
7197
- const memoMethod = this.#memoMethod;
7198
- if (!memoMethod) {
7199
- throw new Error("no memoMethod provided to constructor");
7200
- }
7201
- const { context, forceRefresh, ...options } = memoOptions;
7202
- const v = this.get(k, options);
7203
- if (!forceRefresh && v !== undefined)
7204
- return v;
7205
- const vv = memoMethod(k, v, {
7206
- options,
7207
- context
7208
- });
7209
- this.set(k, vv, options);
7210
- return vv;
7211
- }
7212
- get(k, getOptions = {}) {
7213
- const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
7214
- const index = this.#keyMap.get(k);
7215
- if (index !== undefined) {
7216
- const value = this.#valList[index];
7217
- const fetching = this.#isBackgroundFetch(value);
7218
- if (status)
7219
- this.#statusTTL(status, index);
7220
- if (this.#isStale(index)) {
7221
- if (status)
7222
- status.get = "stale";
7223
- if (!fetching) {
7224
- if (!noDeleteOnStaleGet) {
7225
- this.#delete(k, "expire");
7226
- }
7227
- if (status && allowStale)
7228
- status.returnedStale = true;
7229
- return allowStale ? value : undefined;
7230
- } else {
7231
- if (status && allowStale && value.__staleWhileFetching !== undefined) {
7232
- status.returnedStale = true;
7233
- }
7234
- return allowStale ? value.__staleWhileFetching : undefined;
7235
- }
7236
- } else {
7237
- if (status)
7238
- status.get = "hit";
7239
- if (fetching) {
7240
- return value.__staleWhileFetching;
7241
- }
7242
- this.#moveToTail(index);
7243
- if (updateAgeOnGet) {
7244
- this.#updateItemAge(index);
7245
- }
7246
- return value;
7247
- }
7248
- } else if (status) {
7249
- status.get = "miss";
7250
- }
7251
- }
7252
- #connect(p, n) {
7253
- this.#prev[n] = p;
7254
- this.#next[p] = n;
7255
- }
7256
- #moveToTail(index) {
7257
- if (index !== this.#tail) {
7258
- if (index === this.#head) {
7259
- this.#head = this.#next[index];
7260
- } else {
7261
- this.#connect(this.#prev[index], this.#next[index]);
7262
- }
7263
- this.#connect(this.#tail, index);
7264
- this.#tail = index;
7265
- }
7266
- }
7267
- delete(k) {
7268
- return this.#delete(k, "delete");
7269
- }
7270
- #delete(k, reason) {
7271
- let deleted = false;
7272
- if (this.#size !== 0) {
7273
- const index = this.#keyMap.get(k);
7274
- if (index !== undefined) {
7275
- if (this.#autopurgeTimers?.[index]) {
7276
- clearTimeout(this.#autopurgeTimers?.[index]);
7277
- this.#autopurgeTimers[index] = undefined;
7278
- }
7279
- deleted = true;
7280
- if (this.#size === 1) {
7281
- this.#clear(reason);
7282
- } else {
7283
- this.#removeItemSize(index);
7284
- const v = this.#valList[index];
7285
- if (this.#isBackgroundFetch(v)) {
7286
- v.__abortController.abort(new Error("deleted"));
7287
- } else if (this.#hasDispose || this.#hasDisposeAfter) {
7288
- if (this.#hasDispose) {
7289
- this.#dispose?.(v, k, reason);
7290
- }
7291
- if (this.#hasDisposeAfter) {
7292
- this.#disposed?.push([v, k, reason]);
7293
- }
7294
- }
7295
- this.#keyMap.delete(k);
7296
- this.#keyList[index] = undefined;
7297
- this.#valList[index] = undefined;
7298
- if (index === this.#tail) {
7299
- this.#tail = this.#prev[index];
7300
- } else if (index === this.#head) {
7301
- this.#head = this.#next[index];
7302
- } else {
7303
- const pi = this.#prev[index];
7304
- this.#next[pi] = this.#next[index];
7305
- const ni = this.#next[index];
7306
- this.#prev[ni] = this.#prev[index];
7307
- }
7308
- this.#size--;
7309
- this.#free.push(index);
7310
- }
7311
- }
7312
- }
7313
- if (this.#hasDisposeAfter && this.#disposed?.length) {
7314
- const dt = this.#disposed;
7315
- let task;
7316
- while (task = dt?.shift()) {
7317
- this.#disposeAfter?.(...task);
7318
- }
7319
- }
7320
- return deleted;
7321
- }
7322
- clear() {
7323
- return this.#clear("delete");
7324
- }
7325
- #clear(reason) {
7326
- for (const index of this.#rindexes({ allowStale: true })) {
7327
- const v = this.#valList[index];
7328
- if (this.#isBackgroundFetch(v)) {
7329
- v.__abortController.abort(new Error("deleted"));
7330
- } else {
7331
- const k = this.#keyList[index];
7332
- if (this.#hasDispose) {
7333
- this.#dispose?.(v, k, reason);
7334
- }
7335
- if (this.#hasDisposeAfter) {
7336
- this.#disposed?.push([v, k, reason]);
7337
- }
7338
- }
7339
- }
7340
- this.#keyMap.clear();
7341
- this.#valList.fill(undefined);
7342
- this.#keyList.fill(undefined);
7343
- if (this.#ttls && this.#starts) {
7344
- this.#ttls.fill(0);
7345
- this.#starts.fill(0);
7346
- for (const t of this.#autopurgeTimers ?? []) {
7347
- if (t !== undefined)
7348
- clearTimeout(t);
7349
- }
7350
- this.#autopurgeTimers?.fill(undefined);
7351
- }
7352
- if (this.#sizes) {
7353
- this.#sizes.fill(0);
7354
- }
7355
- this.#head = 0;
7356
- this.#tail = 0;
7357
- this.#free.length = 0;
7358
- this.#calculatedSize = 0;
7359
- this.#size = 0;
7360
- if (this.#hasDisposeAfter && this.#disposed) {
7361
- const dt = this.#disposed;
7362
- let task;
7363
- while (task = dt?.shift()) {
7364
- this.#disposeAfter?.(...task);
7365
- }
7366
- }
7367
- }
7368
- };
7369
- });
7370
-
7371
5355
  // src/utils/cache.ts
7372
5356
  import crypto3 from "crypto";
5357
+ import { LRUCache } from "lru-cache";
7373
5358
  function getCacheKey(args) {
7374
5359
  const hash = crypto3.createHash("sha1");
7375
5360
  for (const arg of args) {
@@ -7394,7 +5379,6 @@ function writeCache(result, args) {
7394
5379
  }
7395
5380
  var config, cache;
7396
5381
  var init_cache = __esm(() => {
7397
- init_esm2();
7398
5382
  init_config();
7399
5383
  config = getConfig();
7400
5384
  cache = new LRUCache({
@@ -10181,8 +8165,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
10181
8165
  }
10182
8166
  dateObj[formatWord.charAt(0)] = dateWord;
10183
8167
  }
10184
- } catch (err2) {
10185
- _iterator.e(err2);
8168
+ } catch (err) {
8169
+ _iterator.e(err);
10186
8170
  } finally {
10187
8171
  _iterator.f();
10188
8172
  }
@@ -14211,8 +12195,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
14211
12195
  allowedParams.delete(key);
14212
12196
  }
14213
12197
  }
14214
- } catch (err2) {
14215
- _iterator.e(err2);
12198
+ } catch (err) {
12199
+ _iterator.e(err);
14216
12200
  } finally {
14217
12201
  _iterator.f();
14218
12202
  }
@@ -26760,7 +24744,7 @@ var require_source_map_support = __commonJS((exports, module) => {
26760
24744
  if (!fs6.existsSync || !fs6.readFileSync) {
26761
24745
  fs6 = null;
26762
24746
  }
26763
- } catch (err2) {}
24747
+ } catch (err) {}
26764
24748
  var bufferFrom = require_buffer_from();
26765
24749
  function dynamicRequire(mod, request) {
26766
24750
  return mod.require(request);
@@ -27212,7 +25196,7 @@ var require_source_map_support = __commonJS((exports, module) => {
27212
25196
 
27213
25197
  // node_modules/typescript/lib/typescript.js
27214
25198
  var require_typescript = __commonJS((exports, module) => {
27215
- var __dirname = "/home/xxnuo/projects/MTran/MTranServer/node_modules/typescript/lib", __filename = "/home/xxnuo/projects/MTran/MTranServer/node_modules/typescript/lib/typescript.js";
25199
+ var __dirname = "/Volumes/MacData/Users/xxnuo/projects/MTranServer/node_modules/typescript/lib", __filename = "/Volumes/MacData/Users/xxnuo/projects/MTranServer/node_modules/typescript/lib/typescript.js";
27216
25200
  /*! *****************************************************************************
27217
25201
  Copyright (c) Microsoft Corporation. All rights reserved.
27218
25202
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
@@ -29203,7 +27187,7 @@ var require_typescript = __commonJS((exports, module) => {
29203
27187
  rangeStartIsOnSameLineAsRangeEnd: () => rangeStartIsOnSameLineAsRangeEnd,
29204
27188
  rangeStartPositionsAreOnSameLine: () => rangeStartPositionsAreOnSameLine,
29205
27189
  readBuilderProgram: () => readBuilderProgram,
29206
- readConfigFile: () => readConfigFile,
27190
+ readConfigFile: () => readConfigFile2,
29207
27191
  readJson: () => readJson,
29208
27192
  readJsonConfigFile: () => readJsonConfigFile,
29209
27193
  readJsonOrUndefined: () => readJsonOrUndefined,
@@ -31702,7 +29686,7 @@ m2: ${this.mapper2.__debugToString().split(`
31702
29686
  return height2 + 1;
31703
29687
  }
31704
29688
  function computeColumnWidths(height2) {
31705
- const columns = fill2(Array(height2), 0);
29689
+ const columns = fill(Array(height2), 0);
31706
29690
  for (const node of nodes) {
31707
29691
  columns[node.level] = Math.max(columns[node.level], node.text.length);
31708
29692
  }
@@ -31781,9 +29765,9 @@ m2: ${this.mapper2.__debugToString().split(`
31781
29765
  function renderGraph() {
31782
29766
  const columnCount = columnWidths.length;
31783
29767
  const laneCount = maxBy(nodes, 0, (n) => n.lane) + 1;
31784
- const lanes = fill2(Array(laneCount), "");
29768
+ const lanes = fill(Array(laneCount), "");
31785
29769
  const grid = columnWidths.map(() => Array(laneCount));
31786
- const connectors = columnWidths.map(() => fill2(Array(laneCount), 0));
29770
+ const connectors = columnWidths.map(() => fill(Array(laneCount), 0));
31787
29771
  for (const node of nodes) {
31788
29772
  grid[node.level][node.lane] = node;
31789
29773
  const children = getChildren(node);
@@ -31829,17 +29813,17 @@ m2: ${this.mapper2.__debugToString().split(`
31829
29813
  for (let column = 0;column < columnCount; column++) {
31830
29814
  for (let lane = 0;lane < lanes.length; lane++) {
31831
29815
  const connector = connectors[column][lane];
31832
- const fill22 = connector & 4 ? "─" : " ";
29816
+ const fill2 = connector & 4 ? "─" : " ";
31833
29817
  const node = grid[column][lane];
31834
29818
  if (!node) {
31835
29819
  if (column < columnCount - 1) {
31836
- writeLane(lane, repeat(fill22, columnWidths[column] + 1));
29820
+ writeLane(lane, repeat(fill2, columnWidths[column] + 1));
31837
29821
  }
31838
29822
  } else {
31839
29823
  writeLane(lane, node.text);
31840
29824
  if (column < columnCount - 1) {
31841
29825
  writeLane(lane, " ");
31842
- writeLane(lane, repeat(fill22, columnWidths[column] - node.text.length));
29826
+ writeLane(lane, repeat(fill2, columnWidths[column] - node.text.length));
31843
29827
  }
31844
29828
  }
31845
29829
  writeLane(lane, getBoxCharacter(connector));
@@ -31881,7 +29865,7 @@ ${lanes.join(`
31881
29865
  }
31882
29866
  return " ";
31883
29867
  }
31884
- function fill2(array, value) {
29868
+ function fill(array, value) {
31885
29869
  if (array.fill) {
31886
29870
  array.fill(value);
31887
29871
  } else {
@@ -35414,9 +33398,9 @@ ${lanes.join(`
35414
33398
  function disableCPUProfiler(cb) {
35415
33399
  if (activeSession && activeSession !== "stopping") {
35416
33400
  const s = activeSession;
35417
- activeSession.post("Profiler.stop", (err2, { profile }) => {
33401
+ activeSession.post("Profiler.stop", (err, { profile }) => {
35418
33402
  var _a;
35419
- if (!err2) {
33403
+ if (!err) {
35420
33404
  if ((_a = statSync(profilePath)) == null ? undefined : _a.isDirectory()) {
35421
33405
  profilePath = _path.join(profilePath, `${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}+P${process.pid}.cpuprofile`);
35422
33406
  }
@@ -66631,7 +64615,7 @@ ${lanes.join(`
66631
64615
  result.originalFileName = result.fileName;
66632
64616
  return parseJsonSourceFileConfigFileContent(result, host, getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), optionsToExtend, getNormalizedAbsolutePath(configFileName, cwd), undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
66633
64617
  }
66634
- function readConfigFile(fileName, readFile3) {
64618
+ function readConfigFile2(fileName, readFile3) {
66635
64619
  const textOrDiagnostic = tryReadFile(fileName, readFile3);
66636
64620
  return isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
66637
64621
  }
@@ -75134,17 +73118,17 @@ ${lanes.join(`
75134
73118
  }
75135
73119
  function addDuplicateDeclarationError(node, message, symbolName2, relatedNodes) {
75136
73120
  const errorNode = (getExpandoInitializer(node, false) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node;
75137
- const err2 = lookupOrIssueError(errorNode, message, symbolName2);
73121
+ const err = lookupOrIssueError(errorNode, message, symbolName2);
75138
73122
  for (const relatedNode of relatedNodes || emptyArray) {
75139
73123
  const adjustedNode = (getExpandoInitializer(relatedNode, false) ? getNameOfExpando(relatedNode) : getNameOfDeclaration(relatedNode)) || relatedNode;
75140
73124
  if (adjustedNode === errorNode)
75141
73125
  continue;
75142
- err2.relatedInformation = err2.relatedInformation || [];
73126
+ err.relatedInformation = err.relatedInformation || [];
75143
73127
  const leadingMessage = createDiagnosticForNode(adjustedNode, Diagnostics._0_was_also_declared_here, symbolName2);
75144
73128
  const followOnMessage = createDiagnosticForNode(adjustedNode, Diagnostics.and_here);
75145
- if (length(err2.relatedInformation) >= 5 || some(err2.relatedInformation, (r) => compareDiagnostics(r, followOnMessage) === 0 || compareDiagnostics(r, leadingMessage) === 0))
73129
+ if (length(err.relatedInformation) >= 5 || some(err.relatedInformation, (r) => compareDiagnostics(r, followOnMessage) === 0 || compareDiagnostics(r, leadingMessage) === 0))
75146
73130
  continue;
75147
- addRelatedInfo(err2, !length(err2.relatedInformation) ? leadingMessage : followOnMessage);
73131
+ addRelatedInfo(err, !length(err.relatedInformation) ? leadingMessage : followOnMessage);
75148
73132
  }
75149
73133
  }
75150
73134
  function combineSymbolTables(first2, second) {
@@ -75851,9 +73835,9 @@ ${lanes.join(`
75851
73835
  const compilerOptionName = moduleKind >= 5 ? "allowSyntheticDefaultImports" : "esModuleInterop";
75852
73836
  const exportEqualsSymbol = moduleSymbol.exports.get("export=");
75853
73837
  const exportAssignment = exportEqualsSymbol.valueDeclaration;
75854
- const err2 = error22(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
73838
+ const err = error22(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
75855
73839
  if (exportAssignment) {
75856
- addRelatedInfo(err2, createDiagnosticForNode(exportAssignment, Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName));
73840
+ addRelatedInfo(err, createDiagnosticForNode(exportAssignment, Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName));
75857
73841
  }
75858
73842
  } else if (isImportClause(node)) {
75859
73843
  reportNonDefaultExport(moduleSymbol, node);
@@ -82399,7 +80383,7 @@ ${lanes.join(`
82399
80383
  return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType);
82400
80384
  }
82401
80385
  if (!(baseConstructorType.flags & 1) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
82402
- const err2 = error22(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
80386
+ const err = error22(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
82403
80387
  if (baseConstructorType.flags & 262144) {
82404
80388
  const constraint = getConstraintFromTypeParameter(baseConstructorType);
82405
80389
  let ctorReturn = unknownType;
@@ -82410,7 +80394,7 @@ ${lanes.join(`
82410
80394
  }
82411
80395
  }
82412
80396
  if (baseConstructorType.symbol.declarations) {
82413
- addRelatedInfo(err2, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
80397
+ addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
82414
80398
  }
82415
80399
  }
82416
80400
  return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType);
@@ -102515,13 +100499,13 @@ ${lanes.join(`
102515
100499
  const isLeftNaN = isGlobalNaN(skipParentheses(left2));
102516
100500
  const isRightNaN = isGlobalNaN(skipParentheses(right2));
102517
100501
  if (isLeftNaN || isRightNaN) {
102518
- const err2 = error22(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === 37 || operator2 === 35 ? 97 : 112));
100502
+ const err = error22(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === 37 || operator2 === 35 ? 97 : 112));
102519
100503
  if (isLeftNaN && isRightNaN)
102520
100504
  return;
102521
100505
  const operatorString = operator2 === 38 || operator2 === 36 ? tokenToString(54) : "";
102522
100506
  const location = isLeftNaN ? right2 : left2;
102523
100507
  const expression = skipParentheses(location);
102524
- addRelatedInfo(err2, createDiagnosticForNode(location, Diagnostics.Did_you_mean_0, `${operatorString}Number.isNaN(${isEntityNameExpression(expression) ? entityNameToString(expression) : "..."})`));
100508
+ addRelatedInfo(err, createDiagnosticForNode(location, Diagnostics.Did_you_mean_0, `${operatorString}Number.isNaN(${isEntityNameExpression(expression) ? entityNameToString(expression) : "..."})`));
102525
100509
  }
102526
100510
  }
102527
100511
  function isGlobalNaN(expr) {
@@ -105343,9 +103327,9 @@ ${lanes.join(`
105343
103327
  const nextDeclarationName = getNameOfDeclaration(nextDeclaration);
105344
103328
  const message = nextDeclaration.kind === 173 || nextDeclaration.kind === 172 ? Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
105345
103329
  const declName = declarationNameToString(nextDeclarationName);
105346
- const err2 = error22(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
103330
+ const err = error22(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
105347
103331
  if (firstDeclaration) {
105348
- addRelatedInfo(err2, createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName));
103332
+ addRelatedInfo(err, createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName));
105349
103333
  }
105350
103334
  }
105351
103335
  function areDeclarationFlagsIdentical(left, right) {
@@ -142759,7 +140743,7 @@ ${lanes.join(`
142759
140743
  (_b = (_a = state.hostWithWatch).onWatchStatusChange) == null || _b.call(_a, createCompilerDiagnostic(message, ...args), state.host.getNewLine(), state.baseCompilerOptions);
142760
140744
  }
142761
140745
  function reportErrors({ host }, errors) {
142762
- errors.forEach((err2) => host.reportDiagnostic(err2));
140746
+ errors.forEach((err) => host.reportDiagnostic(err));
142763
140747
  }
142764
140748
  function reportAndStoreErrors(state, proj, errors) {
142765
140749
  reportErrors(state, errors);
@@ -144657,12 +142641,12 @@ ${lanes.join(`
144657
142641
  return nodeCoreModules.has(moduleName) ? "node" : moduleName;
144658
142642
  }
144659
142643
  function loadSafeList(host, safeListPath) {
144660
- const result = readConfigFile(safeListPath, (path8) => host.readFile(path8));
142644
+ const result = readConfigFile2(safeListPath, (path8) => host.readFile(path8));
144661
142645
  return new Map(Object.entries(result.config));
144662
142646
  }
144663
142647
  function loadTypesMap(host, typesMapPath) {
144664
142648
  var _a;
144665
- const result = readConfigFile(typesMapPath, (path8) => host.readFile(path8));
142649
+ const result = readConfigFile2(typesMapPath, (path8) => host.readFile(path8));
144666
142650
  if ((_a = result.config) == null ? undefined : _a.simpleMap) {
144667
142651
  return new Map(Object.entries(result.config.simpleMap));
144668
142652
  }
@@ -144738,7 +142722,7 @@ ${lanes.join(`
144738
142722
  let manifestTypingNames;
144739
142723
  if (host.fileExists(manifestPath)) {
144740
142724
  filesToWatch2.push(manifestPath);
144741
- manifest = readConfigFile(manifestPath, (path8) => host.readFile(path8)).config;
142725
+ manifest = readConfigFile2(manifestPath, (path8) => host.readFile(path8)).config;
144742
142726
  manifestTypingNames = flatMap([manifest.dependencies, manifest.devDependencies, manifest.optionalDependencies, manifest.peerDependencies], getOwnKeys);
144743
142727
  addInferredTypings(manifestTypingNames, `Typing names in '${manifestPath}' dependencies`);
144744
142728
  }
@@ -144760,7 +142744,7 @@ ${lanes.join(`
144760
142744
  log2(`Searching for typing names in ${packagesFolderPath}; all files: ${JSON.stringify(dependencyManifestNames)}`);
144761
142745
  for (const manifestPath2 of dependencyManifestNames) {
144762
142746
  const normalizedFileName = normalizePath(manifestPath2);
144763
- const result2 = readConfigFile(normalizedFileName, (path8) => host.readFile(path8));
142747
+ const result2 = readConfigFile2(normalizedFileName, (path8) => host.readFile(path8));
144764
142748
  const manifest2 = result2.config;
144765
142749
  if (!manifest2.name) {
144766
142750
  continue;
@@ -148138,9 +146122,9 @@ ${lanes.join(`
148138
146122
  }
148139
146123
  });
148140
146124
  });
148141
- } catch (err2) {
146125
+ } catch (err) {
148142
146126
  cache2.clear();
148143
- throw err2;
146127
+ throw err;
148144
146128
  }
148145
146129
  (_e = host.log) == null || _e.call(host, `getExportInfoMap: done in ${timestamp() - start} ms`);
148146
146130
  return cache2;
@@ -160418,7 +158402,7 @@ ${newComment.split(`
160418
158402
  return [createCodeFixAction(fixId10, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId10, Diagnostics.Convert_all_constructor_functions_to_classes)];
160419
158403
  },
160420
158404
  fixIds: [fixId10],
160421
- getAllCodeActions: (context) => codeFixAll(context, errorCodes11, (changes, err2) => doChange9(changes, err2.file, err2.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions()))
158405
+ getAllCodeActions: (context) => codeFixAll(context, errorCodes11, (changes, err) => doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions()))
160422
158406
  });
160423
158407
  function doChange9(changes, sourceFile, position, checker, preferences, compilerOptions) {
160424
158408
  const ctorSymbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, position));
@@ -160627,7 +158611,7 @@ ${newComment.split(`
160627
158611
  return codeActionSucceeded ? [createCodeFixAction(fixId11, changes, Diagnostics.Convert_to_async_function, fixId11, Diagnostics.Convert_all_to_async_functions)] : [];
160628
158612
  },
160629
158613
  fixIds: [fixId11],
160630
- getAllCodeActions: (context) => codeFixAll(context, errorCodes12, (changes, err2) => convertToAsyncFunction(changes, err2.file, err2.start, context.program.getTypeChecker()))
158614
+ getAllCodeActions: (context) => codeFixAll(context, errorCodes12, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker()))
160631
158615
  });
160632
158616
  function convertToAsyncFunction(changes, sourceFile, position, checker) {
160633
158617
  const tokenAtPosition = getTokenAtPosition(sourceFile, position);
@@ -165527,8 +163511,8 @@ ${newComment.split(`
165527
163511
  getAllCodeActions(context) {
165528
163512
  const { fixId: fixId56, program, sourceFile } = context;
165529
163513
  const checker = program.getTypeChecker();
165530
- return codeFixAll(context, errorCodes46, (changes, err2) => {
165531
- const info2 = getInfo15(err2.file, err2.start, checker);
163514
+ return codeFixAll(context, errorCodes46, (changes, err) => {
163515
+ const info2 = getInfo15(err.file, err.start, checker);
165532
163516
  if (!info2)
165533
163517
  return;
165534
163518
  const { typeNode, type } = info2;
@@ -166463,8 +164447,8 @@ ${newComment.split(`
166463
164447
  getAllCodeActions(context) {
166464
164448
  const { sourceFile, program, cancellationToken, host, preferences } = context;
166465
164449
  const markSeen = nodeSeenTracker();
166466
- return codeFixAll(context, errorCodes51, (changes, err2) => {
166467
- doChange33(changes, sourceFile, getTokenAtPosition(err2.file, err2.start), err2.code, program, cancellationToken, markSeen, host, preferences);
164450
+ return codeFixAll(context, errorCodes51, (changes, err) => {
164451
+ doChange33(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences);
166468
164452
  });
166469
164453
  }
166470
164454
  });
@@ -167694,7 +165678,7 @@ ${newComment.split(`
167694
165678
  }
167695
165679
  const typeArguments = fullTypeArguments.slice(0, cutoff);
167696
165680
  const filledIn = checker.fillMissingTypeArguments(typeArguments, target.typeParameters, cutoff, false);
167697
- if (filledIn.every((fill2, i) => fill2 === fullTypeArguments[i])) {
165681
+ if (filledIn.every((fill, i) => fill === fullTypeArguments[i])) {
167698
165682
  return cutoff;
167699
165683
  }
167700
165684
  }
@@ -185203,7 +183187,7 @@ ${options.prefix}` : `
185203
183187
  rangeStartIsOnSameLineAsRangeEnd: () => rangeStartIsOnSameLineAsRangeEnd,
185204
183188
  rangeStartPositionsAreOnSameLine: () => rangeStartPositionsAreOnSameLine,
185205
183189
  readBuilderProgram: () => readBuilderProgram,
185206
- readConfigFile: () => readConfigFile,
183190
+ readConfigFile: () => readConfigFile2,
185207
183191
  readJson: () => readJson,
185208
183192
  readJsonConfigFile: () => readJsonConfigFile,
185209
183193
  readJsonOrUndefined: () => readJsonOrUndefined,
@@ -187082,8 +185066,8 @@ ${options.prefix}` : `
187082
185066
  resolvedModule = result.module;
187083
185067
  break;
187084
185068
  }
187085
- const err2 = result.error.stack || result.error.message || JSON.stringify(result.error);
187086
- (errorLogs ?? (errorLogs = [])).push(`Failed to load module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err2}`);
185069
+ const err = result.error.stack || result.error.message || JSON.stringify(result.error);
185070
+ (errorLogs ?? (errorLogs = [])).push(`Failed to load module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`);
187087
185071
  }
187088
185072
  return { pluginConfigEntry, resolvedModule, errorLogs };
187089
185073
  }
@@ -187104,8 +185088,8 @@ ${options.prefix}` : `
187104
185088
  resolvedModule = result.module;
187105
185089
  break;
187106
185090
  }
187107
- const err2 = result.error.stack || result.error.message || JSON.stringify(result.error);
187108
- (errorLogs ?? (errorLogs = [])).push(`Failed to dynamically import module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err2}`);
185091
+ const err = result.error.stack || result.error.message || JSON.stringify(result.error);
185092
+ (errorLogs ?? (errorLogs = [])).push(`Failed to dynamically import module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`);
187109
185093
  }
187110
185094
  return { pluginConfigEntry, resolvedModule, errorLogs };
187111
185095
  }
@@ -192948,7 +190932,7 @@ ${json}${newLine}`;
192948
190932
  getCurrentRequestId: () => this.currentRequestId,
192949
190933
  getPerformanceData: () => this.performanceData,
192950
190934
  getServerHost: () => this.host,
192951
- logError: (err2, cmd) => this.logError(err2, cmd),
190935
+ logError: (err, cmd) => this.logError(err, cmd),
192952
190936
  sendRequestCompletedEvent: (requestId2, performanceData) => this.sendRequestCompletedEvent(requestId2, performanceData),
192953
190937
  isCancellationRequested: () => this.cancellationToken.isCancellationRequested()
192954
190938
  };
@@ -193082,17 +191066,17 @@ ${json}${newLine}`;
193082
191066
  }, ProjectsUpdatedInBackgroundEvent);
193083
191067
  }
193084
191068
  }
193085
- logError(err2, cmd) {
193086
- this.logErrorWorker(err2, cmd);
191069
+ logError(err, cmd) {
191070
+ this.logErrorWorker(err, cmd);
193087
191071
  }
193088
- logErrorWorker(err2, cmd, fileRequest) {
191072
+ logErrorWorker(err, cmd, fileRequest) {
193089
191073
  let msg = "Exception on executing command " + cmd;
193090
- if (err2.message) {
191074
+ if (err.message) {
193091
191075
  msg += `:
193092
- ` + indent2(err2.message);
193093
- if (err2.stack) {
191076
+ ` + indent2(err.message);
191077
+ if (err.stack) {
193094
191078
  msg += `
193095
- ` + indent2(err2.stack);
191079
+ ` + indent2(err.stack);
193096
191080
  }
193097
191081
  }
193098
191082
  if (this.logger.hasLevel(3)) {
@@ -193109,10 +191093,10 @@ File text of ${fileRequest.file}:${indent2(text)}
193109
191093
  }
193110
191094
  } catch {}
193111
191095
  }
193112
- if (err2.ProgramFiles) {
191096
+ if (err.ProgramFiles) {
193113
191097
  msg += `
193114
191098
 
193115
- Program files: ${JSON.stringify(err2.ProgramFiles)}
191099
+ Program files: ${JSON.stringify(err.ProgramFiles)}
193116
191100
  `;
193117
191101
  msg += `
193118
191102
 
@@ -193239,8 +191223,8 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter
193239
191223
  };
193240
191224
  this.event(body, kind);
193241
191225
  this.addDiagnosticsPerformanceData(file, kind, duration);
193242
- } catch (err2) {
193243
- this.logError(err2, kind);
191226
+ } catch (err) {
191227
+ this.logError(err, kind);
193244
191228
  }
193245
191229
  }
193246
191230
  updateErrorCheck(next, checkList, ms, requireOpen = true) {
@@ -194847,17 +192831,17 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
194847
192831
  } else if (responseRequired) {
194848
192832
  this.doOutput(undefined, request.command, request.seq, false, performanceData, "No content available.");
194849
192833
  }
194850
- } catch (err2) {
192834
+ } catch (err) {
194851
192835
  (_e = tracing) == null || _e.popAll();
194852
- if (err2 instanceof OperationCanceledException) {
192836
+ if (err instanceof OperationCanceledException) {
194853
192837
  (_f = tracing) == null || _f.instant(tracing.Phase.Session, "commandCanceled", { seq: request == null ? undefined : request.seq, command: request == null ? undefined : request.command });
194854
192838
  this.doOutput({ canceled: true }, request.command, request.seq, true, this.performanceData);
194855
192839
  return;
194856
192840
  }
194857
- this.logErrorWorker(err2, this.toStringMessage(message), relevantFile);
194858
- (_g = tracing) == null || _g.instant(tracing.Phase.Session, "commandError", { seq: request == null ? undefined : request.seq, command: request == null ? undefined : request.command, message: err2.message });
194859
- this.doOutput(undefined, request ? request.command : "unknown", request ? request.seq : 0, false, this.performanceData, "Error processing request. " + err2.message + `
194860
- ` + err2.stack);
192841
+ this.logErrorWorker(err, this.toStringMessage(message), relevantFile);
192842
+ (_g = tracing) == null || _g.instant(tracing.Phase.Session, "commandError", { seq: request == null ? undefined : request.seq, command: request == null ? undefined : request.command, message: err.message });
192843
+ this.doOutput(undefined, request ? request.command : "unknown", request ? request.seq : 0, false, this.performanceData, "Error processing request. " + err.message + `
192844
+ ` + err.stack);
194861
192845
  } finally {
194862
192846
  this.performanceData = currentPerformanceData;
194863
192847
  }
@@ -197489,1123 +195473,8 @@ globstar while`, file, fr, pattern, pr, swallowee);
197489
195473
  exports.minimatch.unescape = unescape_js_1.unescape;
197490
195474
  });
197491
195475
 
197492
- // node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/index.js
197493
- var require_commonjs3 = __commonJS((exports) => {
197494
- Object.defineProperty(exports, "__esModule", { value: true });
197495
- exports.LRUCache = undefined;
197496
- var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
197497
- var warned2 = new Set;
197498
- var PROCESS2 = typeof process === "object" && !!process ? process : {};
197499
- var emitWarning2 = (msg, type, code, fn) => {
197500
- typeof PROCESS2.emitWarning === "function" ? PROCESS2.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
197501
- };
197502
- var AC2 = globalThis.AbortController;
197503
- var AS2 = globalThis.AbortSignal;
197504
- if (typeof AC2 === "undefined") {
197505
- AS2 = class AbortSignal {
197506
- onabort;
197507
- _onabort = [];
197508
- reason;
197509
- aborted = false;
197510
- addEventListener(_, fn) {
197511
- this._onabort.push(fn);
197512
- }
197513
- };
197514
- AC2 = class AbortController2 {
197515
- constructor() {
197516
- warnACPolyfill();
197517
- }
197518
- signal = new AS2;
197519
- abort(reason) {
197520
- if (this.signal.aborted)
197521
- return;
197522
- this.signal.reason = reason;
197523
- this.signal.aborted = true;
197524
- for (const fn of this.signal._onabort) {
197525
- fn(reason);
197526
- }
197527
- this.signal.onabort?.(reason);
197528
- }
197529
- };
197530
- let printACPolyfillWarning = PROCESS2.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
197531
- const warnACPolyfill = () => {
197532
- if (!printACPolyfillWarning)
197533
- return;
197534
- printACPolyfillWarning = false;
197535
- emitWarning2("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);
197536
- };
197537
- }
197538
- var shouldWarn2 = (code) => !warned2.has(code);
197539
- var TYPE2 = Symbol("type");
197540
- var isPosInt2 = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
197541
- var getUintArray2 = (max) => !isPosInt2(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 ? ZeroArray2 : null;
197542
-
197543
- class ZeroArray2 extends Array {
197544
- constructor(size) {
197545
- super(size);
197546
- this.fill(0);
197547
- }
197548
- }
197549
-
197550
- class Stack2 {
197551
- heap;
197552
- length;
197553
- static #constructing = false;
197554
- static create(max) {
197555
- const HeapCls = getUintArray2(max);
197556
- if (!HeapCls)
197557
- return [];
197558
- Stack2.#constructing = true;
197559
- const s = new Stack2(max, HeapCls);
197560
- Stack2.#constructing = false;
197561
- return s;
197562
- }
197563
- constructor(max, HeapCls) {
197564
- if (!Stack2.#constructing) {
197565
- throw new TypeError("instantiate Stack using Stack.create(n)");
197566
- }
197567
- this.heap = new HeapCls(max);
197568
- this.length = 0;
197569
- }
197570
- push(n) {
197571
- this.heap[this.length++] = n;
197572
- }
197573
- pop() {
197574
- return this.heap[--this.length];
197575
- }
197576
- }
197577
-
197578
- class LRUCache2 {
197579
- #max;
197580
- #maxSize;
197581
- #dispose;
197582
- #disposeAfter;
197583
- #fetchMethod;
197584
- #memoMethod;
197585
- ttl;
197586
- ttlResolution;
197587
- ttlAutopurge;
197588
- updateAgeOnGet;
197589
- updateAgeOnHas;
197590
- allowStale;
197591
- noDisposeOnSet;
197592
- noUpdateTTL;
197593
- maxEntrySize;
197594
- sizeCalculation;
197595
- noDeleteOnFetchRejection;
197596
- noDeleteOnStaleGet;
197597
- allowStaleOnFetchAbort;
197598
- allowStaleOnFetchRejection;
197599
- ignoreFetchAbort;
197600
- #size;
197601
- #calculatedSize;
197602
- #keyMap;
197603
- #keyList;
197604
- #valList;
197605
- #next;
197606
- #prev;
197607
- #head;
197608
- #tail;
197609
- #free;
197610
- #disposed;
197611
- #sizes;
197612
- #starts;
197613
- #ttls;
197614
- #hasDispose;
197615
- #hasFetchMethod;
197616
- #hasDisposeAfter;
197617
- static unsafeExposeInternals(c) {
197618
- return {
197619
- starts: c.#starts,
197620
- ttls: c.#ttls,
197621
- sizes: c.#sizes,
197622
- keyMap: c.#keyMap,
197623
- keyList: c.#keyList,
197624
- valList: c.#valList,
197625
- next: c.#next,
197626
- prev: c.#prev,
197627
- get head() {
197628
- return c.#head;
197629
- },
197630
- get tail() {
197631
- return c.#tail;
197632
- },
197633
- free: c.#free,
197634
- isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
197635
- backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
197636
- moveToTail: (index) => c.#moveToTail(index),
197637
- indexes: (options) => c.#indexes(options),
197638
- rindexes: (options) => c.#rindexes(options),
197639
- isStale: (index) => c.#isStale(index)
197640
- };
197641
- }
197642
- get max() {
197643
- return this.#max;
197644
- }
197645
- get maxSize() {
197646
- return this.#maxSize;
197647
- }
197648
- get calculatedSize() {
197649
- return this.#calculatedSize;
197650
- }
197651
- get size() {
197652
- return this.#size;
197653
- }
197654
- get fetchMethod() {
197655
- return this.#fetchMethod;
197656
- }
197657
- get memoMethod() {
197658
- return this.#memoMethod;
197659
- }
197660
- get dispose() {
197661
- return this.#dispose;
197662
- }
197663
- get disposeAfter() {
197664
- return this.#disposeAfter;
197665
- }
197666
- constructor(options) {
197667
- const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options;
197668
- if (max !== 0 && !isPosInt2(max)) {
197669
- throw new TypeError("max option must be a nonnegative integer");
197670
- }
197671
- const UintArray = max ? getUintArray2(max) : Array;
197672
- if (!UintArray) {
197673
- throw new Error("invalid max value: " + max);
197674
- }
197675
- this.#max = max;
197676
- this.#maxSize = maxSize;
197677
- this.maxEntrySize = maxEntrySize || this.#maxSize;
197678
- this.sizeCalculation = sizeCalculation;
197679
- if (this.sizeCalculation) {
197680
- if (!this.#maxSize && !this.maxEntrySize) {
197681
- throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
197682
- }
197683
- if (typeof this.sizeCalculation !== "function") {
197684
- throw new TypeError("sizeCalculation set to non-function");
197685
- }
197686
- }
197687
- if (memoMethod !== undefined && typeof memoMethod !== "function") {
197688
- throw new TypeError("memoMethod must be a function if defined");
197689
- }
197690
- this.#memoMethod = memoMethod;
197691
- if (fetchMethod !== undefined && typeof fetchMethod !== "function") {
197692
- throw new TypeError("fetchMethod must be a function if specified");
197693
- }
197694
- this.#fetchMethod = fetchMethod;
197695
- this.#hasFetchMethod = !!fetchMethod;
197696
- this.#keyMap = new Map;
197697
- this.#keyList = new Array(max).fill(undefined);
197698
- this.#valList = new Array(max).fill(undefined);
197699
- this.#next = new UintArray(max);
197700
- this.#prev = new UintArray(max);
197701
- this.#head = 0;
197702
- this.#tail = 0;
197703
- this.#free = Stack2.create(max);
197704
- this.#size = 0;
197705
- this.#calculatedSize = 0;
197706
- if (typeof dispose === "function") {
197707
- this.#dispose = dispose;
197708
- }
197709
- if (typeof disposeAfter === "function") {
197710
- this.#disposeAfter = disposeAfter;
197711
- this.#disposed = [];
197712
- } else {
197713
- this.#disposeAfter = undefined;
197714
- this.#disposed = undefined;
197715
- }
197716
- this.#hasDispose = !!this.#dispose;
197717
- this.#hasDisposeAfter = !!this.#disposeAfter;
197718
- this.noDisposeOnSet = !!noDisposeOnSet;
197719
- this.noUpdateTTL = !!noUpdateTTL;
197720
- this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
197721
- this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
197722
- this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
197723
- this.ignoreFetchAbort = !!ignoreFetchAbort;
197724
- if (this.maxEntrySize !== 0) {
197725
- if (this.#maxSize !== 0) {
197726
- if (!isPosInt2(this.#maxSize)) {
197727
- throw new TypeError("maxSize must be a positive integer if specified");
197728
- }
197729
- }
197730
- if (!isPosInt2(this.maxEntrySize)) {
197731
- throw new TypeError("maxEntrySize must be a positive integer if specified");
197732
- }
197733
- this.#initializeSizeTracking();
197734
- }
197735
- this.allowStale = !!allowStale;
197736
- this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
197737
- this.updateAgeOnGet = !!updateAgeOnGet;
197738
- this.updateAgeOnHas = !!updateAgeOnHas;
197739
- this.ttlResolution = isPosInt2(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
197740
- this.ttlAutopurge = !!ttlAutopurge;
197741
- this.ttl = ttl || 0;
197742
- if (this.ttl) {
197743
- if (!isPosInt2(this.ttl)) {
197744
- throw new TypeError("ttl must be a positive integer if specified");
197745
- }
197746
- this.#initializeTTLTracking();
197747
- }
197748
- if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
197749
- throw new TypeError("At least one of max, maxSize, or ttl is required");
197750
- }
197751
- if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
197752
- const code = "LRU_CACHE_UNBOUNDED";
197753
- if (shouldWarn2(code)) {
197754
- warned2.add(code);
197755
- const msg = "TTL caching without ttlAutopurge, max, or maxSize can " + "result in unbounded memory consumption.";
197756
- emitWarning2(msg, "UnboundedCacheWarning", code, LRUCache2);
197757
- }
197758
- }
197759
- }
197760
- getRemainingTTL(key) {
197761
- return this.#keyMap.has(key) ? Infinity : 0;
197762
- }
197763
- #initializeTTLTracking() {
197764
- const ttls = new ZeroArray2(this.#max);
197765
- const starts = new ZeroArray2(this.#max);
197766
- this.#ttls = ttls;
197767
- this.#starts = starts;
197768
- this.#setItemTTL = (index, ttl, start = perf.now()) => {
197769
- starts[index] = ttl !== 0 ? start : 0;
197770
- ttls[index] = ttl;
197771
- if (ttl !== 0 && this.ttlAutopurge) {
197772
- const t = setTimeout(() => {
197773
- if (this.#isStale(index)) {
197774
- this.#delete(this.#keyList[index], "expire");
197775
- }
197776
- }, ttl + 1);
197777
- if (t.unref) {
197778
- t.unref();
197779
- }
197780
- }
197781
- };
197782
- this.#updateItemAge = (index) => {
197783
- starts[index] = ttls[index] !== 0 ? perf.now() : 0;
197784
- };
197785
- this.#statusTTL = (status, index) => {
197786
- if (ttls[index]) {
197787
- const ttl = ttls[index];
197788
- const start = starts[index];
197789
- if (!ttl || !start)
197790
- return;
197791
- status.ttl = ttl;
197792
- status.start = start;
197793
- status.now = cachedNow || getNow();
197794
- const age = status.now - start;
197795
- status.remainingTTL = ttl - age;
197796
- }
197797
- };
197798
- let cachedNow = 0;
197799
- const getNow = () => {
197800
- const n = perf.now();
197801
- if (this.ttlResolution > 0) {
197802
- cachedNow = n;
197803
- const t = setTimeout(() => cachedNow = 0, this.ttlResolution);
197804
- if (t.unref) {
197805
- t.unref();
197806
- }
197807
- }
197808
- return n;
197809
- };
197810
- this.getRemainingTTL = (key) => {
197811
- const index = this.#keyMap.get(key);
197812
- if (index === undefined) {
197813
- return 0;
197814
- }
197815
- const ttl = ttls[index];
197816
- const start = starts[index];
197817
- if (!ttl || !start) {
197818
- return Infinity;
197819
- }
197820
- const age = (cachedNow || getNow()) - start;
197821
- return ttl - age;
197822
- };
197823
- this.#isStale = (index) => {
197824
- const s = starts[index];
197825
- const t = ttls[index];
197826
- return !!t && !!s && (cachedNow || getNow()) - s > t;
197827
- };
197828
- }
197829
- #updateItemAge = () => {};
197830
- #statusTTL = () => {};
197831
- #setItemTTL = () => {};
197832
- #isStale = () => false;
197833
- #initializeSizeTracking() {
197834
- const sizes = new ZeroArray2(this.#max);
197835
- this.#calculatedSize = 0;
197836
- this.#sizes = sizes;
197837
- this.#removeItemSize = (index) => {
197838
- this.#calculatedSize -= sizes[index];
197839
- sizes[index] = 0;
197840
- };
197841
- this.#requireSize = (k, v, size, sizeCalculation) => {
197842
- if (this.#isBackgroundFetch(v)) {
197843
- return 0;
197844
- }
197845
- if (!isPosInt2(size)) {
197846
- if (sizeCalculation) {
197847
- if (typeof sizeCalculation !== "function") {
197848
- throw new TypeError("sizeCalculation must be a function");
197849
- }
197850
- size = sizeCalculation(v, k);
197851
- if (!isPosInt2(size)) {
197852
- throw new TypeError("sizeCalculation return invalid (expect positive integer)");
197853
- }
197854
- } else {
197855
- throw new TypeError("invalid size value (must be positive integer). " + "When maxSize or maxEntrySize is used, sizeCalculation " + "or size must be set.");
197856
- }
197857
- }
197858
- return size;
197859
- };
197860
- this.#addItemSize = (index, size, status) => {
197861
- sizes[index] = size;
197862
- if (this.#maxSize) {
197863
- const maxSize = this.#maxSize - sizes[index];
197864
- while (this.#calculatedSize > maxSize) {
197865
- this.#evict(true);
197866
- }
197867
- }
197868
- this.#calculatedSize += sizes[index];
197869
- if (status) {
197870
- status.entrySize = size;
197871
- status.totalCalculatedSize = this.#calculatedSize;
197872
- }
197873
- };
197874
- }
197875
- #removeItemSize = (_i) => {};
197876
- #addItemSize = (_i, _s, _st) => {};
197877
- #requireSize = (_k, _v, size, sizeCalculation) => {
197878
- if (size || sizeCalculation) {
197879
- throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
197880
- }
197881
- return 0;
197882
- };
197883
- *#indexes({ allowStale = this.allowStale } = {}) {
197884
- if (this.#size) {
197885
- for (let i = this.#tail;; ) {
197886
- if (!this.#isValidIndex(i)) {
197887
- break;
197888
- }
197889
- if (allowStale || !this.#isStale(i)) {
197890
- yield i;
197891
- }
197892
- if (i === this.#head) {
197893
- break;
197894
- } else {
197895
- i = this.#prev[i];
197896
- }
197897
- }
197898
- }
197899
- }
197900
- *#rindexes({ allowStale = this.allowStale } = {}) {
197901
- if (this.#size) {
197902
- for (let i = this.#head;; ) {
197903
- if (!this.#isValidIndex(i)) {
197904
- break;
197905
- }
197906
- if (allowStale || !this.#isStale(i)) {
197907
- yield i;
197908
- }
197909
- if (i === this.#tail) {
197910
- break;
197911
- } else {
197912
- i = this.#next[i];
197913
- }
197914
- }
197915
- }
197916
- }
197917
- #isValidIndex(index) {
197918
- return index !== undefined && this.#keyMap.get(this.#keyList[index]) === index;
197919
- }
197920
- *entries() {
197921
- for (const i of this.#indexes()) {
197922
- if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
197923
- yield [this.#keyList[i], this.#valList[i]];
197924
- }
197925
- }
197926
- }
197927
- *rentries() {
197928
- for (const i of this.#rindexes()) {
197929
- if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
197930
- yield [this.#keyList[i], this.#valList[i]];
197931
- }
197932
- }
197933
- }
197934
- *keys() {
197935
- for (const i of this.#indexes()) {
197936
- const k = this.#keyList[i];
197937
- if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
197938
- yield k;
197939
- }
197940
- }
197941
- }
197942
- *rkeys() {
197943
- for (const i of this.#rindexes()) {
197944
- const k = this.#keyList[i];
197945
- if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
197946
- yield k;
197947
- }
197948
- }
197949
- }
197950
- *values() {
197951
- for (const i of this.#indexes()) {
197952
- const v = this.#valList[i];
197953
- if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
197954
- yield this.#valList[i];
197955
- }
197956
- }
197957
- }
197958
- *rvalues() {
197959
- for (const i of this.#rindexes()) {
197960
- const v = this.#valList[i];
197961
- if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
197962
- yield this.#valList[i];
197963
- }
197964
- }
197965
- }
197966
- [Symbol.iterator]() {
197967
- return this.entries();
197968
- }
197969
- [Symbol.toStringTag] = "LRUCache";
197970
- find(fn, getOptions = {}) {
197971
- for (const i of this.#indexes()) {
197972
- const v = this.#valList[i];
197973
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
197974
- if (value === undefined)
197975
- continue;
197976
- if (fn(value, this.#keyList[i], this)) {
197977
- return this.get(this.#keyList[i], getOptions);
197978
- }
197979
- }
197980
- }
197981
- forEach(fn, thisp = this) {
197982
- for (const i of this.#indexes()) {
197983
- const v = this.#valList[i];
197984
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
197985
- if (value === undefined)
197986
- continue;
197987
- fn.call(thisp, value, this.#keyList[i], this);
197988
- }
197989
- }
197990
- rforEach(fn, thisp = this) {
197991
- for (const i of this.#rindexes()) {
197992
- const v = this.#valList[i];
197993
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
197994
- if (value === undefined)
197995
- continue;
197996
- fn.call(thisp, value, this.#keyList[i], this);
197997
- }
197998
- }
197999
- purgeStale() {
198000
- let deleted = false;
198001
- for (const i of this.#rindexes({ allowStale: true })) {
198002
- if (this.#isStale(i)) {
198003
- this.#delete(this.#keyList[i], "expire");
198004
- deleted = true;
198005
- }
198006
- }
198007
- return deleted;
198008
- }
198009
- info(key) {
198010
- const i = this.#keyMap.get(key);
198011
- if (i === undefined)
198012
- return;
198013
- const v = this.#valList[i];
198014
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
198015
- if (value === undefined)
198016
- return;
198017
- const entry = { value };
198018
- if (this.#ttls && this.#starts) {
198019
- const ttl = this.#ttls[i];
198020
- const start = this.#starts[i];
198021
- if (ttl && start) {
198022
- const remain = ttl - (perf.now() - start);
198023
- entry.ttl = remain;
198024
- entry.start = Date.now();
198025
- }
198026
- }
198027
- if (this.#sizes) {
198028
- entry.size = this.#sizes[i];
198029
- }
198030
- return entry;
198031
- }
198032
- dump() {
198033
- const arr = [];
198034
- for (const i of this.#indexes({ allowStale: true })) {
198035
- const key = this.#keyList[i];
198036
- const v = this.#valList[i];
198037
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
198038
- if (value === undefined || key === undefined)
198039
- continue;
198040
- const entry = { value };
198041
- if (this.#ttls && this.#starts) {
198042
- entry.ttl = this.#ttls[i];
198043
- const age = perf.now() - this.#starts[i];
198044
- entry.start = Math.floor(Date.now() - age);
198045
- }
198046
- if (this.#sizes) {
198047
- entry.size = this.#sizes[i];
198048
- }
198049
- arr.unshift([key, entry]);
198050
- }
198051
- return arr;
198052
- }
198053
- load(arr) {
198054
- this.clear();
198055
- for (const [key, entry] of arr) {
198056
- if (entry.start) {
198057
- const age = Date.now() - entry.start;
198058
- entry.start = perf.now() - age;
198059
- }
198060
- this.set(key, entry.value, entry);
198061
- }
198062
- }
198063
- set(k, v, setOptions = {}) {
198064
- if (v === undefined) {
198065
- this.delete(k);
198066
- return this;
198067
- }
198068
- const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
198069
- let { noUpdateTTL = this.noUpdateTTL } = setOptions;
198070
- const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
198071
- if (this.maxEntrySize && size > this.maxEntrySize) {
198072
- if (status) {
198073
- status.set = "miss";
198074
- status.maxEntrySizeExceeded = true;
198075
- }
198076
- this.#delete(k, "set");
198077
- return this;
198078
- }
198079
- let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
198080
- if (index === undefined) {
198081
- index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
198082
- this.#keyList[index] = k;
198083
- this.#valList[index] = v;
198084
- this.#keyMap.set(k, index);
198085
- this.#next[this.#tail] = index;
198086
- this.#prev[index] = this.#tail;
198087
- this.#tail = index;
198088
- this.#size++;
198089
- this.#addItemSize(index, size, status);
198090
- if (status)
198091
- status.set = "add";
198092
- noUpdateTTL = false;
198093
- } else {
198094
- this.#moveToTail(index);
198095
- const oldVal = this.#valList[index];
198096
- if (v !== oldVal) {
198097
- if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
198098
- oldVal.__abortController.abort(new Error("replaced"));
198099
- const { __staleWhileFetching: s } = oldVal;
198100
- if (s !== undefined && !noDisposeOnSet) {
198101
- if (this.#hasDispose) {
198102
- this.#dispose?.(s, k, "set");
198103
- }
198104
- if (this.#hasDisposeAfter) {
198105
- this.#disposed?.push([s, k, "set"]);
198106
- }
198107
- }
198108
- } else if (!noDisposeOnSet) {
198109
- if (this.#hasDispose) {
198110
- this.#dispose?.(oldVal, k, "set");
198111
- }
198112
- if (this.#hasDisposeAfter) {
198113
- this.#disposed?.push([oldVal, k, "set"]);
198114
- }
198115
- }
198116
- this.#removeItemSize(index);
198117
- this.#addItemSize(index, size, status);
198118
- this.#valList[index] = v;
198119
- if (status) {
198120
- status.set = "replace";
198121
- const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
198122
- if (oldValue !== undefined)
198123
- status.oldValue = oldValue;
198124
- }
198125
- } else if (status) {
198126
- status.set = "update";
198127
- }
198128
- }
198129
- if (ttl !== 0 && !this.#ttls) {
198130
- this.#initializeTTLTracking();
198131
- }
198132
- if (this.#ttls) {
198133
- if (!noUpdateTTL) {
198134
- this.#setItemTTL(index, ttl, start);
198135
- }
198136
- if (status)
198137
- this.#statusTTL(status, index);
198138
- }
198139
- if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
198140
- const dt = this.#disposed;
198141
- let task;
198142
- while (task = dt?.shift()) {
198143
- this.#disposeAfter?.(...task);
198144
- }
198145
- }
198146
- return this;
198147
- }
198148
- pop() {
198149
- try {
198150
- while (this.#size) {
198151
- const val = this.#valList[this.#head];
198152
- this.#evict(true);
198153
- if (this.#isBackgroundFetch(val)) {
198154
- if (val.__staleWhileFetching) {
198155
- return val.__staleWhileFetching;
198156
- }
198157
- } else if (val !== undefined) {
198158
- return val;
198159
- }
198160
- }
198161
- } finally {
198162
- if (this.#hasDisposeAfter && this.#disposed) {
198163
- const dt = this.#disposed;
198164
- let task;
198165
- while (task = dt?.shift()) {
198166
- this.#disposeAfter?.(...task);
198167
- }
198168
- }
198169
- }
198170
- }
198171
- #evict(free) {
198172
- const head = this.#head;
198173
- const k = this.#keyList[head];
198174
- const v = this.#valList[head];
198175
- if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
198176
- v.__abortController.abort(new Error("evicted"));
198177
- } else if (this.#hasDispose || this.#hasDisposeAfter) {
198178
- if (this.#hasDispose) {
198179
- this.#dispose?.(v, k, "evict");
198180
- }
198181
- if (this.#hasDisposeAfter) {
198182
- this.#disposed?.push([v, k, "evict"]);
198183
- }
198184
- }
198185
- this.#removeItemSize(head);
198186
- if (free) {
198187
- this.#keyList[head] = undefined;
198188
- this.#valList[head] = undefined;
198189
- this.#free.push(head);
198190
- }
198191
- if (this.#size === 1) {
198192
- this.#head = this.#tail = 0;
198193
- this.#free.length = 0;
198194
- } else {
198195
- this.#head = this.#next[head];
198196
- }
198197
- this.#keyMap.delete(k);
198198
- this.#size--;
198199
- return head;
198200
- }
198201
- has(k, hasOptions = {}) {
198202
- const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
198203
- const index = this.#keyMap.get(k);
198204
- if (index !== undefined) {
198205
- const v = this.#valList[index];
198206
- if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === undefined) {
198207
- return false;
198208
- }
198209
- if (!this.#isStale(index)) {
198210
- if (updateAgeOnHas) {
198211
- this.#updateItemAge(index);
198212
- }
198213
- if (status) {
198214
- status.has = "hit";
198215
- this.#statusTTL(status, index);
198216
- }
198217
- return true;
198218
- } else if (status) {
198219
- status.has = "stale";
198220
- this.#statusTTL(status, index);
198221
- }
198222
- } else if (status) {
198223
- status.has = "miss";
198224
- }
198225
- return false;
198226
- }
198227
- peek(k, peekOptions = {}) {
198228
- const { allowStale = this.allowStale } = peekOptions;
198229
- const index = this.#keyMap.get(k);
198230
- if (index === undefined || !allowStale && this.#isStale(index)) {
198231
- return;
198232
- }
198233
- const v = this.#valList[index];
198234
- return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
198235
- }
198236
- #backgroundFetch(k, index, options, context) {
198237
- const v = index === undefined ? undefined : this.#valList[index];
198238
- if (this.#isBackgroundFetch(v)) {
198239
- return v;
198240
- }
198241
- const ac = new AC2;
198242
- const { signal } = options;
198243
- signal?.addEventListener("abort", () => ac.abort(signal.reason), {
198244
- signal: ac.signal
198245
- });
198246
- const fetchOpts = {
198247
- signal: ac.signal,
198248
- options,
198249
- context
198250
- };
198251
- const cb = (v2, updateCache = false) => {
198252
- const { aborted } = ac.signal;
198253
- const ignoreAbort = options.ignoreFetchAbort && v2 !== undefined;
198254
- if (options.status) {
198255
- if (aborted && !updateCache) {
198256
- options.status.fetchAborted = true;
198257
- options.status.fetchError = ac.signal.reason;
198258
- if (ignoreAbort)
198259
- options.status.fetchAbortIgnored = true;
198260
- } else {
198261
- options.status.fetchResolved = true;
198262
- }
198263
- }
198264
- if (aborted && !ignoreAbort && !updateCache) {
198265
- return fetchFail(ac.signal.reason);
198266
- }
198267
- const bf2 = p;
198268
- if (this.#valList[index] === p) {
198269
- if (v2 === undefined) {
198270
- if (bf2.__staleWhileFetching) {
198271
- this.#valList[index] = bf2.__staleWhileFetching;
198272
- } else {
198273
- this.#delete(k, "fetch");
198274
- }
198275
- } else {
198276
- if (options.status)
198277
- options.status.fetchUpdated = true;
198278
- this.set(k, v2, fetchOpts.options);
198279
- }
198280
- }
198281
- return v2;
198282
- };
198283
- const eb = (er) => {
198284
- if (options.status) {
198285
- options.status.fetchRejected = true;
198286
- options.status.fetchError = er;
198287
- }
198288
- return fetchFail(er);
198289
- };
198290
- const fetchFail = (er) => {
198291
- const { aborted } = ac.signal;
198292
- const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
198293
- const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
198294
- const noDelete = allowStale || options.noDeleteOnFetchRejection;
198295
- const bf2 = p;
198296
- if (this.#valList[index] === p) {
198297
- const del = !noDelete || bf2.__staleWhileFetching === undefined;
198298
- if (del) {
198299
- this.#delete(k, "fetch");
198300
- } else if (!allowStaleAborted) {
198301
- this.#valList[index] = bf2.__staleWhileFetching;
198302
- }
198303
- }
198304
- if (allowStale) {
198305
- if (options.status && bf2.__staleWhileFetching !== undefined) {
198306
- options.status.returnedStale = true;
198307
- }
198308
- return bf2.__staleWhileFetching;
198309
- } else if (bf2.__returned === bf2) {
198310
- throw er;
198311
- }
198312
- };
198313
- const pcall = (res, rej) => {
198314
- const fmp = this.#fetchMethod?.(k, v, fetchOpts);
198315
- if (fmp && fmp instanceof Promise) {
198316
- fmp.then((v2) => res(v2 === undefined ? undefined : v2), rej);
198317
- }
198318
- ac.signal.addEventListener("abort", () => {
198319
- if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
198320
- res(undefined);
198321
- if (options.allowStaleOnFetchAbort) {
198322
- res = (v2) => cb(v2, true);
198323
- }
198324
- }
198325
- });
198326
- };
198327
- if (options.status)
198328
- options.status.fetchDispatched = true;
198329
- const p = new Promise(pcall).then(cb, eb);
198330
- const bf = Object.assign(p, {
198331
- __abortController: ac,
198332
- __staleWhileFetching: v,
198333
- __returned: undefined
198334
- });
198335
- if (index === undefined) {
198336
- this.set(k, bf, { ...fetchOpts.options, status: undefined });
198337
- index = this.#keyMap.get(k);
198338
- } else {
198339
- this.#valList[index] = bf;
198340
- }
198341
- return bf;
198342
- }
198343
- #isBackgroundFetch(p) {
198344
- if (!this.#hasFetchMethod)
198345
- return false;
198346
- const b = p;
198347
- return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC2;
198348
- }
198349
- async fetch(k, fetchOptions = {}) {
198350
- const {
198351
- allowStale = this.allowStale,
198352
- updateAgeOnGet = this.updateAgeOnGet,
198353
- noDeleteOnStaleGet = this.noDeleteOnStaleGet,
198354
- ttl = this.ttl,
198355
- noDisposeOnSet = this.noDisposeOnSet,
198356
- size = 0,
198357
- sizeCalculation = this.sizeCalculation,
198358
- noUpdateTTL = this.noUpdateTTL,
198359
- noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
198360
- allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
198361
- ignoreFetchAbort = this.ignoreFetchAbort,
198362
- allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
198363
- context,
198364
- forceRefresh = false,
198365
- status,
198366
- signal
198367
- } = fetchOptions;
198368
- if (!this.#hasFetchMethod) {
198369
- if (status)
198370
- status.fetch = "get";
198371
- return this.get(k, {
198372
- allowStale,
198373
- updateAgeOnGet,
198374
- noDeleteOnStaleGet,
198375
- status
198376
- });
198377
- }
198378
- const options = {
198379
- allowStale,
198380
- updateAgeOnGet,
198381
- noDeleteOnStaleGet,
198382
- ttl,
198383
- noDisposeOnSet,
198384
- size,
198385
- sizeCalculation,
198386
- noUpdateTTL,
198387
- noDeleteOnFetchRejection,
198388
- allowStaleOnFetchRejection,
198389
- allowStaleOnFetchAbort,
198390
- ignoreFetchAbort,
198391
- status,
198392
- signal
198393
- };
198394
- let index = this.#keyMap.get(k);
198395
- if (index === undefined) {
198396
- if (status)
198397
- status.fetch = "miss";
198398
- const p = this.#backgroundFetch(k, index, options, context);
198399
- return p.__returned = p;
198400
- } else {
198401
- const v = this.#valList[index];
198402
- if (this.#isBackgroundFetch(v)) {
198403
- const stale = allowStale && v.__staleWhileFetching !== undefined;
198404
- if (status) {
198405
- status.fetch = "inflight";
198406
- if (stale)
198407
- status.returnedStale = true;
198408
- }
198409
- return stale ? v.__staleWhileFetching : v.__returned = v;
198410
- }
198411
- const isStale = this.#isStale(index);
198412
- if (!forceRefresh && !isStale) {
198413
- if (status)
198414
- status.fetch = "hit";
198415
- this.#moveToTail(index);
198416
- if (updateAgeOnGet) {
198417
- this.#updateItemAge(index);
198418
- }
198419
- if (status)
198420
- this.#statusTTL(status, index);
198421
- return v;
198422
- }
198423
- const p = this.#backgroundFetch(k, index, options, context);
198424
- const hasStale = p.__staleWhileFetching !== undefined;
198425
- const staleVal = hasStale && allowStale;
198426
- if (status) {
198427
- status.fetch = isStale ? "stale" : "refresh";
198428
- if (staleVal && isStale)
198429
- status.returnedStale = true;
198430
- }
198431
- return staleVal ? p.__staleWhileFetching : p.__returned = p;
198432
- }
198433
- }
198434
- async forceFetch(k, fetchOptions = {}) {
198435
- const v = await this.fetch(k, fetchOptions);
198436
- if (v === undefined)
198437
- throw new Error("fetch() returned undefined");
198438
- return v;
198439
- }
198440
- memo(k, memoOptions = {}) {
198441
- const memoMethod = this.#memoMethod;
198442
- if (!memoMethod) {
198443
- throw new Error("no memoMethod provided to constructor");
198444
- }
198445
- const { context, forceRefresh, ...options } = memoOptions;
198446
- const v = this.get(k, options);
198447
- if (!forceRefresh && v !== undefined)
198448
- return v;
198449
- const vv = memoMethod(k, v, {
198450
- options,
198451
- context
198452
- });
198453
- this.set(k, vv, options);
198454
- return vv;
198455
- }
198456
- get(k, getOptions = {}) {
198457
- const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
198458
- const index = this.#keyMap.get(k);
198459
- if (index !== undefined) {
198460
- const value = this.#valList[index];
198461
- const fetching = this.#isBackgroundFetch(value);
198462
- if (status)
198463
- this.#statusTTL(status, index);
198464
- if (this.#isStale(index)) {
198465
- if (status)
198466
- status.get = "stale";
198467
- if (!fetching) {
198468
- if (!noDeleteOnStaleGet) {
198469
- this.#delete(k, "expire");
198470
- }
198471
- if (status && allowStale)
198472
- status.returnedStale = true;
198473
- return allowStale ? value : undefined;
198474
- } else {
198475
- if (status && allowStale && value.__staleWhileFetching !== undefined) {
198476
- status.returnedStale = true;
198477
- }
198478
- return allowStale ? value.__staleWhileFetching : undefined;
198479
- }
198480
- } else {
198481
- if (status)
198482
- status.get = "hit";
198483
- if (fetching) {
198484
- return value.__staleWhileFetching;
198485
- }
198486
- this.#moveToTail(index);
198487
- if (updateAgeOnGet) {
198488
- this.#updateItemAge(index);
198489
- }
198490
- return value;
198491
- }
198492
- } else if (status) {
198493
- status.get = "miss";
198494
- }
198495
- }
198496
- #connect(p, n) {
198497
- this.#prev[n] = p;
198498
- this.#next[p] = n;
198499
- }
198500
- #moveToTail(index) {
198501
- if (index !== this.#tail) {
198502
- if (index === this.#head) {
198503
- this.#head = this.#next[index];
198504
- } else {
198505
- this.#connect(this.#prev[index], this.#next[index]);
198506
- }
198507
- this.#connect(this.#tail, index);
198508
- this.#tail = index;
198509
- }
198510
- }
198511
- delete(k) {
198512
- return this.#delete(k, "delete");
198513
- }
198514
- #delete(k, reason) {
198515
- let deleted = false;
198516
- if (this.#size !== 0) {
198517
- const index = this.#keyMap.get(k);
198518
- if (index !== undefined) {
198519
- deleted = true;
198520
- if (this.#size === 1) {
198521
- this.#clear(reason);
198522
- } else {
198523
- this.#removeItemSize(index);
198524
- const v = this.#valList[index];
198525
- if (this.#isBackgroundFetch(v)) {
198526
- v.__abortController.abort(new Error("deleted"));
198527
- } else if (this.#hasDispose || this.#hasDisposeAfter) {
198528
- if (this.#hasDispose) {
198529
- this.#dispose?.(v, k, reason);
198530
- }
198531
- if (this.#hasDisposeAfter) {
198532
- this.#disposed?.push([v, k, reason]);
198533
- }
198534
- }
198535
- this.#keyMap.delete(k);
198536
- this.#keyList[index] = undefined;
198537
- this.#valList[index] = undefined;
198538
- if (index === this.#tail) {
198539
- this.#tail = this.#prev[index];
198540
- } else if (index === this.#head) {
198541
- this.#head = this.#next[index];
198542
- } else {
198543
- const pi = this.#prev[index];
198544
- this.#next[pi] = this.#next[index];
198545
- const ni = this.#next[index];
198546
- this.#prev[ni] = this.#prev[index];
198547
- }
198548
- this.#size--;
198549
- this.#free.push(index);
198550
- }
198551
- }
198552
- }
198553
- if (this.#hasDisposeAfter && this.#disposed?.length) {
198554
- const dt = this.#disposed;
198555
- let task;
198556
- while (task = dt?.shift()) {
198557
- this.#disposeAfter?.(...task);
198558
- }
198559
- }
198560
- return deleted;
198561
- }
198562
- clear() {
198563
- return this.#clear("delete");
198564
- }
198565
- #clear(reason) {
198566
- for (const index of this.#rindexes({ allowStale: true })) {
198567
- const v = this.#valList[index];
198568
- if (this.#isBackgroundFetch(v)) {
198569
- v.__abortController.abort(new Error("deleted"));
198570
- } else {
198571
- const k = this.#keyList[index];
198572
- if (this.#hasDispose) {
198573
- this.#dispose?.(v, k, reason);
198574
- }
198575
- if (this.#hasDisposeAfter) {
198576
- this.#disposed?.push([v, k, reason]);
198577
- }
198578
- }
198579
- }
198580
- this.#keyMap.clear();
198581
- this.#valList.fill(undefined);
198582
- this.#keyList.fill(undefined);
198583
- if (this.#ttls && this.#starts) {
198584
- this.#ttls.fill(0);
198585
- this.#starts.fill(0);
198586
- }
198587
- if (this.#sizes) {
198588
- this.#sizes.fill(0);
198589
- }
198590
- this.#head = 0;
198591
- this.#tail = 0;
198592
- this.#free.length = 0;
198593
- this.#calculatedSize = 0;
198594
- this.#size = 0;
198595
- if (this.#hasDisposeAfter && this.#disposed) {
198596
- const dt = this.#disposed;
198597
- let task;
198598
- while (task = dt?.shift()) {
198599
- this.#disposeAfter?.(...task);
198600
- }
198601
- }
198602
- }
198603
- }
198604
- exports.LRUCache = LRUCache2;
198605
- });
198606
-
198607
195476
  // node_modules/path-scurry/node_modules/minipass/dist/commonjs/index.js
198608
- var require_commonjs4 = __commonJS((exports) => {
195477
+ var require_commonjs3 = __commonJS((exports) => {
198609
195478
  var __importDefault = exports && exports.__importDefault || function(mod) {
198610
195479
  return mod && mod.__esModule ? mod : { default: mod };
198611
195480
  };
@@ -199277,7 +196146,7 @@ var require_commonjs4 = __commonJS((exports) => {
199277
196146
  });
199278
196147
 
199279
196148
  // node_modules/path-scurry/dist/commonjs/index.js
199280
- var require_commonjs5 = __commonJS((exports) => {
196149
+ var require_commonjs4 = __commonJS((exports) => {
199281
196150
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
199282
196151
  if (k2 === undefined)
199283
196152
  k2 = k;
@@ -199312,14 +196181,14 @@ var require_commonjs5 = __commonJS((exports) => {
199312
196181
  };
199313
196182
  Object.defineProperty(exports, "__esModule", { value: true });
199314
196183
  exports.PathScurry = exports.Path = exports.PathScurryDarwin = exports.PathScurryPosix = exports.PathScurryWin32 = exports.PathScurryBase = exports.PathPosix = exports.PathWin32 = exports.PathBase = exports.ChildrenCache = exports.ResolveCache = undefined;
199315
- var lru_cache_1 = require_commonjs3();
196184
+ var lru_cache_1 = __require("lru-cache");
199316
196185
  var node_path_1 = __require("node:path");
199317
196186
  var node_url_1 = __require("node:url");
199318
196187
  var fs_1 = __require("fs");
199319
196188
  var actualFS = __importStar(__require("node:fs"));
199320
196189
  var realpathSync = fs_1.realpathSync.native;
199321
196190
  var promises_1 = __require("node:fs/promises");
199322
- var minipass_1 = require_commonjs4();
196191
+ var minipass_1 = require_commonjs3();
199323
196192
  var defaultFS = {
199324
196193
  lstatSync: fs_1.lstatSync,
199325
196194
  readdir: fs_1.readdir,
@@ -200751,7 +197620,7 @@ var require_pattern = __commonJS((exports) => {
200751
197620
  });
200752
197621
 
200753
197622
  // node_modules/glob/node_modules/minipass/dist/commonjs/index.js
200754
- var require_commonjs6 = __commonJS((exports) => {
197623
+ var require_commonjs5 = __commonJS((exports) => {
200755
197624
  var __importDefault = exports && exports.__importDefault || function(mod) {
200756
197625
  return mod && mod.__esModule ? mod : { default: mod };
200757
197626
  };
@@ -201749,7 +198618,7 @@ var require_processor = __commonJS((exports) => {
201749
198618
  var require_walker = __commonJS((exports) => {
201750
198619
  Object.defineProperty(exports, "__esModule", { value: true });
201751
198620
  exports.GlobStream = exports.GlobWalker = exports.GlobUtil = undefined;
201752
- var minipass_1 = require_commonjs6();
198621
+ var minipass_1 = require_commonjs5();
201753
198622
  var ignore_js_1 = require_ignore();
201754
198623
  var processor_js_1 = require_processor();
201755
198624
  var makeIgnore = (ignore, opts) => typeof ignore === "string" ? new ignore_js_1.Ignore([ignore], opts) : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts) : ignore;
@@ -202088,7 +198957,7 @@ var require_glob = __commonJS((exports) => {
202088
198957
  exports.Glob = undefined;
202089
198958
  var minimatch_1 = require_commonjs2();
202090
198959
  var node_url_1 = __require("node:url");
202091
- var path_scurry_1 = require_commonjs5();
198960
+ var path_scurry_1 = require_commonjs4();
202092
198961
  var pattern_js_1 = require_pattern();
202093
198962
  var walker_js_1 = require_walker();
202094
198963
  var defaultPlatform = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
@@ -202285,7 +199154,7 @@ var require_has_magic = __commonJS((exports) => {
202285
199154
  });
202286
199155
 
202287
199156
  // node_modules/glob/dist/commonjs/index.js
202288
- var require_commonjs7 = __commonJS((exports) => {
199157
+ var require_commonjs6 = __commonJS((exports) => {
202289
199158
  Object.defineProperty(exports, "__esModule", { value: true });
202290
199159
  exports.glob = exports.sync = exports.iterate = exports.iterateSync = exports.stream = exports.streamSync = exports.Ignore = exports.hasMagic = exports.Glob = exports.unescape = exports.escape = undefined;
202291
199160
  exports.globStreamSync = globStreamSync;
@@ -202368,7 +199237,7 @@ var require_importClassesFromDirectories = __commonJS((exports) => {
202368
199237
  Object.defineProperty(exports, "__esModule", { value: true });
202369
199238
  exports.importClassesFromDirectories = importClassesFromDirectories;
202370
199239
  var path_1 = __require("path");
202371
- var glob_1 = require_commonjs7();
199240
+ var glob_1 = require_commonjs6();
202372
199241
  function importClassesFromDirectories(directories, formats = [".ts"]) {
202373
199242
  const allFiles = directories.reduce((allDirs, dir) => {
202374
199243
  return allDirs.concat((0, glob_1.sync)(dir));
@@ -204062,9 +200931,9 @@ var require_typeResolver = __commonJS((exports) => {
204062
200931
  const referenceType = referenceTransformer_1.ReferenceTransformer.merge(referenceTypes);
204063
200932
  this.addToLocalReferenceTypeCache(name, referenceType);
204064
200933
  return referenceType;
204065
- } catch (err2) {
200934
+ } catch (err) {
204066
200935
  console.error(`There was a problem resolving type of '${name}'.`);
204067
- throw err2;
200936
+ throw err;
204068
200937
  }
204069
200938
  };
204070
200939
  const result = calcReferenceType();
@@ -204367,9 +201236,9 @@ var require_typeResolver = __commonJS((exports) => {
204367
201236
  try {
204368
201237
  const parsed = JSON.parse(formattedStr);
204369
201238
  return parsed;
204370
- } catch (err2) {
201239
+ } catch (err) {
204371
201240
  throw new exceptions_1.GenerateMetadataError(`JSON could not parse default str: "${defaultStr}", preformatted: "${formattedStr}"
204372
- message: "${err2?.message || "-"}"`);
201241
+ message: "${err?.message || "-"}"`);
204373
201242
  }
204374
201243
  }
204375
201244
  return;
@@ -208668,7 +205537,7 @@ var require_code_gen = __commonJS((exports, module) => {
208668
205537
  SourceMap = require_source_map();
208669
205538
  SourceNode = SourceMap.SourceNode;
208670
205539
  }
208671
- } catch (err2) {}
205540
+ } catch (err) {}
208672
205541
  var SourceMap;
208673
205542
  if (!SourceNode) {
208674
205543
  SourceNode = function(line, column, srcFile, chunks) {
@@ -211555,7 +208424,7 @@ var require_routeGenerator = __commonJS((exports) => {
211555
208424
 
211556
208425
  // node_modules/@tsoa/cli/dist/routeGeneration/defaultRouteGenerator.js
211557
208426
  var require_defaultRouteGenerator = __commonJS((exports) => {
211558
- var __dirname = "/home/xxnuo/projects/MTran/MTranServer/node_modules/@tsoa/cli/dist/routeGeneration";
208427
+ var __dirname = "/Volumes/MacData/Users/xxnuo/projects/MTranServer/node_modules/@tsoa/cli/dist/routeGeneration";
211559
208428
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
211560
208429
  if (k2 === undefined)
211561
208430
  k2 = k;
@@ -211681,7 +208550,7 @@ var require_defaultRouteGenerator = __commonJS((exports) => {
211681
208550
 
211682
208551
  // node_modules/@tsoa/cli/dist/module/generate-routes.js
211683
208552
  var require_generate_routes = __commonJS((exports) => {
211684
- var __dirname = "/home/xxnuo/projects/MTran/MTranServer/node_modules/@tsoa/cli/dist/module";
208553
+ var __dirname = "/Volumes/MacData/Users/xxnuo/projects/MTranServer/node_modules/@tsoa/cli/dist/module";
211685
208554
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
211686
208555
  if (k2 === undefined)
211687
208556
  k2 = k;
@@ -211881,11 +208750,11 @@ var require_build = __commonJS((exports, module) => {
211881
208750
  const cb = work.cb;
211882
208751
  const languageFile = this._resolveLocaleFile(directory, locale);
211883
208752
  const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
211884
- shim.fs.writeFile(languageFile, serializedLocale, "utf-8", function(err2) {
208753
+ shim.fs.writeFile(languageFile, serializedLocale, "utf-8", function(err) {
211885
208754
  _this.writeQueue.shift();
211886
208755
  if (_this.writeQueue.length > 0)
211887
208756
  _this._processWriteQueue();
211888
- cb(err2);
208757
+ cb(err);
211889
208758
  });
211890
208759
  }
211891
208760
  _readLocaleFile() {
@@ -211895,14 +208764,14 @@ var require_build = __commonJS((exports, module) => {
211895
208764
  if (shim.fs.readFileSync) {
211896
208765
  localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, "utf-8"));
211897
208766
  }
211898
- } catch (err2) {
211899
- if (err2 instanceof SyntaxError) {
211900
- err2.message = "syntax error in " + languageFile;
208767
+ } catch (err) {
208768
+ if (err instanceof SyntaxError) {
208769
+ err.message = "syntax error in " + languageFile;
211901
208770
  }
211902
- if (err2.code === "ENOENT")
208771
+ if (err.code === "ENOENT")
211903
208772
  localeLookup = {};
211904
208773
  else
211905
- throw err2;
208774
+ throw err;
211906
208775
  }
211907
208776
  this.cache[this.locale] = localeLookup;
211908
208777
  }
@@ -211941,7 +208810,7 @@ var require_build = __commonJS((exports, module) => {
211941
208810
  exists: (file) => {
211942
208811
  try {
211943
208812
  return fs6.statSync(file).isFile();
211944
- } catch (err2) {
208813
+ } catch (err) {
211945
208814
  return false;
211946
208815
  }
211947
208816
  }
@@ -212604,8 +209473,8 @@ var require_build2 = __commonJS((exports, module) => {
212604
209473
  applied.add(ali);
212605
209474
  argv2[ali] = value;
212606
209475
  });
212607
- } catch (err2) {
212608
- error2 = err2;
209476
+ } catch (err) {
209477
+ error2 = err;
212609
209478
  }
212610
209479
  }
212611
209480
  }
@@ -214610,7 +211479,7 @@ var require_require_directory = __commonJS((exports, module) => {
214610
211479
 
214611
211480
  // node_modules/yargs/build/index.cjs
214612
211481
  var require_build4 = __commonJS((exports, module) => {
214613
- var __dirname = "/home/xxnuo/projects/MTran/MTranServer/node_modules/yargs/build";
211482
+ var __dirname = "/Volumes/MacData/Users/xxnuo/projects/MTranServer/node_modules/yargs/build";
214614
211483
  var t = __require("assert");
214615
211484
 
214616
211485
  class e extends Error {
@@ -216495,7 +213364,7 @@ var require_cli = __commonJS((exports) => {
216495
213364
  try {
216496
213365
  const packageJsonRaw = await (0, fs_1.fsReadFile)(`${workingDir}/package.json`);
216497
213366
  packageJson = JSON.parse(packageJsonRaw.toString("utf8"));
216498
- } catch (err2) {
213367
+ } catch (err) {
216499
213368
  return defaultValue;
216500
213369
  }
216501
213370
  }
@@ -216529,19 +213398,19 @@ var require_cli = __commonJS((exports) => {
216529
213398
  const configRaw = await (0, fs_1.fsReadFile)(configFullPath);
216530
213399
  config2 = JSON.parse(configRaw.toString("utf8"));
216531
213400
  }
216532
- } catch (err2) {
216533
- if (!(err2 instanceof Error)) {
216534
- console.error(err2);
216535
- throw Error(`Unhandled error encountered loading '${configPath}': ${String(err2)}`);
216536
- } else if ("code" in err2 && err2.code === "MODULE_NOT_FOUND") {
213401
+ } catch (err) {
213402
+ if (!(err instanceof Error)) {
213403
+ console.error(err);
213404
+ throw Error(`Unhandled error encountered loading '${configPath}': ${String(err)}`);
213405
+ } else if ("code" in err && err.code === "MODULE_NOT_FOUND") {
216537
213406
  throw Error(`No config file found at '${configPath}'`);
216538
- } else if (err2.name === "SyntaxError") {
216539
- console.error(err2);
213407
+ } else if (err.name === "SyntaxError") {
213408
+ console.error(err);
216540
213409
  const errorType = isJsExtension(ext) ? "JS" : "JSON";
216541
- throw Error(`Invalid ${errorType} syntax in config at '${configPath}': ${err2.message}`);
213410
+ throw Error(`Invalid ${errorType} syntax in config at '${configPath}': ${err.message}`);
216542
213411
  } else {
216543
- console.error(err2);
216544
- throw Error(`Unhandled error encountered loading '${configPath}': ${err2.message}`);
213412
+ console.error(err);
213413
+ throw Error(`Unhandled error encountered loading '${configPath}': ${err.message}`);
216545
213414
  }
216546
213415
  }
216547
213416
  return config2;
@@ -216708,9 +213577,9 @@ var require_cli = __commonJS((exports) => {
216708
213577
  const compilerOptions = validateCompilerOptions(config2.compilerOptions);
216709
213578
  const swaggerConfig = await (0, exports.validateSpecConfig)(config2);
216710
213579
  await (0, generate_spec_1.generateSpec)(swaggerConfig, compilerOptions, config2.ignore);
216711
- } catch (err2) {
213580
+ } catch (err) {
216712
213581
  console.error(`Generate swagger error.
216713
- `, err2);
213582
+ `, err);
216714
213583
  process.exit(1);
216715
213584
  }
216716
213585
  }
@@ -216723,9 +213592,9 @@ var require_cli = __commonJS((exports) => {
216723
213592
  const compilerOptions = validateCompilerOptions(config2.compilerOptions);
216724
213593
  const routesConfig = await validateRoutesConfig(config2);
216725
213594
  await (0, generate_routes_1.generateRoutes)(routesConfig, compilerOptions, config2.ignore);
216726
- } catch (err2) {
213595
+ } catch (err) {
216727
213596
  console.error(`Generate routes error.
216728
- `, err2);
213597
+ `, err);
216729
213598
  process.exit(1);
216730
213599
  }
216731
213600
  }
@@ -216752,11 +213621,11 @@ var require_cli = __commonJS((exports) => {
216752
213621
  }
216753
213622
  await Promise.all([(0, generate_routes_1.generateRoutes)(routesConfig, compilerOptions, config2.ignore, metadata), (0, generate_spec_1.generateSpec)(swaggerConfig, compilerOptions, config2.ignore, metadata)]);
216754
213623
  return metadata;
216755
- } catch (err2) {
213624
+ } catch (err) {
216756
213625
  console.error(`Generate routes error.
216757
- `, err2);
213626
+ `, err);
216758
213627
  process.exit(1);
216759
- throw err2;
213628
+ throw err;
216760
213629
  }
216761
213630
  }
216762
213631
  });
@@ -216945,16 +213814,16 @@ __export(exports_version, {
216945
213814
  function getVersion() {
216946
213815
  return VERSION;
216947
213816
  }
216948
- var VERSION = "4.0.22";
213817
+ var VERSION = "4.0.24";
216949
213818
 
216950
213819
  // src/server/index.ts
216951
213820
  init_config();
216952
213821
  init_logger();
216953
213822
  init_models();
216954
213823
  init_services();
216955
- var import_swagger_ui_express = __toESM(require_swagger_ui_express(), 1);
216956
213824
  import express from "express";
216957
213825
  import fs6 from "fs/promises";
213826
+ import swaggerUi from "swagger-ui-express";
216958
213827
 
216959
213828
  // src/assets/index.ts
216960
213829
  import fs5 from "fs/promises";
@@ -217030,16 +213899,16 @@ function requestId() {
217030
213899
  // src/middleware/error-handler.ts
217031
213900
  init_logger();
217032
213901
  function errorHandler() {
217033
- return (err2, req, res, next) => {
213902
+ return (err, req, res, next) => {
217034
213903
  const requestId2 = req.id || "-";
217035
- const status = err2.status || 500;
213904
+ const status = err.status || 500;
217036
213905
  if (status === 401) {
217037
213906
  warn(`[${requestId2}] Unauthorized`);
217038
213907
  } else {
217039
- error(`[${requestId2}] Unhandled Error: ${err2.message}`, err2);
213908
+ error(`[${requestId2}] Unhandled Error: ${err.message}`, err);
217040
213909
  }
217041
213910
  if (res.headersSent) {
217042
- return next(err2);
213911
+ return next(err);
217043
213912
  }
217044
213913
  if (status === 401) {
217045
213914
  res.status(401).json({ error: "Unauthorized", requestId: requestId2 });
@@ -217047,7 +213916,7 @@ function errorHandler() {
217047
213916
  }
217048
213917
  res.status(500).json({
217049
213918
  error: "Internal Server Error",
217050
- message: err2.message,
213919
+ message: err.message,
217051
213920
  requestId: requestId2
217052
213921
  });
217053
213922
  };
@@ -217278,8 +214147,8 @@ class ImmeController extends import_tsoa5.Controller {
217278
214147
  let result;
217279
214148
  try {
217280
214149
  result = await translateWithPivot2(sourceLang, targetLang, text, false);
217281
- } catch (err2) {
217282
- logger.error(`Imme translation failed at index ${i}: ${err2}`);
214150
+ } catch (err) {
214151
+ logger.error(`Imme translation failed at index ${i}: ${err}`);
217283
214152
  result = text;
217284
214153
  }
217285
214154
  translations.push({
@@ -217786,8 +214655,8 @@ function RegisterRoutes(app) {
217786
214655
  validatedArgs,
217787
214656
  successStatus: 200
217788
214657
  });
217789
- } catch (err2) {
217790
- return next(err2);
214658
+ } catch (err) {
214659
+ return next(err);
217791
214660
  }
217792
214661
  });
217793
214662
  const argsTranslateController_translateBatch = {
@@ -217806,8 +214675,8 @@ function RegisterRoutes(app) {
217806
214675
  validatedArgs,
217807
214676
  successStatus: 200
217808
214677
  });
217809
- } catch (err2) {
217810
- return next(err2);
214678
+ } catch (err) {
214679
+ return next(err);
217811
214680
  }
217812
214681
  });
217813
214682
  const argsSystemController_getVersion = {};
@@ -217824,8 +214693,8 @@ function RegisterRoutes(app) {
217824
214693
  validatedArgs,
217825
214694
  successStatus: 200
217826
214695
  });
217827
- } catch (err2) {
217828
- return next(err2);
214696
+ } catch (err) {
214697
+ return next(err);
217829
214698
  }
217830
214699
  });
217831
214700
  const argsSystemController_getHealth = {};
@@ -217842,8 +214711,8 @@ function RegisterRoutes(app) {
217842
214711
  validatedArgs,
217843
214712
  successStatus: 200
217844
214713
  });
217845
- } catch (err2) {
217846
- return next(err2);
214714
+ } catch (err) {
214715
+ return next(err);
217847
214716
  }
217848
214717
  });
217849
214718
  const argsSystemController_heartbeat = {};
@@ -217860,8 +214729,8 @@ function RegisterRoutes(app) {
217860
214729
  validatedArgs,
217861
214730
  successStatus: 200
217862
214731
  });
217863
- } catch (err2) {
217864
- return next(err2);
214732
+ } catch (err) {
214733
+ return next(err);
217865
214734
  }
217866
214735
  });
217867
214736
  const argsSystemController_lbHeartbeat = {};
@@ -217878,8 +214747,8 @@ function RegisterRoutes(app) {
217878
214747
  validatedArgs,
217879
214748
  successStatus: 200
217880
214749
  });
217881
- } catch (err2) {
217882
- return next(err2);
214750
+ } catch (err) {
214751
+ return next(err);
217883
214752
  }
217884
214753
  });
217885
214754
  const argsLanguageController_getLanguages = {};
@@ -217896,8 +214765,8 @@ function RegisterRoutes(app) {
217896
214765
  validatedArgs,
217897
214766
  successStatus: 200
217898
214767
  });
217899
- } catch (err2) {
217900
- return next(err2);
214768
+ } catch (err) {
214769
+ return next(err);
217901
214770
  }
217902
214771
  });
217903
214772
  const argsLanguageController_detectLanguage = {
@@ -217916,8 +214785,8 @@ function RegisterRoutes(app) {
217916
214785
  validatedArgs,
217917
214786
  successStatus: 200
217918
214787
  });
217919
- } catch (err2) {
217920
- return next(err2);
214788
+ } catch (err) {
214789
+ return next(err);
217921
214790
  }
217922
214791
  });
217923
214792
  const argsKissController_translate = {
@@ -217936,8 +214805,8 @@ function RegisterRoutes(app) {
217936
214805
  validatedArgs,
217937
214806
  successStatus: 200
217938
214807
  });
217939
- } catch (err2) {
217940
- return next(err2);
214808
+ } catch (err) {
214809
+ return next(err);
217941
214810
  }
217942
214811
  });
217943
214812
  const argsImmeController_translate = {
@@ -217957,8 +214826,8 @@ function RegisterRoutes(app) {
217957
214826
  validatedArgs,
217958
214827
  successStatus: 200
217959
214828
  });
217960
- } catch (err2) {
217961
- return next(err2);
214829
+ } catch (err) {
214830
+ return next(err);
217962
214831
  }
217963
214832
  });
217964
214833
  const argsHcfyController_translate = {
@@ -217977,8 +214846,8 @@ function RegisterRoutes(app) {
217977
214846
  validatedArgs,
217978
214847
  successStatus: 200
217979
214848
  });
217980
- } catch (err2) {
217981
- return next(err2);
214849
+ } catch (err) {
214850
+ return next(err);
217982
214851
  }
217983
214852
  });
217984
214853
  const argsGoogleController_translateCompat = {
@@ -217997,8 +214866,8 @@ function RegisterRoutes(app) {
217997
214866
  validatedArgs,
217998
214867
  successStatus: 200
217999
214868
  });
218000
- } catch (err2) {
218001
- return next(err2);
214869
+ } catch (err) {
214870
+ return next(err);
218002
214871
  }
218003
214872
  });
218004
214873
  const argsGoogleController_translateSingle = {
@@ -218019,8 +214888,8 @@ function RegisterRoutes(app) {
218019
214888
  validatedArgs,
218020
214889
  successStatus: 200
218021
214890
  });
218022
- } catch (err2) {
218023
- return next(err2);
214891
+ } catch (err) {
214892
+ return next(err);
218024
214893
  }
218025
214894
  });
218026
214895
  const argsDeeplController_translate = {
@@ -218040,8 +214909,8 @@ function RegisterRoutes(app) {
218040
214909
  validatedArgs,
218041
214910
  successStatus: 200
218042
214911
  });
218043
- } catch (err2) {
218044
- return next(err2);
214912
+ } catch (err) {
214913
+ return next(err);
218045
214914
  }
218046
214915
  });
218047
214916
  function authenticateMiddleware(security = []) {
@@ -218073,7 +214942,7 @@ function RegisterRoutes(app) {
218073
214942
  return;
218074
214943
  }
218075
214944
  next();
218076
- } catch (err2) {
214945
+ } catch (err) {
218077
214946
  const error2 = failedAttempts.pop();
218078
214947
  error2.status = error2.status || 401;
218079
214948
  if (response.writableEnded) {
@@ -218582,7 +215451,7 @@ var swagger_default = {
218582
215451
  },
218583
215452
  info: {
218584
215453
  title: "MTranServer API",
218585
- version: "4.0.22",
215454
+ version: "4.0.24",
218586
215455
  description: "Translation server API",
218587
215456
  license: {
218588
215457
  name: "Apache-2.0"
@@ -219059,23 +215928,27 @@ import { dirname, resolve, isAbsolute } from "path";
219059
215928
  import { fileURLToPath as fileURLToPath3 } from "url";
219060
215929
 
219061
215930
  // ui/dist/icon.png
219062
- var icon_default = "./icon-2r5te9sp.png";
215931
+ var icon_default = "./icon-encyk9bj.png";
219063
215932
 
219064
- // ui/dist/assets/index-7xVSXsEP.css
219065
- var index_7xVSXsEP_default = "./index-7xVSXsEP-sep86yrb.css";
215933
+ // ui/dist/index.html
215934
+ var dist_default = "./index-3w67mw5s.html";
219066
215935
 
219067
- // ui/dist/assets/index-ioAaO-Qu.js
219068
- var index_ioAaO_Qu_default = "./index-ioAaO-Qu-4rdp3sze.js";
215936
+ // ui/dist/.DS_Store
215937
+ var __default = "./-cc07y4t8.DS_Store";
219069
215938
 
219070
- // ui/dist/index.html
219071
- var dist_default = "./index-xyz982sd.html";
215939
+ // ui/dist/assets/index-D-fF9r3Z.css
215940
+ var index_D_fF9r3Z_default = "./index-D-fF9r3Z-r4yznc2q.css";
215941
+
215942
+ // ui/dist/assets/index-bQLHUB4Q.js
215943
+ var index_bQLHUB4Q_default = "./index-bQLHUB4Q-91y6ny8e.js";
219072
215944
 
219073
215945
  // src/assets/ui.ts
219074
215946
  var assets = {
219075
215947
  "/icon.png": icon_default,
219076
- "/assets/index-7xVSXsEP.css": index_7xVSXsEP_default,
219077
- "/assets/index-ioAaO-Qu.js": index_ioAaO_Qu_default,
219078
- "/index.html": dist_default
215948
+ "/index.html": dist_default,
215949
+ "/.DS_Store": __default,
215950
+ "/assets/index-D-fF9r3Z.css": index_D_fF9r3Z_default,
215951
+ "/assets/index-bQLHUB4Q.js": index_bQLHUB4Q_default
219079
215952
  };
219080
215953
 
219081
215954
  // src/middleware/ui.ts
@@ -219124,14 +215997,17 @@ import { readFile as readFile4 } from "fs/promises";
219124
215997
  import { dirname as dirname2, resolve as resolve2, isAbsolute as isAbsolute2 } from "path";
219125
215998
  import { fileURLToPath as fileURLToPath4 } from "url";
219126
215999
 
219127
- // node_modules/swagger-ui-dist/swagger-ui.css
219128
- var swagger_ui_default = "./swagger-ui-bfxfcsxh.css";
216000
+ // node_modules/swagger-ui-dist/favicon-16x16.png
216001
+ var favicon_16x16_default = "./favicon-16x16-xwsy16sv.png";
216002
+
216003
+ // node_modules/swagger-ui-dist/swagger-ui.js
216004
+ var swagger_ui_default = "./swagger-ui-bycaq9jd.js";
219129
216005
 
219130
216006
  // node_modules/swagger-ui-dist/oauth2-redirect.js
219131
216007
  var oauth2_redirect_default = "./oauth2-redirect-bqxabm9x.js";
219132
216008
 
219133
- // node_modules/swagger-ui-dist/swagger-initializer.js
219134
- var swagger_initializer_default = "./swagger-initializer-55m7yyx2.js";
216009
+ // node_modules/swagger-ui-dist/swagger-ui.css
216010
+ var swagger_ui_default2 = "./swagger-ui-bfxfcsxh.css";
219135
216011
 
219136
216012
  // node_modules/swagger-ui-dist/swagger-ui-bundle.js
219137
216013
  var swagger_ui_bundle_default = "./swagger-ui-bundle-a3dgbj09.js";
@@ -219139,24 +216015,21 @@ var swagger_ui_bundle_default = "./swagger-ui-bundle-a3dgbj09.js";
219139
216015
  // node_modules/swagger-ui-dist/swagger-ui-standalone-preset.js
219140
216016
  var swagger_ui_standalone_preset_default = "./swagger-ui-standalone-preset-9dtac9s6.js";
219141
216017
 
219142
- // node_modules/swagger-ui-dist/swagger-ui.js
219143
- var swagger_ui_default2 = "./swagger-ui-bycaq9jd.js";
219144
-
219145
- // node_modules/swagger-ui-dist/favicon-16x16.png
219146
- var favicon_16x16_default = "./favicon-16x16-xwsy16sv.png";
216018
+ // node_modules/swagger-ui-dist/swagger-initializer.js
216019
+ var swagger_initializer_default = "./swagger-initializer-55m7yyx2.js";
219147
216020
 
219148
216021
  // node_modules/swagger-ui-dist/favicon-32x32.png
219149
216022
  var favicon_32x32_default = "./favicon-32x32-zstv2hmc.png";
219150
216023
 
219151
216024
  // src/assets/swagger.ts
219152
216025
  var swaggerAssets = {
219153
- "/swagger-ui.css": swagger_ui_default,
216026
+ "/favicon-16x16.png": favicon_16x16_default,
216027
+ "/swagger-ui.js": swagger_ui_default,
219154
216028
  "/oauth2-redirect.js": oauth2_redirect_default,
219155
- "/swagger-initializer.js": swagger_initializer_default,
216029
+ "/swagger-ui.css": swagger_ui_default2,
219156
216030
  "/swagger-ui-bundle.js": swagger_ui_bundle_default,
219157
216031
  "/swagger-ui-standalone-preset.js": swagger_ui_standalone_preset_default,
219158
- "/swagger-ui.js": swagger_ui_default2,
219159
- "/favicon-16x16.png": favicon_16x16_default,
216032
+ "/swagger-initializer.js": swagger_initializer_default,
219160
216033
  "/favicon-32x32.png": favicon_32x32_default
219161
216034
  };
219162
216035
 
@@ -219225,7 +216098,7 @@ async function checkForUpdate() {
219225
216098
  }
219226
216099
 
219227
216100
  // src/server/index.ts
219228
- async function run() {
216101
+ async function startServer({ handleSignals = true } = {}) {
219229
216102
  const config2 = getConfig();
219230
216103
  info("Initializing MTranServer...");
219231
216104
  await fs6.mkdir(config2.modelDir, { recursive: true });
@@ -219240,6 +216113,117 @@ async function run() {
219240
216113
  if (config2.logRequests) {
219241
216114
  app.use(requestLogger());
219242
216115
  }
216116
+ const getDesktopControl = () => globalThis.mtranDesktopControl;
216117
+ const getSettingsPayload = () => {
216118
+ const current = getConfig();
216119
+ return {
216120
+ config: {
216121
+ locale: "system",
216122
+ server: {
216123
+ host: current.host,
216124
+ port: Number(current.port),
216125
+ logLevel: current.logLevel,
216126
+ enableWebUI: current.enableWebUI,
216127
+ enableOfflineMode: current.enableOfflineMode,
216128
+ workerIdleTimeout: current.workerIdleTimeout,
216129
+ workersPerLanguage: current.workersPerLanguage,
216130
+ apiToken: current.apiToken,
216131
+ logDir: current.logDir,
216132
+ logToFile: current.logToFile,
216133
+ logConsole: current.logConsole,
216134
+ logRequests: current.logRequests,
216135
+ maxLengthBreak: current.maxLengthBreak,
216136
+ checkUpdate: current.checkUpdate,
216137
+ cacheSize: current.cacheSize,
216138
+ modelDir: current.modelDir,
216139
+ configDir: current.configDir
216140
+ }
216141
+ },
216142
+ status: "running",
216143
+ version: VERSION
216144
+ };
216145
+ };
216146
+ const toNumber = (value, fallback) => {
216147
+ if (typeof value === "number" && Number.isFinite(value))
216148
+ return value;
216149
+ const parsed = Number(value);
216150
+ return Number.isFinite(parsed) ? parsed : fallback;
216151
+ };
216152
+ const toBool = (value, fallback) => {
216153
+ if (typeof value === "boolean")
216154
+ return value;
216155
+ return fallback;
216156
+ };
216157
+ const toString2 = (value, fallback) => {
216158
+ if (typeof value === "string")
216159
+ return value;
216160
+ return fallback;
216161
+ };
216162
+ const applyServerConfig = (input) => {
216163
+ const current = getConfig();
216164
+ const next = {
216165
+ host: toString2(input.host, current.host),
216166
+ port: String(toNumber(input.port, Number(current.port))),
216167
+ logLevel: toString2(input.logLevel, current.logLevel),
216168
+ enableWebUI: toBool(input.enableWebUI, current.enableWebUI),
216169
+ enableOfflineMode: toBool(input.enableOfflineMode, current.enableOfflineMode),
216170
+ workerIdleTimeout: toNumber(input.workerIdleTimeout, current.workerIdleTimeout),
216171
+ workersPerLanguage: toNumber(input.workersPerLanguage, current.workersPerLanguage),
216172
+ apiToken: toString2(input.apiToken, current.apiToken),
216173
+ logDir: toString2(input.logDir, current.logDir),
216174
+ logToFile: toBool(input.logToFile, current.logToFile),
216175
+ logConsole: toBool(input.logConsole, current.logConsole),
216176
+ logRequests: toBool(input.logRequests, current.logRequests),
216177
+ maxLengthBreak: toNumber(input.maxLengthBreak, current.maxLengthBreak),
216178
+ checkUpdate: toBool(input.checkUpdate, current.checkUpdate),
216179
+ cacheSize: toNumber(input.cacheSize, current.cacheSize),
216180
+ modelDir: toString2(input.modelDir, current.modelDir),
216181
+ configDir: toString2(input.configDir, current.configDir)
216182
+ };
216183
+ setConfig(next);
216184
+ saveConfigFile(next);
216185
+ setLogLevel(next.logLevel);
216186
+ };
216187
+ app.get("/ui/api/settings", async (_, res) => {
216188
+ const control = getDesktopControl();
216189
+ if (control?.getConfig) {
216190
+ const payload = await control.getConfig();
216191
+ res.json(payload);
216192
+ return;
216193
+ }
216194
+ res.json(getSettingsPayload());
216195
+ });
216196
+ app.post("/ui/api/settings/apply", async (req, res) => {
216197
+ const control = getDesktopControl();
216198
+ if (control?.applyConfig) {
216199
+ const payload = await control.applyConfig(req.body?.config || req.body);
216200
+ res.json(payload);
216201
+ return;
216202
+ }
216203
+ const input = req.body?.config?.server || req.body?.server || {};
216204
+ applyServerConfig(input);
216205
+ res.json(getSettingsPayload());
216206
+ });
216207
+ app.post("/ui/api/settings/reset", async (_, res) => {
216208
+ const control = getDesktopControl();
216209
+ if (control?.resetConfig) {
216210
+ const payload = await control.resetConfig();
216211
+ res.json(payload);
216212
+ return;
216213
+ }
216214
+ clearConfigFile();
216215
+ resetConfig();
216216
+ res.json(getSettingsPayload());
216217
+ });
216218
+ app.post("/ui/api/settings/restart", async (_, res) => {
216219
+ const control = getDesktopControl();
216220
+ if (control?.restartServer) {
216221
+ const payload = await control.restartServer();
216222
+ res.json(payload);
216223
+ return;
216224
+ }
216225
+ res.json(getSettingsPayload());
216226
+ });
219243
216227
  RegisterRoutes(app);
219244
216228
  app.use("/ui", (req, res, next) => {
219245
216229
  if (req.originalUrl === "/ui") {
@@ -219252,7 +216236,7 @@ async function run() {
219252
216236
  return res.redirect(301, "/docs/");
219253
216237
  }
219254
216238
  next();
219255
- }, swaggerStatic, import_swagger_ui_express.default.serve, import_swagger_ui_express.default.setup(swagger_default));
216239
+ }, swaggerStatic, swaggerUi.serve, swaggerUi.setup(swagger_default));
219256
216240
  app.get("/", (_, res) => res.redirect(301, "/ui/"));
219257
216241
  app.use((_, res) => res.status(404).send("404"));
219258
216242
  app.use(errorHandler());
@@ -219265,20 +216249,33 @@ async function run() {
219265
216249
  checkForUpdate();
219266
216250
  }
219267
216251
  });
219268
- const shutdown = async () => {
216252
+ const stop = async () => {
219269
216253
  info("Shutting down server...");
219270
216254
  cleanupAllEngines();
219271
- server2.close(() => {
219272
- info("Server shutdown complete");
219273
- process.exit(0);
219274
- });
219275
- setTimeout(() => {
219276
- error("Forced shutdown after timeout");
219277
- process.exit(1);
219278
- }, 1e4);
216255
+ await new Promise((resolve3) => server2.close(() => resolve3()));
216256
+ info("Server shutdown complete");
219279
216257
  };
219280
- process.on("SIGINT", shutdown);
219281
- process.on("SIGTERM", shutdown);
216258
+ if (handleSignals) {
216259
+ let shuttingDown = false;
216260
+ const shutdown = async () => {
216261
+ if (shuttingDown)
216262
+ return;
216263
+ shuttingDown = true;
216264
+ const timeout = setTimeout(() => {
216265
+ error("Forced shutdown after timeout");
216266
+ process.exit(1);
216267
+ }, 1e4);
216268
+ await stop();
216269
+ clearTimeout(timeout);
216270
+ process.exit(0);
216271
+ };
216272
+ process.on("SIGINT", shutdown);
216273
+ process.on("SIGTERM", shutdown);
216274
+ }
216275
+ return { server: server2, stop };
216276
+ }
216277
+ async function run() {
216278
+ const { server: server2 } = await startServer({ handleSignals: true });
219282
216279
  return server2;
219283
216280
  }
219284
216281
 
@@ -219427,5 +216424,5 @@ run().catch((error2) => {
219427
216424
  fatal("Failed to start server:", error2);
219428
216425
  });
219429
216426
 
219430
- //# debugId=9E50E63232D7FE8764756E2164756E21
216427
+ //# debugId=D0B31454CFA68C0664756E2164756E21
219431
216428
  //# sourceMappingURL=main.js.map