pubo-node 1.0.206 → 1.0.207

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.
@@ -1,11 +1,15 @@
1
- export declare function getProcessName(pid: any): Promise<string>;
2
- export declare function getPidByPort(port: any): Promise<number>;
1
+ interface ProcessTree {
2
+ pid: number;
3
+ children: ProcessTree[];
4
+ }
5
+ export declare function getProcessName(pid: number): Promise<string>;
6
+ export declare function getPidByPort(port: number): Promise<number>;
3
7
  export declare function getProcessCpuUseByPid(pid: number): Promise<number>;
4
8
  export declare function getProcessCommandByPid(pid: number): Promise<string>;
5
9
  export declare function isProcessDied(pid: number): Promise<boolean>;
6
10
  export declare function getProcessByPpid(pid: number): Promise<number[]>;
7
- export declare const getProcessTree: (pid: number, tree?: any) => Promise<any>;
8
- export declare const getProcessList: (pid: any) => Promise<number[]>;
11
+ export declare const getProcessTree: (pid: number, tree?: ProcessTree) => Promise<ProcessTree | null>;
12
+ export declare const getProcessList: (pid: number) => Promise<number[]>;
9
13
  export declare function SIGKILL(pid: number, signal?: number, times?: number): Promise<{
10
14
  success: boolean;
11
15
  error: string;
@@ -15,4 +19,5 @@ export declare const getAudioCards: (filter?: string) => Promise<{
15
19
  text: string;
16
20
  index: string;
17
21
  }[]>;
18
- export declare const getDiskUsage: () => Promise<import("./p-process-type").DiskInfo[]>;
22
+ export declare const getDiskUsage: () => Promise<unknown[]>;
23
+ export {};
@@ -52,10 +52,7 @@ const getProcessTree = async (pid, tree) => {
52
52
  if (isRoot) {
53
53
  return tree;
54
54
  }
55
- else {
56
- tree = null;
57
- return null;
58
- }
55
+ return null;
59
56
  };
60
57
  exports.getProcessTree = getProcessTree;
61
58
  // 广度优先遍历进程树,将pid放入tmp
@@ -64,20 +61,17 @@ const flatProcessTree = (tree, tmp) => {
64
61
  tmp.push(...tree.children.map((item) => item.pid));
65
62
  tree.children.forEach((item) => flatProcessTree(item, tmp));
66
63
  }
67
- tree = null;
68
- tmp = null;
69
64
  };
70
65
  // 获取所有进程PID,从叶到根
71
66
  const getProcessList = async (pid) => {
72
- let tree = await (0, exports.getProcessTree)(pid);
67
+ const tree = await (0, exports.getProcessTree)(pid);
73
68
  const tmp = [];
74
- if (!tree.pid) {
69
+ if (!tree?.pid) {
75
70
  return tmp;
76
71
  }
77
72
  tmp.push(tree.pid);
78
73
  flatProcessTree(tree, tmp);
79
74
  tmp.reverse();
80
- tree = null;
81
75
  return tmp;
82
76
  };
83
77
  exports.getProcessList = getProcessList;
@@ -92,7 +86,7 @@ const heartbeat = () => {
92
86
  }
93
87
  (0, pubo_utils_1.loop)(async () => {
94
88
  await new Promise((resolve) => {
95
- process.send({ type: 'beat', timestamp: new Date().valueOf() }, resolve);
89
+ process.send({ type: 'beat', timestamp: Date.now() }, resolve);
96
90
  });
97
91
  }, 6000);
98
92
  };
@@ -1,8 +1,8 @@
1
- import { PProcess } from './p-process-type';
1
+ import { PProcess, DiskInfo } from './p-process-type';
2
2
  export declare class PProcessLinux implements PProcess {
3
3
  private _SIGKILL;
4
- getProcessName(pid: any): Promise<string>;
5
- getPidByPort(port: any): Promise<number>;
4
+ getProcessName(pid: number): Promise<string>;
5
+ getPidByPort(port: number): Promise<number>;
6
6
  getProcessCpuUseByPid(pid: number): Promise<number>;
7
7
  getProcessCommandByPid(pid: number): Promise<string>;
8
8
  isProcessDied(pid: number): Promise<boolean>;
@@ -11,7 +11,7 @@ export declare class PProcessLinux implements PProcess {
11
11
  success: boolean;
12
12
  error: string;
13
13
  }>;
14
- getDiskUsage(): Promise<any>;
14
+ getDiskUsage(): Promise<DiskInfo[]>;
15
15
  getAudioCards(filter?: string): Promise<{
16
16
  text: string;
17
17
  index: string;
@@ -16,7 +16,7 @@ class PProcessLinux {
16
16
  timeout: 4000,
17
17
  });
18
18
  }
19
- catch (err) {
19
+ catch {
20
20
  await this._SIGKILL(pid, 9, times + 1);
21
21
  }
22
22
  }
@@ -27,7 +27,7 @@ class PProcessLinux {
27
27
  reject(err);
28
28
  }
29
29
  else {
30
- resolve(data.toString().split(':')[1]?.trim());
30
+ resolve(data.toString().split(':')[1]?.trim() ?? '');
31
31
  }
32
32
  });
33
33
  });
@@ -39,16 +39,13 @@ class PProcessLinux {
39
39
  reject(err);
40
40
  }
41
41
  else {
42
- let res = stdout.split('\n')[1];
43
- if (res) {
44
- res = res.trim();
45
- }
46
- res = parseInt(res);
47
- if (isNaN(res)) {
48
- reject('process not found');
42
+ const res = stdout.split('\n')[1]?.trim();
43
+ const pid = parseInt(res ?? '', 10);
44
+ if (isNaN(pid)) {
45
+ reject(new Error('process not found'));
49
46
  return;
50
47
  }
51
- resolve(res);
48
+ resolve(pid);
52
49
  }
53
50
  });
