file-handle 0.0.5 → 0.0.7

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/README.md CHANGED
@@ -26,7 +26,7 @@ A simple local web file server with a user-friendly interface, allowing easy fil
26
26
  > npx file-handle
27
27
  ```
28
28
 
29
- ## Installation Usage
29
+ ### Installation Usage
30
30
 
31
31
  ```bash
32
32
  > npm install -g file-handle
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "file-handle",
3
- "version": "0.0.5",
3
+ "version": "0.0.7",
4
4
  "author": "jsonhandle@gmail.com",
5
5
  "description": "A simple local web file server with a user-friendly interface, allowing easy file upload, download, preview, and management through a browser. \n一个简易的文件服务器,方便通过浏览器来浏览、上传或管理目录和文件. ",
6
6
  "main": "server/index.js",
@@ -12,7 +12,8 @@
12
12
  "upload",
13
13
  "download",
14
14
  "preview",
15
- "file",
15
+ "transfer",
16
+ "share",
16
17
  "serve",
17
18
  "web-server",
18
19
  "http-server"
package/server/bin/cli.js CHANGED
@@ -1,13 +1,14 @@
1
- #!/usr/bin/env node --title=File-Handle-Server
1
+ #!/usr/bin/env node
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+ import { fileURLToPath } from 'url';
2
5
  import yargs from 'yargs';
3
6
  import { hideBin } from 'yargs/helpers';
4
- import path from 'path';
5
- import { startServer } from "../index.js";
7
+ import { start } from './fork.js';
6
8
  import { getText } from '../common/i18n.js';
7
- import packageData from '../../package.json' with { type: "json" };
8
9
  import { parseFileSize } from '../config.js';
9
10
  const cmdConfig = loadCmdArgs(process.argv);
10
- startServer(cmdConfig);
11
+ start(cmdConfig);
11
12
  // 加载命令行参数
