key.ts
2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/** 高德 Key 的取用:环境变量优先,其次终端隐藏输入。Key 不落盘、不进日志与缓存。 */
import process from 'node:process';
import { AmapClient } from './client.ts';
import { UserError } from './errors.ts';
/** 隐藏输入(等价 Python getpass):不回显,支持退格与 Ctrl+C。 */
export function promptHidden(question: string): Promise<string> {
const input = process.stdin;
if (input.isTTY !== true || input.setRawMode === undefined) {
return Promise.reject(new UserError('当前终端不支持隐藏输入,请设置环境变量 AMAP_KEY'));
}
return new Promise((resolve, reject) => {
let value = '';
const stop = () => {
input.off('data', onData);
input.off('SIGINT', onCancel);
input.setRawMode(false);
input.pause();
process.stdout.write('\n');
};
const onCancel = () => {
stop();
reject(new UserError('用户取消输入'));
};
const onData = (chunk: Buffer) => {
for (const char of chunk.toString('utf8')) {
const code = char.charCodeAt(0);
if (code === 13 || code === 10) {
stop();
resolve(value);
return;
}
if (code === 3) {
onCancel();
return;
}
if (code === 8 || code === 127) value = value.slice(0, -1);
else if (code >= 32) value += char;
}
};
input.on('data', onData);
input.on('SIGINT', onCancel);
process.stdout.write(question);
input.setRawMode(true);
input.resume();
});
}
/** 只有确有待查坐标时才会走到这里:能靠地址与缓存补齐的运行不需要 Key。 */
export async function createClient(qps: number): Promise<AmapClient> {
const fromEnv = typeof process.env.AMAP_KEY === 'string' ? process.env.AMAP_KEY.trim() : '';
if (fromEnv !== '') return new AmapClient(fromEnv, qps);
if (process.stdin.isTTY !== true) throw new UserError('非交互运行请先设置环境变量 AMAP_KEY');
const key = (await promptHidden('请输入高德 Web 服务 Key(隐藏输入):')).trim();
return new AmapClient(key, qps);
}