54
51
  });
@@ -72,7 +69,7 @@ class PProcessLinux {
72
69
  resolve('');
73
70
  }
74
71
  else {
75
- resolve(stdout.toString().split('\n')[0]);
72
+ resolve(stdout.toString().split('\n')[0] ?? '');
76
73
  }
77
74
  });
78
75
  });
@@ -83,18 +80,17 @@ class PProcessLinux {
83
80
  }
84
81
  getProcessByPpid(pid) {
85
82
  return new Promise((resolve) => {
86
- let child = (0, child_process_1.exec)(`ps -o pid --no-headers --ppid ${pid}`, (err, stdout) => {
83
+ (0, child_process_1.exec)(`ps -o pid --no-headers --ppid ${pid}`, (err, stdout) => {
87
84
  if (err) {
88
85
  resolve([]);
89
- child = null;
90
86
  }
91
87
  else {
92
- resolve(stdout
88
+ const pidList = stdout
93
89
  .split('\n')
94
90
  .filter((item) => !!item)
95
91
  .map((item) => parseFloat(item.trim()))
96
- .filter((item) => item !== child.pid));
97
- child = null;
92
+ .filter((item) => !isNaN(item));
93
+ resolve(pidList);
98
94
  }
99
95
  });
100
96
  });
@@ -107,7 +103,7 @@ class PProcessLinux {
107
103
  await this._SIGKILL(item, signal, times);
108
104
  }
109
105
  catch (err) {
110
- res.error = err;
106
+ res.error = String(err);
111
107
  res.success = false;
112
108
  }
113
109
  }
@@ -120,7 +116,7 @@ class PProcessLinux {
120
116
  resolve([]);
121
117
  }
122
118
  else {
123
- resolve(parser(stdout.toString()));
119
+ resolve(parseDiskUsage(stdout.toString()));
124
120
  }
125
121
  });
126
122
  });
@@ -145,26 +141,36 @@ class PProcessLinux {
145
141
  }
146
142
  exports.PProcessLinux = PProcessLinux;
147
143
  const parseAudioCard = (v) => {
148
- let card = /card \d/.exec(v) ?? ['card 1'];
149
- card = parseInt(card[0].replace('card ', ''), 10);
150
- let device = /device \d/.exec(v) ?? ['device 0'];
151
- device = parseInt(device[0].replace('device ', ''), 10);
144
+ const cardMatch = /card (\d+)/.exec(v) ?? ['card 1', '1'];
145
+ const deviceMatch = /device (\d+)/.exec(v) ?? ['device 0', '0'];
146
+ const card = parseInt(cardMatch[1], 10);
147
+ const device = parseInt(deviceMatch[1], 10);
152
148
  return { text: v, index: `hw:${card},${device}` };
153
149
  };
154
- const dic = ['fileSystem', 'size', 'used', 'avail', 'usedPercent', 'mounted'];
155
- const parser = (str) => {
150
+ const parseDiskUsage = (str) => {
151
+ const keys = ['fileSystem', 'size', 'used', 'avail', 'usePercent', 'mounted'];
156
152
  return str
157
153
  .split('\n')
158
154
  .filter((item) => item)
159
- .map((item) => item.split(' ').filter((s) => !!s))
160
155
  .map((item) => {
161
- const res = {};
162
- dic.forEach((key, i) => (res[key] = item[i]));
163
- return res;
164
- })
165
- .map((item) => ({
166
- ...item,
167
- total: parseFloat(item.size),
168
- percentage: parseFloat(item['use%']),
169
- }));
156
+ const values = item.split(' ').filter((s) => !!s);
157
+ const raw = {
158
+ fileSystem: values[0] ?? '',
159
+ size: values[1] ?? '',
160
+ used: values[2] ?? '',
161
+ avail: values[3] ?? '',
162
+ usePercent: values[4] ?? '',
163
+ mounted: values[5] ?? '',
164
+ };
165
+ return {
166
+ fileSystem: raw.fileSystem,
167
+ size: parseFloat(raw.size),
168
+ used: parseFloat(raw.used),
169
+ avail: parseFloat(raw.avail),
170
+ usedPercent: parseFloat(raw.usePercent.replace('%', '')),
171
+ mounted: raw.mounted,
172
+ total: parseFloat(raw.size),
173
+ percentage: parseFloat(raw.usePercent.replace('%', '')),
174
+ };
175
+ });
170
176
  };
@@ -1,6 +1,6 @@
1
1
  export interface PidTree {
2
2
  pid: number;
3
- children: PidTree;
3
+ children: PidTree[];
4
4
  }