12
13
  function loadCmdArgs(args) {
13
14
  const lang = getText();
@@ -41,6 +42,11 @@ function loadCmdArgs(args) {
41
42
  type: 'array',
42
43
  description: lang.config.tlsDesc
43
44
  },
45
+ 't': {
46
+ alias: 'time',
47
+ type: 'number',
48
+ description: lang.config.timeDesc
49
+ },
44
50
  'del': {
45
51
  type: 'boolean',
46
52
  description: lang.config.delDesc,
@@ -79,6 +85,8 @@ function loadCmdArgs(args) {
79
85
  .help()
80
86
  .argv;
81
87
  if ('V' in argv || 'v' in argv) {
88
+ const mdDir = path.dirname(fileURLToPath(import.meta.url));
89
+ const packageData = JSON.parse(fs.readFileSync(path.join(mdDir, '../../package.json')).toString());
82
90
  console.log(`v${packageData.version}`);
83
91
  process.exit(0);
84
92
  }
@@ -88,6 +96,7 @@ function loadCmdArgs(args) {
88
96
  version: argv.version,
89
97
  allowDelete: argv.del,
90
98
  allowEdit: argv.edit,
99
+ time: argv.time,
91
100
  writeLog: argv.log ? true : undefined,
92
101
  password: argv.password,
93
102
  uploadLimit: parseFileSize(argv.limit),
@@ -0,0 +1,23 @@
1
+ import { startServer } from '../index.js';
2
+ import { fork } from 'child_process';
3
+ import path from 'path';
4
+ import { loadConfig } from '../config.js';
5
+ import Debug from 'debug';
6
+ const debug = Debug('FH fork');
7
+ process.on('message', (msg) => {
8
+ startServer(JSON.parse(msg.opt));
9
+ });
10
+ export function start(config) {
11
+ const env = loadConfig({ rootDir: process.cwd() });
12
+ const forkEnter = path.join(env.mdDir, './bin/fork.js');
13
+ const child = fork(forkEnter, [], {
14
+ execArgv: ['--title=File-Handle-Server']
15
+ });
16
+ child.on('message', (msg) => {
17
+ debug('child:', msg);
18
+ });
19
+ child.send({ opt: JSON.stringify(config) });
20
+ child.on('exit', (code) => {
21
+ debug(`FH exited with code ${code}`);
22
+ });
23
+ }
@@ -7,15 +7,17 @@ const i18n = {
7
7
  switchLang: 'Switch to English'
8
8
  },
9
9
  server: {
10
- startingHttps: '正在启动HTTPS服务器...',
11
- startingHttp: '正在启动HTTP服务器...',
10
+ startingHttps: '正在启动 FH HTTPS 服务器...',
11
+ startingHttp: '正在启动 FH HTTP 服务器...',
12
12
  running: 'File-Handle Server正在运行,端口:',
13
13
  rootDirectory: '根目录:',
14
14
  accessibleAddresses: '可访问的地址:',
15
15
  allowedIpsOnly: '仅允许指定IP访问',
16
16
  localAndLanOnly: '仅允许本地和局域网访问',
17
17
  loginPassword: '登录密码是:',
18
- portInUse: '端口 {port} 正在使用中, 正在尝试下一个端口。'
18
+ portInUse: '端口 {port} 正在使用中, 正在尝试下一个端口。',
19
+ exitAfterTime: '服务器将在 {time} 秒后退出',
20
+ exitOutTime: '服务器到时退出'
19
21
  },
20
22
  config: {
21
23
  allowWanDesc: '允许公网访问',
@@ -23,6 +25,7 @@ const i18n = {
23
25
  portDesc: '指定服务器监听的端口号',
24
26
  ipDesc: '指定服务器允许访问的IP地址,多个IP地址用逗号分隔',
25
27
  tlsDesc: '启用HTTPS安全传输,需提供证书和密钥文件路径',
28
+ timeDesc: '启动多少秒后退出',
26
29
  delDesc: '启用文件删除功能',
27
30
  passwordDesc: '设置服务器访问的密码',
28
31
  editDesc: '启用文件编辑修改功能',
@@ -39,15 +42,17 @@ const i18n = {
39
42
  switchLang: '切换到中文'
40
43
  },
41
44
  server: {
42
- startingHttps: 'Starting HTTPS server...',
43
- startingHttp: 'Starting HTTP server...',
45
+ startingHttps: 'Starting FH HTTPS server...',
46
+ startingHttp: 'Starting FH HTTP server...',
44
47
  running: 'File-Handle Server is running on port',
45
48
  rootDirectory: 'Root directory:',
46
49
  accessibleAddresses: 'Accessible addresses:',
47
50
  allowedIpsOnly: 'Only allowed IPs can access',
48
51
  localAndLanOnly: 'Only local and LAN access allowed',
49
52
  loginPassword: 'Login password is:',
50
- portInUse: 'Port {port} is being used, trying next port...'
53
+ portInUse: 'Port {port} is being used, trying next port...',
54
+ exitAfterTime: 'Server will exit after {time} seconds',
55
+ exitOutTime: 'The server has expired and exited'
51
56
  },
52
57
  config: {
53
58
  allowWanDesc: 'Allow public network access',
@@ -55,6 +60,7 @@ const i18n = {
55
60
  portDesc: 'Specify server listening port',
56
61
  ipDesc: 'Specify allowed IP addresses, separated by commas',
57
62
  tlsDesc: 'Enable HTTPS secure transmission, requires certificate and key file paths',
63
+ timeDesc: 'How many seconds does it exit',
58
64
  delDesc: 'Enable file deletion',
59
65
  passwordDesc: 'Set server access password',
60
66
  editDesc: 'Enable file editing',
package/server/config.js CHANGED
@@ -7,6 +7,8 @@ import Debug from 'debug';
7
7
  import packageData from '../package.json' with { type: "json" };
8
8
  const debug = Debug('FH config');
9
9
  export const appName = 'File-Handle';
10
+ const keyPath = 'app.key';
11
+ let oKey;
10
12
  // 文件大小单位转换
11
13
  const sizeUnits = {
12
14
  PB: 1024 * 1024 * 1024 * 1024 * 1024,
@@ -26,14 +28,23 @@ global.config = global.config || {
26
28
  writeLog: false,
27
29
  uploadLimit: parseFileSize('3GB'),
28
30
  allowWan: false,
31
+ ipList: ['127.0.0.1']
29
32
  };
30
33
  export function loadConfig(opt) {
31
- const runConfig = Object.assign(Object.create(global.config), opt);
32
- if (runConfig.password === '') {
33
- runConfig.password = createRandomPassword(16);
34
+ if (!fs.existsSync(opt.rootDir)) {
35
+ throw new Error(`Root directory does not exist. => ${opt.rootDir}`);
34
36
  }
37
+ for (const key in global.config) {
38
+ if (opt[key] === undefined) {
39
+ opt[key] = global.config[key];
40
+ }
41
+ }
42
+ if (opt.password === '') {
43
+ opt.password = createRandomPassword(16);
44
+ }
45
+ global.config = opt;
35
46
  createAppKey(global.config);
36
- return runConfig;
47
+ return opt;
37
48
  }
38
49
  export function getAppKeyPath() {
39
50
  const priKeyPath = path.join(config.dataDir, 'hostPri.key');
@@ -87,7 +98,7 @@ export function createRandomPassword(n) {
87
98
  return password;
88
99
  }
89
100
  // 加密信息
90
- export function encryptData(msg, pubKey) {
101
+ export function encryptDataRsa(msg, pubKey) {
91
102
  try {
92
103
  const maxChunkSize = 190;
93
104
  const messageBuffer = Buffer.from(msg);
@@ -107,11 +118,11 @@ export function encryptData(msg, pubKey) {
107
118
  }
108
119
  catch (error) {
109
120
  debug('加密失败:', error);
110
- console.log(error);
121
+ // console.log(error);
111
122
  throw error;
112
123
  }
113
124
  }
114
- export function decryptData(msg, priKey) {
125
+ export function decryptDataRsa(msg, priKey) {
115
126
  try {
116
127
  const encryptedBuffer = Buffer.from(msg, 'base64');
117
128
  const chunkSize = 256;
@@ -134,6 +145,57 @@ export function decryptData(msg, priKey) {
134
145
  throw error;
135
146
  }
136
147
  }
148
+ function getKey() {
149
+ const thirtyDaysInMillis = 30 * 24 * 60 * 60 * 1000;
150
+ const currentTime = +new Date();
151
+ let keyData;
152
+ const keyFilePath = path.join(config.dataDir, keyPath);
153
+ if (!oKey) {
154
+ if (fs.existsSync(keyFilePath)) {
155
+ const keyContent = fs.readFileSync(keyFilePath, 'utf8');
156
+ keyData = JSON.parse(keyContent);
157
+ oKey = keyData;
158
+ }
159
+ }
160
+ if (!oKey || Math.abs(currentTime - oKey.time) > thirtyDaysInMillis) {
161
+ oKey = createKey();
162
+ }
163
+ // console.log('get: ', JSON.stringify(oKey, null, 2));
164
+ return {
165
+ key: Buffer.from(oKey.key, 'base64'),
166
+ iv: Buffer.from(oKey.iv, 'base64'),
167
+ };
168
+ }
169
+ function createKey() {
170
+ const keyFilePath = path.join(config.dataDir, keyPath);
171
+ const key = crypto.randomBytes(32); // 256位密钥
172
+ const iv = crypto.randomBytes(16); // 初始化向量
173
+ const oKey = {
174
+ key: key.toString('base64'),
175
+ iv: iv.toString('base64'),
176
+ time: +new Date()
177
+ };
178
+ fs.writeFileSync(keyFilePath, JSON.stringify(oKey));
179
+ const oData = JSON.parse(fs.readFileSync(keyFilePath).toString());
180
+ // console.log('create: ', JSON.stringify(oData, null, 2));
181
+ return oData;
182
+ }
183
+ // 加密函数
184
+ export function encrypt(text) {
185
+ const { key, iv } = getKey();
186
+ const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
187
+ let encrypted = cipher.update(text, 'utf8', 'hex');
188
+ encrypted += cipher.final('hex');
189
+ return encrypted;
190
+ }
191
+ // 解密函数
192
+ export function decrypt(encrypted) {
193
+ const { key, iv } = getKey();
194
+ const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
195
+ let decrypted = decipher.update(encrypted, 'hex', 'utf8');
196
+ decrypted += decipher.final('utf8');
197
+ return decrypted;
198
+ }
137
199
  function getUserDataDir() {
138
200
  let dir = path.join(os.homedir(), `.${appName}`);
139
201
  switch (process.platform) {
package/server/fh.app.dat CHANGED
Binary file
package/server/index.js CHANGED
@@ -18,7 +18,7 @@ import { info, debug } from './utils/logger.js';
18
18
  const lang = getText();
19
19
  export async function startServer(opt) {
20
20
  // 加载配置
21
- const config = Object.freeze(loadConfig(opt));
21
+ const config = loadConfig(opt);
22
22
  global.config = config;
23
23
  if (!global.config.rootDir) {
24
24
  throw new Error('Root directory is required');
@@ -65,48 +65,70 @@ export async function startServer(opt) {
65
65
  }
66
66
  const port = await findAvailablePort(config.port);
67
67
  const localIPs = getLocalNetworkIPs();
68
- if (config.allowedIPs) {
69
- // 如果指定了允许访问的IP地址,则只允许这些IP访问
70
- server.listen(port, '0.0.0.0', () => {
71
- info(lang.server.allowedIpsOnly);
72
- info(`${lang.server.running}${color.blueBright(port)}`);
73
- info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
74
- info(lang.server.accessibleAddresses);
75
- info(color.green(`http://127.0.0.1:${port}/fh/`));
76
- config.allowedIPs && config.allowedIPs.forEach(ip => {
77
- info(color.green(`http://${ip}:${port}/fh/`));
68
+ global.config.port = port;
69
+ return new Promise((resolve, reject) => {
70
+ if (config.allowedIPs) {
71
+ // 如果指定了允许访问的IP地址,则只允许这些IP访问
72
+ server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
73
+ info(lang.server.allowedIpsOnly);
74
+ info(`${lang.server.running}${color.blueBright(port)}`);
75
+ info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
76
+ info(lang.server.accessibleAddresses);
77
+ info(color.green(`http://127.0.0.1:${port}/fh/`));
78
+ config.allowedIPs && config.allowedIPs.forEach(ip => {
79
+ info(color.green(`http://${ip}:${port}/fh/`));
80
+ config.ipList?.push(ip);
81
+ });
82
+ info('\n\n');
78
83
  });
79
- info('\n\n');
80
- });
81
- }
82
- else if (localIPs.length > 0 && !config.allowWan) {
83
- // 如果存在局域网IP且未启用公网访问,则只监听局域网IP
84
- server.listen(port, '0.0.0.0', () => {
85
- info(lang.server.localAndLanOnly);
86
- info(`${lang.server.running}${color.blueBright(port)}`);
87
- info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
88
- info(lang.server.accessibleAddresses);
89
- info(color.green(`http://127.0.0.1:${port}/fh/`));
90
- localIPs.forEach(ip => {
91
- info(color.green(`http://${ip}:${port}/fh/`));
84
+ }
85
+ else if (localIPs.length > 0 && !config.allowWan) {
86
+ // 如果存在局域网IP且未启用公网访问,则只监听局域网IP
87
+ server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
88
+ info(lang.server.localAndLanOnly);
89
+ info(`${lang.server.running}${color.blueBright(port)}`);
90
+ info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
91
+ info(lang.server.accessibleAddresses);
92
+ info(color.green(`http://127.0.0.1:${port}/fh/`));
93
+ localIPs.forEach(ip => {
94
+ info(color.green(`http://${ip}:${port}/fh/`));
95
+ config.ipList?.push(ip);
96
+ });
97
+ info('\n\n');
92
98
  });
93
- info('\n\n');
94
- });
95
- }
96
- else {
97
- // 允许所有IP访问
98
- server.listen(port, '0.0.0.0', () => {
99
- info(`${lang.server.running}${color.blueBright(port)}`);
100
- info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
101
- info(lang.server.accessibleAddresses);
102
- info(`http://0.0.0.0:${port}/fh/`);
103
- info(color.green(`http://127.0.0.1:${port}/fh/`));
104
- info(`\n\n`);
105
- });
106
- }
107
- if (config.password) {
108
- info(`${lang.server.loginPassword}${color.green(config.password)}`);
109
- }
99
+ }
100
+ else {
101
+ // 允许所有IP访问
102
+ server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
103
+ info(`${lang.server.running}${color.blueBright(port)}`);
104
+ info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
105
+ info(lang.server.accessibleAddresses);
106
+ info(`http://0.0.0.0:${port}/fh/`);
107
+ info(color.green(`http://127.0.0.1:${port}/fh/`));
108
+ localIPs.forEach(ip => {
109
+ config.ipList?.push(ip);
110
+ });
111
+ info(`\n\n`);
112
+ });
113
+ }
114
+ if (config.password) {
115
+ info(`${lang.server.loginPassword}${color.green(config.password)}`);
116
+ }
117
+ }).then(_ => {
118
+ // 对ipList进行去重
119
+ if (global.config.ipList) {
120
+ global.config.ipList = [...new Set(global.config.ipList)];
121
+ }
122
+ global.config = Object.freeze(global.config);
123
+ if (config.time) {
124
+ // @ts-ignore
125
+ info(lang.server.exitAfterTime.replace('{time}', color.red(config.time.toString())));
126
+ setTimeout(() => {
127
+ info(lang.server.exitOutTime);
128
+ process.exit(0);
129
+ }, config.time * 1000);
130
+ }
131
+ });
110
132
  }
111
133
  async function findAvailablePort(startPort, maxAttempts = 50) {
112
134
  const app = express();
@@ -1,41 +1,54 @@
1
1
  import { Router } from 'express';
2
2
  import Debug from 'debug';
3
- import { getAppKey } from '../config.js';
4
- import { decryptData, encryptData } from '../config.js';
3
+ import { decrypt, encrypt } from '../config.js';
5
4
  import { ApiResponseBuilder } from '../types/response.js';
6
5
  const debug = Debug('app:route');
7
- const { priKey, pubKey } = getAppKey();
8
6
  export function createAppRouter(config) {
9
7
  const router = Router();
10
8
  router.get('/getServerInfo', (req, res, next) => {
11
- checkAuth(req, res, next);
12
- res.json(ApiResponseBuilder.success(encryptData(JSON.stringify(config), pubKey)));
9
+ checkAuth('getServerInfo', req, res, next);
10
+ res.json(ApiResponseBuilder.success(encrypt(JSON.stringify(config))));
13
11
  });
14
12
  router.get('/shutdown', (req, res, next) => {
15
- checkAuth(req, res, next);
16
- res.json(ApiResponseBuilder.success({
13
+ checkAuth('shutdown', req, res, next);
14
+ res.json(ApiResponseBuilder.success(encrypt(JSON.stringify({
17
15
  rootDir: config.rootDir,
18
16
  port: config.port,
19
17
  shutdown: true
20
- }));
18
+ }))));
21
19
  setTimeout(() => {
22
20
  process.exit(0);
23
21
  }, 500);
24
22
  });
25
23
  router.get('/test', (req, res, next) => {
26
- let msg = encryptData('xxx', pubKey);
27
- let text = decryptData(msg, priKey);
24
+ let msg = encrypt('ok');
25
+ let text = decrypt(msg);
28
26
  console.log(text);
29
- res.status(404).send('Not Found');
27
+ res.send(text);
30
28
  });
31
- router.get('/*', (req, res, next) => {
32
- res.status(404).send('Not Found');
29
+ router.get('/token', (req, res, next) => {
30
+ let token = encrypt(JSON.stringify({
31
+ token: (+new Date()).toString(),
32
+ version: config.version
33
+ }));
34
+ res.json(ApiResponseBuilder.success(token));
33
35
  });
36
+ // router.get('/*', (req, res, next) => {
37
+ // res.status(404).send('Not Found');
38
+ // });
34
39
  return router;
35
40
  }
36
- function checkAuth(req, res, next) {
41
+ function checkAuth(act, req, res, next) {
37
42
  const authInHeader = req.headers['authorization'];
38
- if (!authInHeader || decryptData(authInHeader, priKey) != 'file-handle-mc') {
39
- res.status(403).send('Unauthorized');
43
+ if (authInHeader) {
44
+ try {
45
+ const oAuth = JSON.parse(decrypt(authInHeader));
46
+ if (Math.abs(+new Date() - +oAuth.time) < 1000 && oAuth.act === act) {
47
+ next();
48
+ return;
49
+ }
50
+ }
51
+ catch (error) { }
40
52
  }
53
+ res.status(403).send('Unauthorized');
41
54
  }
@@ -0,0 +1,336 @@
1
+ import exhaust from 'exhaust';
2
+ // 36进制字符集
3
+ const CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
4
+ const oIndexs = {
5
+ 1: () => {
6
+ // 18, 2, 1
7
+ const r = oIndexs.build([buildArrFrom(0, 17), [0, 1], [6688]]);
8
+ oIndexs[1] = () => r;
9
+ return r;
10
+ },
11
+ 2: (p) => {
12
+ // 7, 3, 1
13
+ // 25, 5, 2
14
+ const r = oIndexs.build([buildArrFrom(18, 24), [2, 3, 4], [6689]], p);
15
+ oIndexs[2] = () => r;
16
+ return r;
17
+ },
18
+ 3: (p) => {
19
+ // 13, 4, 1
20
+ // 48, 9, 3
21
+ const r = oIndexs.build([buildArrFrom(25, 47), buildArrFrom(5, 8), [6690]], p);
22
+ oIndexs[3] = () => r;
23
+ return r;
24
+ },
25
+ 4: (p) => {
26
+ // 13, 36, 1
27
+ // 255, 45, 4
28
+ const r = oIndexs.build([buildArrFrom(48, 255), buildArrFrom(9, 24).concat([30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 253, 254]), [6691]], p);
29
+ oIndexs[4] = () => r;
30
+ return r;
31
+ },
32
+ 5: () => {
33
+ },
34
+ build: (rangs, p) => {
35
+ let oIndex = {};
36
+ let i = 0;
37
+ if (p) {
38
+ i = p.oIndex.lastIndex + 1;
39
+ oIndex = Object.create(p.oIndex);
40
+ }
41
+ exhaust((may) => `${may(rangs[0])},${may(rangs[1])},${may(rangs[2])}`).forEach((s) => {
42
+ oIndex[s] = i++;
43
+ });
44
+ let mergeRangs = rangs;
45
+ if (p) {
46
+ let [a1, a2, a3] = p.rangs;
47
+ const [b1, b2, b3] = rangs;
48
+ mergeRangs = [a1.concat(b1), a2.concat(b2), a3.concat(b3)];
49
+ exhaust((may) => `${may(mergeRangs[0])},${may(mergeRangs[1])},${may(mergeRangs[2])}`).forEach((s) => {
50
+ if (!(s in oIndex)) {
51
+ oIndex[s] = i++;
52
+ }
53
+ });
54
+ }
55
+ oIndex.lastIndex = i - 1;
56
+ const r = {
57
+ rangs: mergeRangs,
58
+ oIndex,
59
+ check: (a, b, c) => {
60
+ return mergeRangs[0].includes(a) && mergeRangs[1].includes(b) && mergeRangs[2].includes(c);
61
+ }
62
+ };
63
+ return r;
64
+ }
65
+ };
66
+ function buideIndex(lv) {
67
+ let oIndex = oIndexs[1]();
68
+ for (let i = 2; i <= lv; i++) {
69
+ oIndex = oIndexs[i](oIndex);
70
+ }
71
+ return oIndex;
72
+ }
73
+ function encode(a, b, c) {
74
+ // 检查输入范围
75
+ if (a < 0 || a > 255 || b < 0 || b > 255 || c < 1 || c > 65536) {
76
+ throw new Error('输入数值超出范围');
77
+ }
78
+ // 高频区域: 1个字符
79
+ let oIndexConfig = buideIndex(1);
80
+ if (oIndexConfig.check(a, b, c)) {
81
+ const index = oIndexConfig.oIndex[[a, b, c].toString()];
82
+ return numToCode(index);
83
+ }
84
+ // 中频区域: 2个字符
85
+ oIndexConfig = buideIndex(2);
86
+ if (oIndexConfig.check(a, b, c)) {
87
+ const index = oIndexConfig.oIndex[[a, b, c].toString()];
88
+ return numToCode(index);
89
+ }
90
+ // 低频区域: 2个字符
91
+ oIndexConfig = buideIndex(3);
92
+ if (oIndexConfig.check(a, b, c)) {
93
+ const index = oIndexConfig.oIndex[[a, b, c].toString()];
94
+ return numToCode(index);
95
+ }
96
+ // 罕见区域: 3个字符
97
+ oIndexConfig = buideIndex(4);
98
+ if (oIndexConfig.check(a, b, c)) {
99
+ const index = oIndexConfig.oIndex[[a, b, c].toString()];
100
+ return numToCode(index);
101
+ }
102
+ return encodeBig(a, b, c);
103
+ }
104
+ function decode(str) {
105
+ if (!str || str.length === 0) {
106
+ throw new Error('输入字符串不能为空');
107
+ }
108
+ if (!/^[0-9A-Z]+$/.test(str)) {
109
+ throw new Error('无效的编码字符串 of [0-9A-Z]');
110
+ }
111
+ const index = codeToNum(str);
112
+ // 高频区域: 1个字符
113
+ if (str.length < 3) {
114
+ const oIndex = buideIndex(2).oIndex;
115
+ for (const key in oIndex) {
116
+ if (oIndex[key] === index) {
117
+ return key.split(',').map(Number);
118
+ }
119
+ }
120
+ }
121
+ // 中低频区域: 2个字符
122
+ if (str.length < 3) {
123
+ const oIndex = buideIndex(3).oIndex;
124
+ for (const key in oIndex) {
125
+ if (oIndex[key] === index) {
126
+ return key.split(',').map(Number);
127
+ }
128
+ }
129
+ }
130
+ // 罕见区域: 3个字符
131
+ if (str.length < 4) {
132
+ const oIndex = buideIndex(4).oIndex;
133
+ for (const key in oIndex) {
134
+ if (oIndex[key] === index) {
135
+ return key.split(',').map(Number);
136
+ }
137
+ }
138
+ }
139
+ return decodeBig(str);
140
+ }
141
+ function encodeBig(a, b, c) {
142
+ // 验证输入范围
143
+ if (a < 0 || a > 255 || b < 0 || b > 255 || c < 1 || c > 65536) {
144
+ throw new Error('Invalid input parameters. Expected a:0-255, b:0-255, c:1-65536');
145
+ }
146
+ // 计算组合值
147
+ const combined = a * 0x1000000 + b * 0x10000 + (c - 1);
148
+ // 转换为36进制并大写,补齐7位
149
+ return combined.toString(36).toUpperCase().padStart(7, '0');
150
+ }
151
+ function decodeBig(str) {
152
+ // 验证输入字符串
153
+ if (!str || str.length !== 7 || !/^[0-9A-Z]+$/.test(str)) {
154
+ throw new Error('Invalid encoded string: must be 7 characters of [0-9A-Z]');
155
+ }
156
+ // 转换为小写并解析
157
+ const combined = parseInt(str.toLowerCase(), 36);
158
+ if (isNaN(combined)) {
159
+ throw new Error('Invalid encoded string');
160
+ }
161
+ // 验证组合值范围
162
+ if (combined < 0 || combined > 0xFFFFFFFF) {
163
+ throw new Error('Encoded value out of valid range');
164
+ }
165
+ // 分解各部分的数值
166
+ const a = (combined >>> 24) & 0xFF;
167
+ const b = (combined >>> 16) & 0xFF;
168
+ const c = (combined & 0xFFFF) + 1; // 恢复c的原始值
169
+ // 验证分解后的参数范围
170
+ if (a < 0 || a > 255 || b < 0 || b > 255 || c < 1 || c > 65536) {
171
+ throw new Error('Decoded values out of range');
172
+ }
173
+ return [a, b, c];
174
+ }
175
+ // 将十进制数转换为36进制字符串
176
+ function numToCode(num) {
177
+ let result = '';
178
+ if (num === 0) {
179
+ return '0';
180
+ }
181
+ while (num > 0) {
182
+ const remainder = num % 36;
183
+ result = CHARS[remainder] + result;
184
+ num = Math.floor(num / 36);
185
+ }
186
+ return result;
187
+ }
188
+ // 将36进制字符串转换为十进制数
189
+ function codeToNum(code) {
190
+ let result = 0;
191
+ for (let i = 0; i < code.length; i++) {
192
+ const char = code[i];
193
+ const value = CHARS.indexOf(char);
194
+ result = result * 36 + value;
195
+ }
196
+ return result;
197
+ }
198
+ // 生成一个范围数组
199
+ function buildArrFrom(start, end) {
200
+ const arr = [];
201
+ for (let i = start; i <= end; i++) {
202
+ arr.push(i);
203
+ }
204
+ return arr;
205
+ }
206
+ /*
207
+ // 测试代码
208
+ function test() {
209
+ describe('编码解码测试', () => {
210
+ // 高频区域测试
211
+ it('高频区域编码解码', () => {
212
+ // 测试边界值
213
+ const testCases = [
214
+ [ 0, 0, 6688 ],
215
+ [ 1, 0, 6688 ],
216
+ [ 0, 1, 6688 ],
217
+ [ 1, 1, 6688 ],
218
+ [ 3, 1, 6688 ],
219
+ [ 4, 1, 6688 ],
220
+ [ 5, 1, 6688 ],
221
+ [ 6, 1, 6688 ],
222
+ [ 7, 1, 6688 ]
223
+ ];
224
+
225
+ testCases.forEach(([ a, b, c ]) => {
226
+ const encoded = encode(a, b, c);
227
+ assert.strictEqual(encoded.length, 1, '高频区域编码应为1个字符');
228
+ const decoded = decode(encoded);
229
+ assert.deepStrictEqual(decoded, [ a, b, c ], '解码结果应与原始输入匹配');
230
+ });
231
+ });
232
+
233
+ // 中频区域测试
234
+ it('中频区域编码解码', () => {
235
+ const testCases = [
236
+ [ 19, 3, 6688 ],
237
+ [ 1, 0, 6689 ],
238
+ [ 0, 3, 6689 ],
239
+ [ 20, 4, 6689 ],
240
+ [ 5, 1, 6689 ],
241
+ [ 0, 4, 6688 ]
242
+ ];
243
+
244
+ testCases.forEach(([ a, b, c ]) => {
245
+ const encoded = encode(a, b, c);
246
+ assert.strictEqual(encoded.length, 2, '中频区域编码应为2个字符');
247
+ const decoded = decode(encoded);
248
+ assert.deepStrictEqual(decoded, [ a, b, c ], '解码结果应与原始输入匹配');
249
+ });
250
+ });
251
+
252
+ // 低频区域测试
253
+ it('低频区域编码解码', () => {
254
+ const testCases = [
255
+ [ 19, 5, 6688 ],
256
+ [ 28, 0, 6689 ],
257
+ [ 0, 7, 6689 ],
258
+ [ 28, 5, 6689 ],
259
+ [ 5, 1, 6690 ],
260
+ [ 1, 1, 6690 ]
261
+ ];
262
+
263
+ testCases.forEach(([ a, b, c ]) => {
264
+ const encoded = encode(a, b, c);
265
+ assert.strictEqual(encoded.length, 2, '低频区域编码应为2个字符');
266
+ const decoded = decode(encoded);
267
+ assert.deepStrictEqual(decoded, [ a, b, c ], '解码结果应与原始输入匹配');
268
+ });
269
+ });
270
+
271
+ // 罕见区域测试
272
+ it('罕见区域编码解码', () => {
273
+ const testCases = [
274
+ [ 49, 5, 6688 ],
275
+ [ 28, 9, 6689 ],
276
+ [ 232, 13, 6689 ],
277
+ [ 28, 150, 6689 ],
278
+ [ 5, 1, 6691 ],
279
+ [ 111, 254, 6691 ]
280
+ ];
281
+
282
+ testCases.forEach(([ a, b, c ]) => {
283
+ const encoded = encode(a, b, c);
284
+ assert.strictEqual(encoded.length, 3, '罕见区域编码应为3个字符');
285
+ const decoded = decode(encoded);
286
+ assert.deepStrictEqual(decoded, [ a, b, c ], '解码结果应与原始输入匹配');
287
+ });
288
+ });
289
+
290
+ // 其它区域测试
291
+ it('其它区域编码解码', () => {
292
+ const testCases = [
293
+ [ 49, 5, 8688 ],
294
+ [ 28, 191, 8689 ],
295
+ [ 232, 188, 6689 ],
296
+ [ 28, 150, 3689 ],
297
+ [ 5, 1, 691 ],
298
+ [ 111, 121, 16691 ]
299
+ ];
300
+
301
+ testCases.forEach(([ a, b, c ]) => {
302
+ const encoded = encode(a, b, c);
303
+ assert.strictEqual(encoded.length, 7, '其它区域编码应为7个字符');
304
+ const decoded = decode(encoded);
305
+ assert.deepStrictEqual(decoded, [ a, b, c ], '解码结果应与原始输入匹配');
306
+ });
307
+ });
308
+
309
+ // 边界条件测试
310
+ it('输入范围验证', () => {
311
+ assert.throws(() => encode(-1, 0, 1), Error, '应当检测到负数输入');
312
+ assert.throws(() => encode(256, 0, 1), Error, '应当检测到a超出范围');
313
+ assert.throws(() => encode(0, 256, 1), Error, '应当检测到b超出范围');
314
+ assert.throws(() => encode(0, 0, 0), Error, '应当检测到c小于1');
315
+ assert.throws(() => encode(0, 0, 65537), Error, '应当检测到c超出范围');
316
+ });
317
+
318
+ // 解码异常测试
319
+ it('解码异常验证', () => {
320
+ assert.throws(() => decode(''), Error, '应当检测到空字符串');
321
+ assert.throws(() => decode('Q-'), Error, '应当检测到无效的编码字符串');
322
+ });
323
+ });
324
+ }
325
+
326
+
327
+ function describe(title:string, fun:Function) {
328
+ console.log(title, '\n开始测试...\n');
329
+ fun();
330
+ console.log(title, '测试完成\n');
331
+ }
332
+ const it = describe;
333
+
334
+ test();
335
+
336
+ */