5
5
  export interface DiskInfo {
6
6
  fileSystem: string;
@@ -8,7 +8,9 @@ export interface DiskInfo {
8
8
  used: number;
9
9
  avail: number;
10
10
  usedPercent: number;
11
- mounted: number;
11
+ mounted: string;
12
+ total?: number;
13
+ percentage?: number;
12
14
  }
13
15
  export interface PProcess {
14
16
  getProcessName(pid: number): Promise<string>;
@@ -1,15 +1,18 @@
1
- import { PProcess } from './p-process-type';
1
+ import { PProcess, DiskInfo } from './p-process-type';
2
2
  export declare class PProcessWin32 implements PProcess {
3
- getProcessName(pid: any): Promise<string>;
4
- getPidByPort(port: any): Promise<number>;
3
+ getProcessName(pid: number): Promise<string>;
4
+ getPidByPort(port: number): Promise<number>;
5
5
  getProcessCpuUseByPid(pid: number): Promise<number>;
6
6
  getProcessCommandByPid(pid: number): Promise<string>;
7
7
  isProcessDied(pid: number): Promise<boolean>;
8
8
  getProcessByPpid(ppid: number): Promise<number[]>;
9
- SIGKILL(pid: number, signal?: number, times?: number): Promise<{
9
+ SIGKILL(pid: number): Promise<{
10
10
  success: boolean;
11
11
  error: string;
12
12
  }>;
13
- getDiskUsage(): Promise<any>;
14
- getAudioCards(): Promise<never[]>;
13
+ getDiskUsage(): Promise<DiskInfo[]>;
14
+ getAudioCards(): Promise<{
15
+ text: string;
16
+ index: string;
17
+ }[]>;
15
18
  }
@@ -16,7 +16,7 @@ class PProcessWin32 {
16
16
  resolve(match[1]);
17
17
  }
18
18
  else {
19
- reject('process not found');
19
+ reject(new Error('process not found'));
20
20
  }
21
21
  }
22
22
  });
@@ -31,17 +31,17 @@ class PProcessWin32 {
31
31
  }
32
32
  const arr = stdout.split('\n');
33
33
  if (!arr[0]) {
34
- reject('process not found');
34
+ reject(new Error('process not found'));
35
35
  return;
36
36
  }
37
37
  const tmp = arr[0].split(' ');
38
- let res = tmp.pop();
39
- res = parseInt(res);
40
- if (isNaN(res)) {
41
- reject('process not found');
38
+ const res = tmp.pop();
39
+ const pid = parseInt(res ?? '', 10);
40
+ if (isNaN(pid)) {
41
+ reject(new Error('process not found'));
42
42
  return;
43
43
  }
44
- resolve(res);
44
+ resolve(pid);
45
45
  });
46
46
  });
47
47
  }
@@ -54,10 +54,10 @@ class PProcessWin32 {
54
54
  }
55
55
  const match = stdout.match(/\d+\s+(\d+)/);
56
56
  if (!match) {
57
- reject('Process not found');
57
+ reject(new Error('Process not found'));
58
58
  return;
59
59
  }
60
- resolve(parseInt(match[1]));
60
+ resolve(parseInt(match[1], 10));
61
61
  });
62
62
  });
63
63
  }
@@ -70,7 +70,7 @@ class PProcessWin32 {
70
70
  }
71
71
  const match = stdout.match(/CommandLine=(.*)/);
72
72
  if (!match) {
73
- reject('Process not found');
73
+ reject(new Error('Process not found'));
74
74
  return;
75
75
  }
76
76
  resolve(match[1].trim());
@@ -93,7 +93,7 @@ class PProcessWin32 {
93
93
  for (const line of lines) {
94
94
  const match = line.match(/ProcessId=(\d+)/);
95
95
  if (match) {
96
- const pid = parseInt(match[1]);
96
+ const pid = parseInt(match[1], 10);
97
97
  if (!isNaN(pid)) {
98
98
  pids.push(pid);
99
99
  }
@@ -103,10 +103,10 @@ class PProcessWin32 {
103
103
  });
104
104
  });
105
105
  }
106
- async SIGKILL(pid, signal, times) {
106
+ async SIGKILL(pid) {
107
107
  return new Promise((resolve) => {
108
108
  (0, child_process_1.exec)(`taskkill /pid ${pid} /T /F`, (err) => {
109
- resolve({ success: true, error: err.toString() });
109
+ resolve({ success: true, error: err?.toString() ?? '' });
110
110
  });
111
111
  });
112
112
  }
@@ -118,36 +118,32 @@ class PProcessWin32 {
118
118
  return;
119
119
  }
120
120
  const lines = stdout.split('\r\n').filter((line) => line.trim() !== '');
121
- // format:csv output has a header line "Node,Caption,FreeSpace,Size" usually.
122
- // It might also have empty lines.
123
121
  const disks = lines
124
122
  .map((line) => {
125
- // CSV parsing: simple split by comma
126
123
  const parts = line.split(',').map((s) => s.trim());
127
124
  if (parts.length < 4)
128
- return null; // Node, Caption, FreeSpace, Size
129
- // Header check
125
+ return null;
130
126
  if (parts[1] === 'Caption')
131
127
  return null;
132
128
  const caption = parts[1];
133
- const freeSpace = parseInt(parts[2]);
134
- const size = parseInt(parts[3]);
129
+ const freeSpace = parseInt(parts[2], 10);
130
+ const size = parseInt(parts[3], 10);
135
131
  if (isNaN(size) || isNaN(freeSpace))
136
132
  return null;
137
133
  const used = size - freeSpace;
138
134
  const usedPercent = size > 0 ? (used / size) * 100 : 0;
139
135
  return {
140
136
  fileSystem: caption,
141
- size: size, // bytes
142
- used: used,
137
+ size,
138
+ used,
143
139
  avail: freeSpace,
144
- usedPercent: `${usedPercent.toFixed(0)}%`,
140
+ usedPercent: usedPercent,
145
141
  mounted: caption,
146
142
  total: size,
147
- percentage: parseFloat(usedPercent.toFixed(0)),
143
+ percentage: Math.round(usedPercent),
148
144
  };
149
145
  })
150
- .filter((item) => item);
146
+ .filter((item) => item !== null);
151
147
  resolve(disks);
152
148
  });
153
149
  });
@@ -11,7 +11,17 @@ export interface FtpConnectOptions {
11
11
  user: string;
12
12
  host: string;
13
13
  password: string;
14
- driver: any;
14
+ driver: new () => FtpDriver;
15
+ }
16
+ interface FtpDriver {
17
+ once(event: 'ready' | 'error', listener: (err?: Error) => void): this;
18
+ connect(options: Record<string, string>): this;
19
+ end(): void;
20
+ get(path: string, callback: (err: Error | null, stream: NodeJS.ReadableStream) => void): void;
21
+ put(input: string | Buffer | Stream, path: string, callback: (err: Error | null, result: string) => void): void;
22
+ delete(path: string, callback: (err: Error | null, result: string) => void): void;
23
+ list(path: string, callback: (err: Error | null, list: FtpFile[]) => void): void;
24
+ rename(oldPath: string, newPath: string, callback: (err: Error | null, result: string) => void): void;
15
25
  }
16
26
  type GetFile = (path: string) => Promise<Buffer>;
17
27
  type PutFile = (input: string | Buffer | Stream, path: string) => Promise<string>;
@@ -31,19 +41,19 @@ export declare class FtpClient implements FtpClientInterface {
31
41
  private readonly state;
32
42
  private client;
33
43
  private _len;
34
- id: string;
44
+ readonly id: string;
35
45
  constructor({ driver, ...options }: FtpConnectOptions);
36
46
  get len(): number;
37
47
  set len(n: number);
38
- put: (...args: any[]) => Promise<any>;
39
- delete: (...args: any[]) => Promise<any>;
40
- list: (...args: any[]) => Promise<any>;
41
- rename: (...args: any[]) => Promise<any>;
48
+ put: PutFile;
49
+ delete: DeleteFile;
50
+ list: ListFiles;
51
+ rename: RenameFile;
42
52
  private connect;
43
53
  private close;
44
54
  private run;
45
55
  private bind;
46
- get(...args: any[]): Promise<Buffer>;
56
+ get(path: string): Promise<Buffer>;
47
57
  }
48
58
  export declare class FtpClientPool implements FtpClientInterface {
49
59
  private readonly options;
@@ -52,11 +62,11 @@ export declare class FtpClientPool implements FtpClientInterface {
52
62
  constructor({ maxConnection, ...options }: {
53
63
  maxConnection?: number;
54
64
  } & FtpConnectOptions);
55
- get: (...args: any[]) => Promise<any>;
56
- put: (...args: any[]) => Promise<any>;
57
- delete: (...args: any[]) => Promise<any>;
58
- list: (...args: any[]) => Promise<any>;
59
- rename: (...args: any[]) => Promise<any>;
65
+ get: GetFile;
66
+ put: PutFile;
67
+ delete: DeleteFile;
68
+ list: ListFiles;
69
+ rename: RenameFile;
60
70
  get len(): number;
61
71
  private get client();
62
72
  private bind;
@@ -6,7 +6,7 @@ class FtpClient {
6
6
  driver;
7
7
  options;
8
8
  state = { running: false, connected: false, destroyed: false, connecting: false };
9
- client;
9
+ client = null;
10
10
  _len = 0;
11
11
  id = (0, pubo_utils_1.random)();
12
12
  constructor({ driver, ...options }) {
@@ -46,11 +46,11 @@ class FtpClient {
46
46
  reject(err);
47
47
  this.close();
48
48
  });
49
- this.client.connect({ ...this.options });
49
+ this.client.connect(this.options);
50
50
  });
51
51
  }
52
52
  close() {
53
- this.client.end();
53
+ this.client?.end();
54
54
  this.state.connected = false;
55
55
  this.state.destroyed = true;
56
56
  this.state.connecting = false;
@@ -84,11 +84,12 @@ class FtpClient {
84
84
  return res;
85
85
  };
86
86
  }
87
- async get(...args) {
87
+ async get(path) {
88
88
  let res = Buffer.alloc(0);
89
- const stream = await this.run({ fn: 'get', args });
90
- return new Promise((resolve) => {
89
+ const stream = await this.run({ fn: 'get', args: [path] });
90
+ return new Promise((resolve, reject) => {
91
91
  stream.on('data', (chunk) => {
92
+ // @ts-ignore
92
93
  res = Buffer.concat([res, chunk], res.byteLength + chunk.byteLength);
93
94
  });
94
95
  stream.on('end', () => {
@@ -96,6 +97,7 @@ class FtpClient {
96
97
  this.state.running = false;
97
98
  this.len -= 1;
98
99
  });
100
+ stream.on('error', reject);
99
101
  });
100
102
  }
101
103
  }
@@ -1,10 +1,33 @@
1
- export interface CreateClientProps {
1
+ export interface CreateClientProps<T = unknown> {
2
2
  url: string;
3
- options?: any;
4
- ServiceImp: any;
5
- Grpc: any;
3
+ options?: GrpcClientOptions;
4
+ ServiceImp: new (impl: {
5
+ request: GrpcRequestFn;
6
+ }) => T;
7
+ Grpc: GrpcStatic;
6
8
  cert?: Buffer;
7
9
  }
10
+ interface GrpcClientOptions {
11
+ 'grpc.max_send_message_length'?: number;
12
+ 'grpc.max_receive_message_length'?: number;
13
+ timeout?: number;
14
+ }
15
+ interface GrpcCredentials {
16
+ createSsl(cert?: Buffer): GrpcCredentials;
17
+ createInsecure(): GrpcCredentials;
18
+ }
19
+ interface GrpcClientStatic {
20
+ new (address: string, credentials: GrpcCredentials, options: GrpcClientOptions): GrpcClientInstance;
21
+ }
22
+ interface GrpcClientInstance {
23
+ close(): void;
24
+ makeUnaryRequest(path: string, serialize: (obj: unknown) => Buffer, deserialize: (bytes: Buffer) => unknown, data: Buffer, callback: (err: Error | null, response: Buffer) => void): void;
25
+ }
26
+ type GrpcRequestFn = (service: string, method: string, data?: unknown) => Promise<Buffer>;
27
+ interface GrpcStatic {
28
+ credentials: GrpcCredentials;
29
+ Client: GrpcClientStatic;
30
+ }
8
31
  declare class GrpcClient {
9
32
  private readonly url;
10
33
  private readonly options;
@@ -13,15 +36,16 @@ declare class GrpcClient {
13
36
  private client;
14
37
  private _timeout;
15
38
  connections: number;
16
- constructor({ url, options, Grpc, cert }: any);
17
- request(service: any, method: any, data: any): Promise<Buffer>;
18
- _request({ service, method, data }: {
19
- service: any;
20
- method: any;
21
- data: any;
22
- }): Promise<Buffer>;
39
+ constructor({ url, options, Grpc, cert, }: {
40
+ url: string;
41
+ options?: GrpcClientOptions;
42
+ Grpc: GrpcStatic;
43
+ cert?: Buffer;
44
+ });
45
+ request(service: string, method: string, data?: unknown): Promise<Buffer>;
46
+ private _request;
23
47
  close(): void;
24
48
  }
25
49
  export declare const GrpcList: GrpcClient[];
26
- export declare function createRpcClient<T>({ url, options, ServiceImp, Grpc, cert }: CreateClientProps): T;
50
+ export declare function createRpcClient<T>({ url, options, ServiceImp, Grpc, cert }: CreateClientProps<T>): T;
27
51
  export {};
package/lib/grpc/index.js CHANGED
@@ -8,20 +8,21 @@ class GrpcClient {
8
8
  options;
9
9
  Grpc;
10
10
  credentials;
11
- client;
12
- _timeout;
11
+ client = null;
12
+ _timeout = null;
13
13
  connections = 0;
14
- constructor({ url, options = {}, Grpc, cert }) {
15
- const opt = { 'grpc.max_send_message_length': -1, 'grpc.max_receive_message_length': -1, ...options };
14
+ constructor({ url, options = {}, Grpc, cert, }) {
15
+ const opt = {
16
+ 'grpc.max_send_message_length': -1,
17
+ 'grpc.max_receive_message_length': -1,
18
+ ...options,
19
+ };
16
20
  const credentials = cert ? Grpc.credentials.createSsl(cert) : Grpc.credentials.createInsecure();
17
21
  this.url = url;
18
22
  this.Grpc = Grpc;
19
23
  this.credentials = credentials;
20
24
  this.options = opt;
21
- this.options.timeout = this.options.timeout ?? 10000;
22
- Grpc = null;
23
- options = null;
24
- cert = null;
25
+ this.options.timeout ??= 10000;
25
26
  }
26
27
  async request(service, method, data) {
27
28
  if (this._timeout) {
@@ -32,7 +33,7 @@ class GrpcClient {
32
33
  if (!this.client) {
33
34
  this.client = new this.Grpc.Client(this.url, this.credentials, this.options);
34
35
  }
35
- let error;
36
+ let error = null;
36
37
  let result = Buffer.alloc(0);
37
38
  try {
38
39
  result = await this._request({ service, method, data });
@@ -40,9 +41,6 @@ class GrpcClient {
40
41
  catch (err) {
41
42
  error = err;
42
43
  }
43
- service = null;
44
- method = null;
45
- data = null;
46
44
  this.connections -= 1;
47
45
  if (this.connections < 0) {
48
46
  this.connections = 0;
@@ -50,7 +48,6 @@ class GrpcClient {
50
48
  if (this.connections < 1) {
51
49
  if (this._timeout) {
52
50
  clearTimeout(this._timeout);
53
- this._timeout = null;
54
51
  }
55
52
  this._timeout = setTimeout(() => this.close(), 60000);
56
53
  }
@@ -63,20 +60,18 @@ class GrpcClient {
63
60
  }
64
61
  _request({ service, method, data }) {
65
62
  return new Promise((resolve, reject) => {
66
- let _ended = false;
67
- const _timeout = setTimeout(() => {
68
- _ended = true;
63
+ let ended = false;
64
+ const timeout = setTimeout(() => {
65
+ ended = true;
69
66
  this.close();
70
67
  console.log('rpc request timeout');
71
68
  reject(new Error('timeout'));
72
69
  }, this.options.timeout);
73
70
  const onResponse = (err, res) => {
74
- if (_ended) {
71
+ if (ended) {
75
72
  return;
76
73
  }
77
- else {
78
- clearTimeout(_timeout);
79
- }
74
+ clearTimeout(timeout);
80
75
  if (err) {
81
76
  reject(err);
82
77
  }
@@ -84,24 +79,21 @@ class GrpcClient {
84
79
  resolve(res);
85
80
  }
86
81
  };
87
- this.client.makeUnaryRequest(`/${service}/${method}`, passThrough, passThrough, data ? Buffer.from(data) : Buffer.alloc(0), onResponse);
82
+ this.client.makeUnaryRequest(`/${service}/${method}`, passThrough, passThrough, data ? Buffer.from(JSON.stringify(data)) : Buffer.alloc(0), onResponse);
88
83
  });
89
84
  }
90
85
  close() {
91
86
  if (this._timeout) {
92
87
  clearTimeout(this._timeout);
93
- delete this._timeout;
88
+ this._timeout = null;
94
89
  }
95
90
  this.client?.close();
96
91
  this.client = null;
97
- delete this.client;
98
92
  }
99
93
  }
100
94
  exports.GrpcList = [];
101
- function createRpcClient({ url, options = {}, ServiceImp, Grpc, cert }) {
95
+ function createRpcClient({ url, options, ServiceImp, Grpc, cert }) {
102
96
  const client = new GrpcClient({ url, options, Grpc, cert });
103
97
  exports.GrpcList.push(client);
104
- Grpc = null;
105
- options = null;
106
98
  return new ServiceImp({ request: client.request.bind(client) });
107
99
  }
package/lib/index.d.ts CHANGED
@@ -7,4 +7,3 @@ export { SIGKILL, isProcessDied, getProcessName, getProcessTree, getProcessByPpi
7
7
  export { getWifiName, getNetworks } from './utils/network';
8
8
  export { RosTopicManager, RosTopic } from './ros/topic';
9
9
  export { PProcess } from './child-process/p-process';
10
- export { PuboFileSystem } from './file-system';
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PuboFileSystem = exports.PProcess = exports.RosTopic = exports.RosTopicManager = exports.getNetworks = exports.getWifiName = exports.getDiskUsage = exports.heartbeat = exports.getPidByPort = exports.getProcessList = exports.getProcessCommandByPid = exports.getProcessCpuUseByPid = exports.getProcessByPpid = exports.getProcessTree = exports.getProcessName = exports.isProcessDied = exports.SIGKILL = exports.isPortAvailable = exports.GrpcList = exports.createRpcClient = exports.FtpClientPool = exports.FtpClient = exports.JsonStorage = void 0;
3
+ exports.PProcess = exports.RosTopic = exports.RosTopicManager = exports.getNetworks = exports.getWifiName = exports.getDiskUsage = exports.heartbeat = exports.getPidByPort = exports.getProcessList = exports.getProcessCommandByPid = exports.getProcessCpuUseByPid = exports.getProcessByPpid = exports.getProcessTree = exports.getProcessName = exports.isProcessDied = exports.SIGKILL = exports.isPortAvailable = exports.GrpcList = exports.createRpcClient = exports.FtpClientPool = exports.FtpClient = exports.JsonStorage = void 0;
4
4
  var json_1 = require("./storage/json");
5
5
  Object.defineProperty(exports, "JsonStorage", { enumerable: true, get: function () { return json_1.JsonStorage; } });
6
6
  var ftp_client_1 = require("./ftp-client");
@@ -31,5 +31,3 @@ Object.defineProperty(exports, "RosTopicManager", { enumerable: true, get: funct
31
31
  Object.defineProperty(exports, "RosTopic", { enumerable: true, get: function () { return topic_1.RosTopic; } });
32
32
  var p_process_1 = require("./child-process/p-process");
33
33
  Object.defineProperty(exports, "PProcess", { enumerable: true, get: function () { return p_process_1.PProcess; } });
34
- var file_system_1 = require("./file-system");
35
- Object.defineProperty(exports, "PuboFileSystem", { enumerable: true, get: function () { return file_system_1.PuboFileSystem; } });
@@ -1,20 +1,22 @@
1
1
  import { Emitter } from 'pubo-utils';
2
2
  export declare class RosTopic {
3
- topic: string;
4
- messageType: string;
5
- emitter: Emitter;
3
+ readonly topic: string;
4
+ readonly messageType: string;
5
+ readonly emitter: Emitter;
6
6
  private subscribed;
7
7
  private readonly dog;
8
8
  private readonly strSplit;
9
9
  private subscribeChildProcess;
10
- constructor(topic: any, messageType: any);
10
+ constructor(topic: string, messageType: string);
11
+ get isSubscribed(): boolean;
11
12
  private onTimeout;
12
13
  private onData;
13
14
  subscribe(): Promise<void>;
14
15
  unsubscribe(): Promise<void>;
15
- publish(payload: any): Promise<unknown>;
16
+ publish(payload: unknown): Promise<string>;
16
17
  }
17
- export declare const RosTopicManager: {
18
- cache: never[];
19
- getTopic: (topic: any, messageType: any) => RosTopic;
20
- };
18
+ export interface RosTopicManagerType {
19
+ cache: RosTopic[];
20
+ getTopic(topic: string, messageType: string): RosTopic;
21
+ }
22
+ export declare const RosTopicManager: RosTopicManagerType;
package/lib/ros/topic.js CHANGED
@@ -35,13 +35,16 @@ class RosTopic {
35
35
  subscribed = false;
36
36
  dog = new pubo_utils_1.WatchDog({ limit: 10, onTimeout: this.onTimeout.bind(this) });
37
37
  strSplit = new pubo_utils_1.StringSplit('---');
38
- subscribeChildProcess;
38
+ subscribeChildProcess = null;
39
39
  constructor(topic, messageType) {
40
40
  this.topic = topic;
41
41
  this.messageType = messageType;
42
42
  this.subscribed = false;
43
43
  this.emitter = new pubo_utils_1.Emitter();
44
44
  }
45
+ get isSubscribed() {
46
+ return this.subscribed;
47
+ }
45
48
  async onTimeout() {
46
49
  await this.unsubscribe();
47
50
  await (0, pubo_utils_1.sleep)(1000);
@@ -62,9 +65,9 @@ class RosTopic {
62
65
  }
63
66
  this.subscribed = true;
64
67
  this.dog.init();
65
- this.subscribeChildProcess = (0, child_process_1.spawn)(`rostopic`, ['echo', this.topic]);
66
- this.subscribeChildProcess.stdout.on('data', this.onData.bind(this));
67
- this.subscribeChildProcess.stderr.on('data', (buf) => console.log(buf.toString()));
68
+ this.subscribeChildProcess = (0, child_process_1.spawn)('rostopic', ['echo', this.topic]);
69
+ this.subscribeChildProcess.stdout?.on('data', this.onData.bind(this));
70
+ this.subscribeChildProcess.stderr?.on('data', (buf) => console.log(buf.toString()));
68
71
  }
69
72
  async unsubscribe() {
70
73
  if (!this.subscribeChildProcess) {
@@ -92,7 +95,7 @@ class RosTopic {
92
95
  exports.RosTopic = RosTopic;
93
96
  exports.RosTopicManager = {
94
97
  cache: [],
95
- getTopic: function (topic, messageType) {
98
+ getTopic(topic, messageType) {
96
99
  const tmp = this.cache.find((item) => item.topic === topic);
97
100
  if (tmp) {
98
101
  return tmp;
@@ -1,6 +1,6 @@
1
1
  export interface JsonStorageOptions {
2
- initialState?: any;
3
- defaultState?: any;
2
+ initialState?: Record<string, unknown>;
3
+ defaultState?: Record<string, unknown>;
4
4
  }
5
5
  export declare class JsonStorage {
6
6
  private readonly instance;
@@ -8,8 +8,8 @@ export declare class JsonStorage {
8
8
  constructor(path: string, options?: JsonStorageOptions);
9
9
  private getState;
10
10
  private setState;
11
- get(key?: string): Promise<any>;
12
- set(key: string, values: any): Promise<void>;
13
- merge(values: any): Promise<void>;
11
+ get(key?: string): Promise<unknown>;
12
+ set(key: string, values: unknown): Promise<void>;
13
+ merge(values: Record<string, unknown>): Promise<void>;
14
14
  remove(key: string): Promise<void>;
15
15
  }
@@ -4,8 +4,6 @@ exports.JsonStorage = void 0;
4
4
  const fs_1 = require("fs");
5
5
  const pubo_utils_1 = require("pubo-utils");
6
6
  const uuid_1 = require("uuid");
7
- // eslint-disable-next-line @typescript-eslint/no-var-requires
8
- const cluster = require('cluster');
9
7
  // 主线程的实现
10
8
  class Manager {
11
9
  path;
@@ -13,20 +11,20 @@ class Manager {
13
11
  queue = new pubo_utils_1.SyncQueue();
14
12
  key;
15
13
  defaultState;
16
- constructor(path, defaultState) {
14
+ constructor(path, defaultState, clusterModule) {
17
15
  this.path = path;
18
16
  this.defaultState = defaultState;
19
17
  this.key = encodeURIComponent(path);
20
- cluster.on('online', (worker) => {
21
- worker.on('message', (message) => {
22
- this.onMessage(message, worker);
23
- message = null;
18
+ if (clusterModule) {
19
+ clusterModule.on('online', (worker) => {
20
+ worker.on('message', (message) => {
21
+ this.onMessage(message, worker);
22
+ });
24
23
  });
25
- });
26
- cluster.on('exit', (worker) => {
27
- worker.removeAllListeners('message');
28
- worker = null;
29
- });
24
+ clusterModule.on('exit', (worker) => {
25
+ worker.removeAllListeners('message');
26
+ });
27
+ }
30
28
  this.restore();
31
29
  if (global.GlobalEmitter) {
32
30
  global.GlobalEmitter.on('SIGINT', this.kill.bind(this));
@@ -49,12 +47,10 @@ class Manager {
49
47
  if (message.type === 'get') {
50
48
  payload = await this.getState();
51
49
  }
52
- else if (message.type === 'set') {
50
+ else if (message.type === 'set' && message.payload) {
53
51
  payload = await this.setState(message.payload);
54
52
  }
55
53
  worker.send({ uid: message.uid, key: this.key, payload });
56
- message = null;
57
- worker = null;
58
54
  }
59
55
  sync() {
60
56
  if (this.queue.length > 0) {
@@ -84,9 +80,9 @@ class Manager {
84
80
  const buf = (0, fs_1.readFileSync)(this.path);
85
81
  this._state = JSON.parse(buf.toString());
86
82
  }
87
- catch (err) {
88
- const str = process.platform === 'win32' ? '\\' : '/';
89
- const folder = this.path.split(str).slice(0, -1).join(str);
83
+ catch {
84
+ const separator = process.platform === 'win32' ? '\\' : '/';
85
+ const folder = this.path.split(separator).slice(0, -1).join(separator);
90
86
  if (folder) {
91
87
  (0, fs_1.mkdirSync)(folder, { recursive: true });
92
88
  }
@@ -113,35 +109,33 @@ class Worker {
113
109
  if (message.key !== this.key) {
114
110
  return;
115
111
  }
116
- if (typeof this.callback[message.uid] === 'function') {
112
+ if (message.uid && typeof this.callback[message.uid] === 'function') {
117
113
  this.callback[message.uid](message.payload);
118
114
  delete this.callback[message.uid];
119
115
  }
120
- message = null;
121
116
  }
122
117
  async call({ type, payload }) {
123
118
  return new Promise((resolve) => {
124
119
  const uid = (0, uuid_1.v4)();
125
120
  this.callback[uid] = (data) => resolve(data);
126
- //@ts-ignore
127
121
  process.send({ uid, type, payload, key: this.key });
128
- payload = null;
129
- type = null;
130
122
  });
131
123
  }
132
124
  async getState() {
133
- return this.call({ type: 'get', payload: {} });
125
+ return (await this.call({ type: 'get', payload: {} }));
134
126
  }
135
127
  async setState(payload) {
136
- return this.call({ type: 'set', payload });
128
+ await this.call({ type: 'set', payload });
137
129
  }
138
130
  }
139
131
  class JsonStorage {
140
132
  instance;
141
133
  queue = new pubo_utils_1.SyncQueue();
142
134
  constructor(path, options = {}) {
143
- if (cluster.isPrimary) {
144
- this.instance = new Manager(path, options.defaultState);
135
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
136
+ const clusterModule = require('cluster');
137
+ if (clusterModule.isPrimary) {
138
+ this.instance = new Manager(path, options.defaultState, clusterModule);
145
139
  }
146
140
  else {
147
141
  this.instance = new Worker(path);
@@ -160,10 +154,8 @@ class JsonStorage {
160
154
  if (!key) {
161
155
  return this.getState();
162
156
  }
163
- else {
164
- const state = await this.getState();
165
- return state[key];
166
- }
157
+ const state = await this.getState();
158
+ return state[key];
167
159
  }
168
160
  async set(key, values) {
169
161
  const state = await this.getState();
@@ -1 +1 @@
1
- export declare const isPortAvailable: (port: any) => Promise<unknown>;
1
+ export declare const isPortAvailable: (port: number) => Promise<boolean>;
@@ -1,2 +1,8 @@
1
- export declare function getNetworks(): Promise<any[]>;
2
- export declare function getWifiName(): Promise<any>;
1
+ interface NetworkInfo {
2
+ description?: string;
3
+ 'logical name'?: string;
4
+ [key: string]: string | undefined;
5
+ }
6
+ export declare function getNetworks(): Promise<NetworkInfo[]>;
7
+ export declare function getWifiName(): Promise<string>;
8
+ export {};
@@ -27,6 +27,9 @@ async function getNetworks() {
27
27
  child.stdout?.on('data', (data) => {
28
28
  resolve(parseNetworkData(data));
29
29
  });
30
+ child.on('error', () => {
31
+ resolve([]);
32
+ });
30
33
  });
31
34
  }
32
35
  async function getWifiName() {
@@ -35,5 +38,5 @@ async function getWifiName() {
35
38
  if (!wifi) {
36
39
  return '';
37
40
  }
38
- return wifi['logical name'];
41
+ return wifi['logical name'] ?? '';
39
42
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pubo-node",
3
- "version": "1.0.206",
3
+ "version": "1.0.207",
4
4
  "main": "./lib/index.js",
5
5
  "types": "./lib/index.d.ts",
6
6
  "sideEffects": false,
@@ -18,10 +18,10 @@
18
18
  },
19
19
  "dependencies": {
20
20
  "@types/node": "^17.0.25",
21
- "pubo-utils": "^1.0.206",
21
+ "pubo-utils": "^1.0.207",
22
22
  "yaml": "^2.5.1"
23
23
  },
24
- "gitHead": "f26d7016b8a957cfab489dc831cf3052db2f87ea",
24
+ "gitHead": "f785821fb5a3ec8f9c7db2c3b818108dc9139ea2",
25
25
  "devDependencies": {
26
26
  "del": "^5.1.0",
27
27
  "eslint": "^8.42.0",
@@ -1,22 +0,0 @@
1
- import type EventEmitter from 'events';
2
- import * as fs from 'fs';
3
- interface PuboFileSystemInterface {
4
- read: <TBuffer extends NodeJS.ArrayBufferView>(fd: number, buffer?: TBuffer, offset?: number, length?: number, position?: fs.ReadPosition | null) => Promise<[number, TBuffer]>;
5
- stat: (path: fs.PathLike) => Promise<fs.Stats>;
6
- readFile: (path: fs.PathOrFileDescriptor, options?: ({
7
- encoding?: null;
8
- flag?: string;
9
- } & EventEmitter.Abortable) | null) => Promise<Buffer>;
10
- writeFile: (file: fs.PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: fs.WriteFileOptions) => Promise<void>;
11
- readdir: (path: fs.PathLike, options?: BufferEncoding | {
12
- encoding: BufferEncoding | null;
13
- withFileTypes: false;
14
- } | null) => Promise<string[]>;
15
- open: (path: fs.PathLike, flags?: fs.OpenMode, mode?: fs.Mode | null) => Promise<number>;
16
- close: (fd: number) => Promise<void>;
17
- mkdir: (path: fs.PathLike, options?: fs.MakeDirectoryOptions) => Promise<void>;
18
- rm: (path: fs.PathLike) => Promise<void>;
19
- write: <TBuffer extends NodeJS.ArrayBufferView>(fd: number, buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null) => Promise<void>;
20
- }
21
- export declare const PuboFileSystem: PuboFileSystemInterface;
22
- export {};
@@ -1,54 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.PuboFileSystem = void 0;
27
- const fs = __importStar(require("fs"));
28
- const callback2promise = (fn) => {
29
- return (...args) => new Promise((resolve, reject) => {
30
- fn(...args, (err, ...rest) => {
31
- if (err) {
32
- reject(err);
33
- }
34
- if (rest.length < 2) {
35
- resolve(rest[0]);
36
- }
37
- else {
38
- resolve([...rest]);
39
- }
40
- });
41
- });
42
- };
43
- exports.PuboFileSystem = {
44
- read: callback2promise(fs.read),
45
- readFile: callback2promise(fs.readFile),
46
- writeFile: callback2promise(fs.writeFile),
47
- readdir: callback2promise(fs.readdir),
48
- open: callback2promise(fs.open),
49
- close: callback2promise(fs.close),
50
- write: callback2promise(fs.write),
51
- stat: callback2promise(fs.stat),
52
- mkdir: callback2promise(fs.mkdir),
53
- rm: callback2promise(fs.rm),
54
- };