camstreamerlib 3.0.0 → 3.1.0

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,4 +1,5 @@
1
- import { Options } from './internal/common';
1
+ /// <reference types="node" />
2
+ import { IClient, Options } from './internal/common';
2
3
  export type CamOverlayOptions = Options;
3
4
  export type TField = {
4
5
  field_name: string;
@@ -21,13 +22,8 @@ export declare enum ImageType {
21
22
  JPEG = 1
22
23
  }
23
24
  export declare class CamOverlayAPI {
24
- private tls;
25
- private tlsInsecure;
26
- private ip;
27
- private port;
28
- private user;
29
- private pass;
30
- constructor(options?: CamOverlayOptions);
25
+ private client;
26
+ constructor(options?: CamOverlayOptions | IClient);
31
27
  updateCGText(serviceID: number, fields: TField[]): Promise<void>;
32
28
  updateCGImagePos(serviceID: number, coordinates?: string, x?: number, y?: number): Promise<void>;
33
29
  updateCGImage(serviceID: number, path: string, coordinates?: string, x?: number, y?: number): Promise<void>;
@@ -38,5 +34,4 @@ export declare class CamOverlayAPI {
38
34
  updateCGImageFromData(serviceID: number, imageType: ImageType, imageData: Buffer, coordinates?: string, x?: number, y?: number): Promise<void>;
39
35
  promiseCGUpdate(serviceID: number, action: string, params: string, contentType?: string, data?: Buffer): Promise<void>;
40
36
  private formCoordinates;
41
- private getBaseVapixConnectionParams;
42
37
  }
package/CamOverlayAPI.js CHANGED
@@ -10,21 +10,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.CamOverlayAPI = exports.ImageType = void 0;
13
- const HttpRequest_1 = require("./internal/HttpRequest");
13
+ const common_1 = require("./internal/common");
14
+ const DefaultAgent_1 = require("./DefaultAgent");
14
15
  var ImageType;
15
16
  (function (ImageType) {
16
17
  ImageType[ImageType["PNG"] = 0] = "PNG";
17
18
  ImageType[ImageType["JPEG"] = 1] = "JPEG";
18
19
  })(ImageType || (exports.ImageType = ImageType = {}));
19
20
  class CamOverlayAPI {
20
- constructor(options) {
21
- var _a, _b, _c, _d, _e, _f;
22
- this.tls = (_a = options === null || options === void 0 ? void 0 : options.tls) !== null && _a !== void 0 ? _a : false;
23
- this.tlsInsecure = (_b = options === null || options === void 0 ? void 0 : options.tlsInsecure) !== null && _b !== void 0 ? _b : false;
24
- this.ip = (_c = options === null || options === void 0 ? void 0 : options.ip) !== null && _c !== void 0 ? _c : '127.0.0.1';
25
- this.port = (_d = options === null || options === void 0 ? void 0 : options.port) !== null && _d !== void 0 ? _d : (this.tls ? 443 : 80);
26
- this.user = (_e = options === null || options === void 0 ? void 0 : options.user) !== null && _e !== void 0 ? _e : '';
27
- this.pass = (_f = options === null || options === void 0 ? void 0 : options.pass) !== null && _f !== void 0 ? _f : '';
21
+ constructor(options = {}) {
22
+ if ((0, common_1.isClient)(options)) {
23
+ this.client = options;
24
+ }
25
+ else {
26
+ this.client = new DefaultAgent_1.DefaultAgent(options);
27
+ }
28
28
  }
29
29
  updateCGText(serviceID, fields) {
30
30
  let field_specs = '';
@@ -49,8 +49,7 @@ class CamOverlayAPI {
49
49
  updateInfoticker(serviceID, text) {
50
50
  return __awaiter(this, void 0, void 0, function* () {
51
51
  const path = `/local/camoverlay/api/infoticker.cgi?service_id=${serviceID}&text=${text}`;
52
- const options = this.getBaseVapixConnectionParams(path);
53
- const res = yield (0, HttpRequest_1.sendRequest)(options);
52
+ const res = yield this.client.get(path);
54
53
  if (!res.ok) {
55
54
  throw new Error(JSON.stringify(res));
56
55
  }
@@ -59,8 +58,7 @@ class CamOverlayAPI {
59
58
  setEnabled(serviceID, enabled) {
60
59
  return __awaiter(this, void 0, void 0, function* () {
61
60
  const path = `/local/camoverlay/api/enabled.cgi?id_${serviceID}=${enabled ? 1 : 0}`;
62
- const options = this.getBaseVapixConnectionParams(path, 'POST');
63
- const res = yield (0, HttpRequest_1.sendRequest)(options);
61
+ const res = yield this.client.post(path, '');
64
62
  if (!res.ok) {
65
63
  throw new Error(JSON.stringify(res));
66
64
  }
@@ -69,8 +67,7 @@ class CamOverlayAPI {
69
67
  isEnabled(serviceID) {
70
68
  return __awaiter(this, void 0, void 0, function* () {
71
69
  const path = '/local/camoverlay/api/services.cgi?action=get';
72
- const options = this.getBaseVapixConnectionParams(path);
73
- const res = yield (0, HttpRequest_1.sendRequest)(options);
70
+ const res = yield this.client.get(path);
74
71
  if (res.ok) {
75
72
  const data = JSON.parse(yield res.text());
76
73
  for (const service of data.services) {
@@ -88,8 +85,7 @@ class CamOverlayAPI {
88
85
  updateServices(servicesJson) {
89
86
  return __awaiter(this, void 0, void 0, function* () {
90
87
  const path = '/local/camoverlay/api/services.cgi?action=set';
91
- const options = this.getBaseVapixConnectionParams(path, 'POST');
92
- const res = yield (0, HttpRequest_1.sendRequest)(options, JSON.stringify(servicesJson));
88
+ const res = yield this.client.post(path, JSON.stringify(servicesJson));
93
89
  if (!res.ok) {
94
90
  throw new Error(JSON.stringify(res));
95
91
  }
@@ -103,11 +99,11 @@ class CamOverlayAPI {
103
99
  promiseCGUpdate(serviceID, action, params, contentType, data) {
104
100
  return __awaiter(this, void 0, void 0, function* () {
105
101
  const path = `/local/camoverlay/api/customGraphics.cgi?action=${action}&service_id=${serviceID}${params}`;
106
- const options = this.getBaseVapixConnectionParams(path, 'POST');
102
+ let headers = {};
107
103
  if (contentType !== undefined && data) {
108
- options.headers = { 'Content-Type': contentType };
104
+ headers = { 'Content-Type': contentType };
109
105
  }
110
- const res = yield (0, HttpRequest_1.sendRequest)(options, data);
106
+ const res = yield this.client.post(path, data !== null && data !== void 0 ? data : '', {}, headers);
111
107
  if (!res.ok) {
112
108
  throw new Error(JSON.stringify(res));
113
109
  }
@@ -116,17 +112,5 @@ class CamOverlayAPI {
116
112
  formCoordinates(coordinates, x, y) {
117
113
  return coordinates !== '' ? `&coord_system=${coordinates}&pos_x=${x}&pos_y=${y}` : '';
118
114
  }
119
- getBaseVapixConnectionParams(path, method = 'GET') {
120
- return {
121
- method: method,
122
- protocol: this.tls ? 'https:' : 'http:',
123
- host: this.ip,
124
- port: this.port,
125
- path: path,
126
- user: this.user,
127
- pass: this.pass,
128
- rejectUnauthorized: !this.tlsInsecure,
129
- };
130
- }
131
115
  }
132
116
  exports.CamOverlayAPI = CamOverlayAPI;
@@ -1,3 +1,5 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  import * as EventEmitter from 'events';
2
4
  import { Options } from './internal/common';
3
5
  export type CamOverlayDrawingOptions = Options & {
@@ -136,9 +136,11 @@ class CamOverlayDrawingAPI extends EventEmitter {
136
136
  if (this.connected) {
137
137
  try {
138
138
  yield (0, promises_1.setTimeout)(10000);
139
- void this.openWebsocket();
139
+ yield this.openWebsocket();
140
+ resolve();
140
141
  }
141
142
  catch (err) {
143
+ reject(err);
142
144
  }
143
145
  }
144
146
  }));
@@ -156,7 +158,8 @@ class CamOverlayDrawingAPI extends EventEmitter {
156
158
  this.ws.send(JSON.stringify(msgJson));
157
159
  }
158
160
  catch (err) {
159
- this.reportError(new Error(`Send message error: ${err}`));
161
+ const errorMessage = (err instanceof Error) ? err.message : err;
162
+ this.reportError(new Error(`Send message error: ${errorMessage}`));
160
163
  }
161
164
  });
162
165
  }
@@ -177,7 +180,8 @@ class CamOverlayDrawingAPI extends EventEmitter {
177
180
  this.ws.send(msgBuffer);
178
181
  }
179
182
  catch (err) {
180
- this.reportError(new Error(`Send binary message error: ${err}`));
183
+ const errorMessage = (err instanceof Error) ? err.message : err;
184
+ this.reportError(new Error(`Send binary message error: ${errorMessage}`));
181
185
  }
182
186
  });
183
187
  }
@@ -78,8 +78,8 @@ class Frame {
78
78
  disable() {
79
79
  this.enabled = false;
80
80
  }
81
- displayImage(cod_1, rm_1, cairo_1, ppX_1, ppY_1) {
82
- return __awaiter(this, arguments, void 0, function* (cod, rm, cairo, ppX, ppY, scale = 1) {
81
+ displayImage(cod, rm, cairo, ppX, ppY, scale = 1) {
82
+ return __awaiter(this, void 0, void 0, function* () {
83
83
  if (this.enabled) {
84
84
  ppX += this.posX;
85
85
  ppY += this.posY;
@@ -65,8 +65,8 @@ class Painter extends Frame_1.Frame {
65
65
  setCoAlignment(coa) {
66
66
  this.coAlignment = exports.COORD[coa];
67
67
  }
68
- display() {
69
- return __awaiter(this, arguments, void 0, function* (scale = 1) {
68
+ display(scale = 1) {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
70
  if (this.enabled) {
71
71
  [this.surface, this.cairo] = yield this.prepareDrawing(scale);
72
72
  yield this.displayOwnImage(this.cod, this.rm, this.cairo, 0, 0, scale);
@@ -1,3 +1,4 @@
1
+ /// <reference types="node" />
1
2
  import * as EventEmitter from 'events';
2
3
  import { Options } from './internal/common';
3
4
  export type CamScripterOptions = Options;
@@ -1,17 +1,35 @@
1
- import { Options } from './internal/common';
1
+ import { Options, IClient } from './internal/common';
2
2
  export type CamStreamerAPIOptions = Options;
3
+ export type TStreamAttributes = {
4
+ enabled: string;
5
+ active: string;
6
+ audioSource: string;
7
+ avSyncMsec: string;
8
+ internalVapixParameters: string;
9
+ userVapixParameters: string;
10
+ outputParameters: string;
11
+ outputType: string;
12
+ mediaServerUrl: string;
13
+ inputType: string;
14
+ inputUrl: string;
15
+ forceStereo: string;
16
+ streamDelay: string;
17
+ statusLed: string;
18
+ statusPort: string;
19
+ callApi: string;
20
+ trigger: string;
21
+ schedule: string;
22
+ prepareAhead: string;
23
+ startTime: string;
24
+ stopTime: string;
25
+ };
26
+ export type TStreamList = Record<string, TStreamAttributes>;
3
27
  export declare class CamStreamerAPI {
4
- private tls;
5
- private tlsInsecure;
6
- private ip;
7
- private port;
8
- private user;
9
- private pass;
10
- constructor(options?: CamStreamerAPIOptions);
11
- getStreamList(): Promise<any>;
12
- getStreamParameter(streamID: string, paramName: string): Promise<any>;
13
- setStreamParameter(streamID: string, paramName: string, value: string): Promise<any>;
14
- isStreaming(streamID: string): Promise<any>;
28
+ private client;
29
+ constructor(options?: CamStreamerAPIOptions | IClient);
30
+ getStreamList(): Promise<TStreamList>;
31
+ getStreamParameter(streamID: string, paramName: string): Promise<string>;
32
+ setStreamParameter(streamID: string, paramName: string, value: string): Promise<void>;
33
+ isStreaming(streamID: string): Promise<boolean>;
15
34
  get(path: string): Promise<any>;
16
- private getBaseConnectionParams;
17
35
  }
package/CamStreamerAPI.js CHANGED
@@ -10,16 +10,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.CamStreamerAPI = void 0;
13
- const HttpRequest_1 = require("./internal/HttpRequest");
13
+ const common_1 = require("./internal/common");
14
+ const DefaultAgent_1 = require("./DefaultAgent");
14
15
  class CamStreamerAPI {
15
- constructor(options) {
16
- var _a, _b, _c, _d, _e, _f;
17
- this.tls = (_a = options === null || options === void 0 ? void 0 : options.tls) !== null && _a !== void 0 ? _a : false;
18
- this.tlsInsecure = (_b = options === null || options === void 0 ? void 0 : options.tlsInsecure) !== null && _b !== void 0 ? _b : false;
19
- this.ip = (_c = options === null || options === void 0 ? void 0 : options.ip) !== null && _c !== void 0 ? _c : '127.0.0.1';
20
- this.port = (_d = options === null || options === void 0 ? void 0 : options.port) !== null && _d !== void 0 ? _d : (this.tls ? 443 : 80);
21
- this.user = (_e = options === null || options === void 0 ? void 0 : options.user) !== null && _e !== void 0 ? _e : '';
22
- this.pass = (_f = options === null || options === void 0 ? void 0 : options.pass) !== null && _f !== void 0 ? _f : '';
16
+ constructor(options = {}) {
17
+ if ((0, common_1.isClient)(options)) {
18
+ this.client = options;
19
+ }
20
+ else {
21
+ this.client = new DefaultAgent_1.DefaultAgent(options);
22
+ }
23
23
  }
24
24
  getStreamList() {
25
25
  return __awaiter(this, void 0, void 0, function* () {
@@ -35,19 +35,18 @@ class CamStreamerAPI {
35
35
  }
36
36
  setStreamParameter(streamID, paramName, value) {
37
37
  return __awaiter(this, void 0, void 0, function* () {
38
- return yield this.get(`/local/camstreamer/stream/set.cgi?stream_id=${streamID}&${paramName}=${value}`);
38
+ yield this.get(`/local/camstreamer/stream/set.cgi?stream_id=${streamID}&${paramName}=${value}`);
39
39
  });
40
40
  }
41
41
  isStreaming(streamID) {
42
42
  return __awaiter(this, void 0, void 0, function* () {
43
43
  const response = yield this.get(`/local/camstreamer/get_streamstat.cgi?stream_id=${streamID}`);
44
- return response.data.is_streaming;
44
+ return response.data.is_streaming === 1;
45
45
  });
46
46
  }
47
47
  get(path) {
48
48
  return __awaiter(this, void 0, void 0, function* () {
49
- const options = this.getBaseConnectionParams(path);
50
- const res = yield (0, HttpRequest_1.sendRequest)(options);
49
+ const res = yield this.client.get(path);
51
50
  if (res.ok) {
52
51
  return yield res.json();
53
52
  }
@@ -56,17 +55,5 @@ class CamStreamerAPI {
56
55
  }
57
56
  });
58
57
  }
59
- getBaseConnectionParams(path, method = 'GET') {
60
- return {
61
- method: method,
62
- protocol: this.tls ? 'https:' : 'http:',
63
- host: this.ip,
64
- port: this.port,
65
- path: path,
66
- user: this.user,
67
- pass: this.pass,
68
- rejectUnauthorized: !this.tlsInsecure,
69
- };
70
- }
71
58
  }
72
59
  exports.CamStreamerAPI = CamStreamerAPI;
@@ -1,24 +1,52 @@
1
+ /// <reference types="node" />
1
2
  import * as EventEmitter from 'events';
2
- import { Options } from './internal/common';
3
+ import { IClient, Options } from './internal/common';
3
4
  export type CamSwitcherAPIOptions = Options;
5
+ export type TStreamInfo = {
6
+ id: string;
7
+ isTimeoutCustom: boolean;
8
+ ptz_preset_pos_name: string;
9
+ repeat: number;
10
+ timeout: number;
11
+ video: Record<string, string>;
12
+ audio: Record<string, string>;
13
+ };
14
+ export type TPlaylistInfo = {
15
+ channel: string;
16
+ isFavourite: false;
17
+ keyboard: object;
18
+ loop: boolean;
19
+ niceName: string;
20
+ sortIndexFavourite: number;
21
+ sortIndexOverview: number;
22
+ stream_list: TStreamInfo[];
23
+ };
24
+ export type TClipInfo = {
25
+ niceName: string;
26
+ channel: string;
27
+ keyboard: object;
28
+ sortIndexOverview: number;
29
+ };
30
+ export type TPlaylistList = Record<string, TPlaylistInfo>;
31
+ export type TClipList = Record<string, TClipInfo>;
32
+ export type TPlaylistQueue = {
33
+ playlist_queue_list: string[];
34
+ };
35
+ export type TOutputInfo = {
36
+ rtsp_url: string;
37
+ ws: string;
38
+ ws_initial_message: string;
39
+ };
4
40
  export declare class CamSwitcherAPI extends EventEmitter {
5
- private tls;
6
- private tlsInsecure;
7
- private ip;
8
- private port;
9
- private user;
10
- private pass;
11
- private ws?;
12
- constructor(options?: CamSwitcherAPIOptions);
13
- connect(): Promise<void>;
14
- getPlaylistList(): Promise<object>;
15
- getClipList(): Promise<object>;
16
- playlistSwitch(playlistName: string): Promise<object>;
17
- playlistQueueList(): Promise<object>;
18
- playlistQueueClear(): Promise<object>;
19
- playlistQueuePush(playlistName: string): Promise<object>;
20
- playlistQueuePlayNext(): Promise<object>;
21
- getOutputInfo(): Promise<object>;
22
- get(path: string): Promise<object>;
23
- private getBaseConnectionParams;
41
+ private client;
42
+ constructor(options?: CamSwitcherAPIOptions | IClient);
43
+ getPlaylistList(): Promise<TPlaylistList>;
44
+ getClipList(): Promise<TClipList>;
45
+ playlistSwitch(playlistName: string): Promise<void>;
46
+ playlistQueueList(): Promise<TPlaylistQueue>;
47
+ playlistQueueClear(): Promise<void>;
48
+ playlistQueuePush(playlistName: string): Promise<void>;
49
+ playlistQueuePlayNext(): Promise<void>;
50
+ getOutputInfo(): Promise<TOutputInfo>;
51
+ get(path: string): Promise<any>;
24
52
  }
package/CamSwitcherAPI.js CHANGED
@@ -11,61 +11,19 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.CamSwitcherAPI = void 0;
13
13
  const EventEmitter = require("events");
14
- const WsClient_1 = require("./internal/WsClient");
15
- const HttpRequest_1 = require("./internal/HttpRequest");
14
+ const DefaultAgent_1 = require("./DefaultAgent");
15
+ const common_1 = require("./internal/common");
16
16
  class CamSwitcherAPI extends EventEmitter {
17
- constructor(options) {
18
- var _a, _b, _c, _d, _e, _f;
17
+ constructor(options = {}) {
19
18
  super();
20
- this.tls = (_a = options === null || options === void 0 ? void 0 : options.tls) !== null && _a !== void 0 ? _a : false;
21
- this.tlsInsecure = (_b = options === null || options === void 0 ? void 0 : options.tlsInsecure) !== null && _b !== void 0 ? _b : false;
22
- this.ip = (_c = options === null || options === void 0 ? void 0 : options.ip) !== null && _c !== void 0 ? _c : '127.0.0.1';
23
- this.port = (_d = options === null || options === void 0 ? void 0 : options.port) !== null && _d !== void 0 ? _d : (this.tls ? 443 : 80);
24
- this.user = (_e = options === null || options === void 0 ? void 0 : options.user) !== null && _e !== void 0 ? _e : '';
25
- this.pass = (_f = options === null || options === void 0 ? void 0 : options.pass) !== null && _f !== void 0 ? _f : '';
19
+ if ((0, common_1.isClient)(options)) {
20
+ this.client = options;
21
+ }
22
+ else {
23
+ this.client = new DefaultAgent_1.DefaultAgent(options);
24
+ }
26
25
  EventEmitter.call(this);
27
26
  }
28
- connect() {
29
- return __awaiter(this, void 0, void 0, function* () {
30
- try {
31
- const token = yield this.get('/local/camswitcher/ws_authorization.cgi');
32
- const options = {
33
- ip: this.ip,
34
- port: this.port,
35
- user: this.user,
36
- pass: this.pass,
37
- tls: this.tls,
38
- tlsInsecure: this.tlsInsecure,
39
- address: '/local/camswitcher/events',
40
- protocol: 'events',
41
- };
42
- this.ws = new WsClient_1.WsClient(options);
43
- this.ws.on('open', () => {
44
- var _a;
45
- (_a = this.ws) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify({ authorization: token }));
46
- });
47
- this.ws.on('message', (data) => {
48
- try {
49
- const parsedData = JSON.parse(data.toString());
50
- this.emit('event', parsedData);
51
- }
52
- catch (err) {
53
- console.log(err);
54
- }
55
- });
56
- this.ws.on('close', () => {
57
- this.emit('event_connection_close');
58
- });
59
- this.ws.on('error', (err) => {
60
- this.emit('event_connection_error', err);
61
- });
62
- this.ws.open();
63
- }
64
- catch (err) {
65
- this.emit('event_connection_error', err);
66
- }
67
- });
68
- }
69
27
  getPlaylistList() {
70
28
  return this.get('/local/camswitcher/playlists.cgi?action=get');
71
29
  }
@@ -73,52 +31,41 @@ class CamSwitcherAPI extends EventEmitter {
73
31
  return this.get('/local/camswitcher/clips.cgi?action=get');
74
32
  }
75
33
  playlistSwitch(playlistName) {
76
- return this.get(`/local/camswitcher/playlist_switch.cgi?playlist_name=${playlistName}`);
34
+ return __awaiter(this, void 0, void 0, function* () {
35
+ yield this.get(`/local/camswitcher/playlist_switch.cgi?playlist_name=${playlistName}`);
36
+ });
77
37
  }
78
38
  playlistQueueList() {
79
39
  return this.get('/local/camswitcher/playlist_queue_list.cgi');
80
40
  }
81
41
  playlistQueueClear() {
82
- return this.get('/local/camswitcher/playlist_queue_clear.cgi');
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ yield this.get('/local/camswitcher/playlist_queue_clear.cgi');
44
+ });
83
45
  }
84
46
  playlistQueuePush(playlistName) {
85
- return this.get(`/local/camswitcher/playlist_queue_push.cgi?playlist_name=${playlistName}`);
47
+ return __awaiter(this, void 0, void 0, function* () {
48
+ yield this.get(`/local/camswitcher/playlist_queue_push.cgi?playlist_name=${playlistName}`);
49
+ });
86
50
  }
87
51
  playlistQueuePlayNext() {
88
- return this.get('/local/camswitcher/playlist_queue_play_next.cgi');
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ yield this.get('/local/camswitcher/playlist_queue_play_next.cgi');
54
+ });
89
55
  }
90
56
  getOutputInfo() {
91
57
  return this.get('/local/camswitcher/output_info.cgi');
92
58
  }
93
59
  get(path) {
94
60
  return __awaiter(this, void 0, void 0, function* () {
95
- const options = this.getBaseConnectionParams(path);
96
- const res = yield (0, HttpRequest_1.sendRequest)(options);
61
+ const res = yield this.client.get(path);
97
62
  if (res.ok) {
98
- const responseText = JSON.parse(yield res.text());
99
- if (responseText.status === 200) {
100
- return responseText.data;
101
- }
102
- else {
103
- throw new Error(`Request (${path}) error, response: ${JSON.stringify(responseText)}`);
104
- }
63
+ return yield res.json();
105
64
  }
106
65
  else {
107
66
  throw new Error(JSON.stringify(res));
108
67
  }
109
68
  });
110
69
  }
111
- getBaseConnectionParams(path, method = 'GET') {
112
- return {
113
- method: method,
114
- protocol: this.tls ? 'https:' : 'http:',
115
- host: this.ip,
116
- port: this.port,
117
- path: path,
118
- user: this.user,
119
- pass: this.pass,
120
- rejectUnauthorized: !this.tlsInsecure,
121
- };
122
- }
123
70
  }
124
71
  exports.CamSwitcherAPI = CamSwitcherAPI;
@@ -0,0 +1,17 @@
1
+ /// <reference types="node" />
2
+ import * as EventEmitter from 'events';
3
+ import { Options } from './internal/common';
4
+ export type CamSwitcherEventsOptions = Options;
5
+ export declare class CamSwitcherEvents extends EventEmitter {
6
+ private ws?;
7
+ private client;
8
+ private tls;
9
+ private tlsInsecure;
10
+ private ip;
11
+ private port;
12
+ private user;
13
+ private pass;
14
+ constructor(options?: CamSwitcherEventsOptions);
15
+ connect(): Promise<void>;
16
+ private get;
17
+ }
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.CamSwitcherEvents = void 0;
13
+ const EventEmitter = require("events");
14
+ const WsClient_1 = require("./internal/WsClient");
15
+ const DefaultAgent_1 = require("./DefaultAgent");
16
+ class CamSwitcherEvents extends EventEmitter {
17
+ constructor(options = {}) {
18
+ var _a, _b, _c, _d, _e, _f;
19
+ super();
20
+ this.tls = (_a = options.tls) !== null && _a !== void 0 ? _a : false;
21
+ this.tlsInsecure = (_b = options.tlsInsecure) !== null && _b !== void 0 ? _b : false;
22
+ this.ip = (_c = options.ip) !== null && _c !== void 0 ? _c : '127.0.0.1';
23
+ this.port = (_d = options.port) !== null && _d !== void 0 ? _d : (this.tls ? 443 : 80);
24
+ this.user = (_e = options.user) !== null && _e !== void 0 ? _e : 'root';
25
+ this.pass = (_f = options.pass) !== null && _f !== void 0 ? _f : '';
26
+ this.client = new DefaultAgent_1.DefaultAgent(options);
27
+ EventEmitter.call(this);
28
+ }
29
+ connect() {
30
+ return __awaiter(this, void 0, void 0, function* () {
31
+ try {
32
+ const token = yield this.get('/local/camswitcher/ws_authorization.cgi');
33
+ const options = {
34
+ ip: this.ip,
35
+ port: this.port,
36
+ user: this.user,
37
+ pass: this.pass,
38
+ tls: this.tls,
39
+ tlsInsecure: this.tlsInsecure,
40
+ address: '/local/camswitcher/events',
41
+ protocol: 'events',
42
+ };
43
+ this.ws = new WsClient_1.WsClient(options);
44
+ this.ws.on('open', () => {
45
+ var _a;
46
+ (_a = this.ws) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify({ authorization: token }));
47
+ });
48
+ this.ws.on('message', (data) => {
49
+ try {
50
+ const parsedData = JSON.parse(data.toString());
51
+ this.emit('event', parsedData);
52
+ }
53
+ catch (err) {
54
+ console.log(err);
55
+ }
56
+ });
57
+ this.ws.on('close', () => {
58
+ this.emit('event_connection_close');
59
+ });
60
+ this.ws.on('error', (err) => {
61
+ this.emit('event_connection_error', err);
62
+ });
63
+ this.ws.open();
64
+ }
65
+ catch (err) {
66
+ this.emit('event_connection_error', err);
67
+ }
68
+ });
69
+ }
70
+ get(path) {
71
+ return __awaiter(this, void 0, void 0, function* () {
72
+ const res = yield this.client.get(path);
73
+ if (res.ok) {
74
+ const responseText = JSON.parse(yield res.text());
75
+ if (responseText.status === 200) {
76
+ return responseText.data;
77
+ }
78
+ else {
79
+ throw new Error(`Request (${path}) error, response: ${JSON.stringify(responseText)}`);
80
+ }
81
+ }
82
+ else {
83
+ throw new Error(JSON.stringify(res));
84
+ }
85
+ });
86
+ }
87
+ }
88
+ exports.CamSwitcherEvents = CamSwitcherEvents;
package/CameraVapix.d.ts CHANGED
@@ -1,6 +1,8 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  import { WritableStream } from 'node:stream/web';
2
4
  import { EventEmitter2 as EventEmitter } from 'eventemitter2';
3
- import { Options } from './internal/common';
5
+ import { IClient, Options } from './internal/common';
4
6
  export type CameraVapixOptions = Options;
5
7
  export type TApplicationList = {
6
8
  reply: {
@@ -40,14 +42,8 @@ export type TGuardTour = {
40
42
  }[];
41
43
  };
42
44
  export declare class CameraVapix extends EventEmitter {
43
- private tls;
44
- private tlsInsecure;
45
- private ip;
46
- private port;
47
- private user;
48
- private pass;
49
- private ws?;
50
- constructor(options?: CameraVapixOptions);
45
+ private client;
46
+ constructor(options?: CameraVapixOptions | IClient);
51
47
  vapixGet(path: string): Promise<Response>;
52
48
  vapixPost(path: string, data: string, contentType?: string): Promise<Response>;
53
49
  getParameterGroup(groupNames: string): Promise<Record<string, string>>;
@@ -61,8 +57,4 @@ export declare class CameraVapix extends EventEmitter {
61
57
  getApplicationList(): Promise<TApplication[]>;
62
58
  getCameraImage(camera: string, compression: string, resolution: string, outputStream: WritableStream): Promise<WritableStream<any>>;
63
59
  getEventDeclarations(): Promise<string>;
64
- eventsConnect(): void;
65
- eventsDisconnect(): void;
66
- private isReservedEventName;
67
- private getBaseVapixConnectionParams;
68
60
  }
package/CameraVapix.js CHANGED
@@ -13,29 +13,27 @@ exports.CameraVapix = void 0;
13
13
  const prettifyXml = require("prettify-xml");
14
14
  const xml2js_1 = require("xml2js");
15
15
  const eventemitter2_1 = require("eventemitter2");
16
- const WsClient_1 = require("./internal/WsClient");
17
- const HttpRequest_1 = require("./internal/HttpRequest");
16
+ const common_1 = require("./internal/common");
17
+ const DefaultAgent_1 = require("./DefaultAgent");
18
18
  class CameraVapix extends eventemitter2_1.EventEmitter2 {
19
- constructor(options) {
20
- var _a, _b, _c, _d, _e, _f;
19
+ constructor(options = {}) {
21
20
  super();
22
- this.tls = (_a = options === null || options === void 0 ? void 0 : options.tls) !== null && _a !== void 0 ? _a : false;
23
- this.tlsInsecure = (_b = options === null || options === void 0 ? void 0 : options.tlsInsecure) !== null && _b !== void 0 ? _b : false;
24
- this.ip = (_c = options === null || options === void 0 ? void 0 : options.ip) !== null && _c !== void 0 ? _c : '127.0.0.1';
25
- this.port = (_d = options === null || options === void 0 ? void 0 : options.port) !== null && _d !== void 0 ? _d : (this.tls ? 443 : 80);
26
- this.user = (_e = options === null || options === void 0 ? void 0 : options.user) !== null && _e !== void 0 ? _e : '';
27
- this.pass = (_f = options === null || options === void 0 ? void 0 : options.pass) !== null && _f !== void 0 ? _f : '';
21
+ if ((0, common_1.isClient)(options)) {
22
+ this.client = options;
23
+ }
24
+ else {
25
+ this.client = new DefaultAgent_1.DefaultAgent(options);
26
+ }
28
27
  }
29
28
  vapixGet(path) {
30
- const options = this.getBaseVapixConnectionParams(path);
31
- return (0, HttpRequest_1.sendRequest)(options, undefined);
29
+ return this.client.get(path);
32
30
  }
33
31
  vapixPost(path, data, contentType) {
34
- const options = this.getBaseVapixConnectionParams(path, 'POST');
32
+ let headers = {};
35
33
  if (contentType !== undefined) {
36
- options.headers = { 'Content-Type': contentType };
34
+ headers = { 'Content-Type': contentType };
37
35
  }
38
- return (0, HttpRequest_1.sendRequest)(options, data);
36
+ return this.client.post(path, data, {}, headers);
39
37
  }
40
38
  getParameterGroup(groupNames) {
41
39
  return __awaiter(this, void 0, void 0, function* () {
@@ -165,87 +163,5 @@ class CameraVapix extends eventemitter2_1.EventEmitter2 {
165
163
  return prettifyXml(declarations);
166
164
  });
167
165
  }
168
- eventsConnect() {
169
- if (this.ws !== undefined) {
170
- throw new Error('Websocket is already opened.');
171
- }
172
- const options = {
173
- tls: this.tls,
174
- tlsInsecure: this.tlsInsecure,
175
- user: this.user,
176
- pass: this.pass,
177
- ip: this.ip,
178
- port: this.port,
179
- address: '/vapix/ws-data-stream?sources=events',
180
- };
181
- this.ws = new WsClient_1.WsClient(options);
182
- this.ws.on('open', () => {
183
- var _a;
184
- const topics = [];
185
- const eventNames = this.eventNames();
186
- for (let i = 0; i < eventNames.length; i++) {
187
- if (!this.isReservedEventName(eventNames[i])) {
188
- const topic = {
189
- topicFilter: eventNames[i],
190
- };
191
- topics.push(topic);
192
- }
193
- }
194
- const topicFilter = {
195
- apiVersion: '1.0',
196
- method: 'events:configure',
197
- params: {
198
- eventFilterList: topics,
199
- },
200
- };
201
- (_a = this.ws) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(topicFilter));
202
- });
203
- this.ws.on('message', (data) => {
204
- const dataJSON = JSON.parse(data.toString());
205
- if (dataJSON.method === 'events:configure') {
206
- if (dataJSON.error === undefined) {
207
- this.emit('eventsConnect');
208
- }
209
- else {
210
- this.emit('eventsDisconnect', dataJSON.error);
211
- this.eventsDisconnect();
212
- }
213
- return;
214
- }
215
- const eventName = dataJSON.params.notification.topic;
216
- this.emit(eventName, dataJSON);
217
- });
218
- this.ws.on('error', (error) => {
219
- this.emit('eventsDisconnect', error);
220
- this.ws = undefined;
221
- });
222
- this.ws.on('close', () => {
223
- if (this.ws !== undefined) {
224
- this.emit('eventsClose');
225
- }
226
- this.ws = undefined;
227
- });
228
- this.ws.open();
229
- }
230
- eventsDisconnect() {
231
- if (this.ws !== undefined) {
232
- this.ws.close();
233
- }
234
- }
235
- isReservedEventName(eventName) {
236
- return eventName === 'eventsConnect' || eventName === 'eventsDisconnect' || eventName === 'eventsClose';
237
- }
238
- getBaseVapixConnectionParams(path, method = 'GET') {
239
- return {
240
- method: method,
241
- protocol: this.tls ? 'https:' : 'http:',
242
- host: this.ip,
243
- port: this.port,
244
- path: path,
245
- user: this.user,
246
- pass: this.pass,
247
- rejectUnauthorized: !this.tlsInsecure,
248
- };
249
- }
250
166
  }
251
167
  exports.CameraVapix = CameraVapix;
@@ -0,0 +1,15 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { Options, IClient } from './internal/common';
4
+ export declare class DefaultAgent implements IClient {
5
+ private tls;
6
+ private tlsInsecure;
7
+ private ip;
8
+ private port;
9
+ private user;
10
+ private pass;
11
+ constructor(opt?: Options);
12
+ private getBaseConnectionParams;
13
+ get(path: string, parameters?: Record<string, string>, headers?: Record<string, string>): Promise<Response>;
14
+ post(path: string, data: string | Buffer | FormData, parameters?: Record<string, string>, headers?: Record<string, string>): Promise<Response>;
15
+ }
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.DefaultAgent = void 0;
13
+ const HttpRequest_1 = require("./internal/HttpRequest");
14
+ function isBrowserEnvironment() {
15
+ return typeof process === 'undefined' || process.versions === null || process.versions.node === null;
16
+ }
17
+ class DefaultAgent {
18
+ constructor(opt = {}) {
19
+ var _a, _b, _c, _d, _e, _f;
20
+ this.tls = (_a = opt.tls) !== null && _a !== void 0 ? _a : false;
21
+ this.tlsInsecure = (_b = opt.tlsInsecure) !== null && _b !== void 0 ? _b : false;
22
+ this.ip = (_c = opt.ip) !== null && _c !== void 0 ? _c : '127.0.0.1';
23
+ this.port = (_d = opt.port) !== null && _d !== void 0 ? _d : (this.tls ? 443 : 80);
24
+ this.user = (_e = opt.user) !== null && _e !== void 0 ? _e : '';
25
+ this.pass = (_f = opt.pass) !== null && _f !== void 0 ? _f : '';
26
+ if (isBrowserEnvironment() && opt.tlsInsecure) {
27
+ throw new Error("HTTPS insecure can't be used on the frontend side.");
28
+ }
29
+ }
30
+ getBaseConnectionParams(method, path, params) {
31
+ if (path.indexOf('?') === -1) {
32
+ path += '?';
33
+ }
34
+ else {
35
+ path += '&';
36
+ }
37
+ for (const key in params) {
38
+ path += `${key}=${params[key]}&`;
39
+ }
40
+ path = path.slice(0, path.length - 1);
41
+ return {
42
+ method: method,
43
+ protocol: this.tls ? 'https:' : 'http:',
44
+ host: this.ip,
45
+ port: this.port,
46
+ path: path,
47
+ user: this.user,
48
+ pass: this.pass,
49
+ rejectUnauthorized: !this.tlsInsecure,
50
+ };
51
+ }
52
+ get(path, parameters = {}, headers) {
53
+ return __awaiter(this, void 0, void 0, function* () {
54
+ const options = this.getBaseConnectionParams('GET', path, parameters);
55
+ options.headers = headers;
56
+ return (0, HttpRequest_1.sendRequest)(options);
57
+ });
58
+ }
59
+ post(path, data, parameters = {}, headers) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ const options = this.getBaseConnectionParams('POST', path, parameters);
62
+ options.headers = headers;
63
+ return (0, HttpRequest_1.sendRequest)(options, data);
64
+ });
65
+ }
66
+ }
67
+ exports.DefaultAgent = DefaultAgent;
package/HttpServer.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  import * as http from 'http';
2
4
  import * as EventEmitter from 'events';
3
5
  export type HttpServerOptions = {
@@ -0,0 +1,16 @@
1
+ import { EventEmitter2 as EventEmitter } from 'eventemitter2';
2
+ import { Options } from './internal/common';
3
+ export type VapixEventsOptions = Options;
4
+ export declare class VapixEvents extends EventEmitter {
5
+ private ws?;
6
+ private tls;
7
+ private tlsInsecure;
8
+ private ip;
9
+ private port;
10
+ private user;
11
+ private pass;
12
+ constructor(options?: VapixEventsOptions);
13
+ connect(): void;
14
+ disconnect(): void;
15
+ private isReservedEventName;
16
+ }
package/VapixEvents.js ADDED
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VapixEvents = void 0;
4
+ const eventemitter2_1 = require("eventemitter2");
5
+ const WsClient_1 = require("./internal/WsClient");
6
+ class VapixEvents extends eventemitter2_1.EventEmitter2 {
7
+ constructor(options = {}) {
8
+ var _a, _b, _c, _d, _e, _f;
9
+ super();
10
+ this.tls = (_a = options.tls) !== null && _a !== void 0 ? _a : false;
11
+ this.tlsInsecure = (_b = options.tlsInsecure) !== null && _b !== void 0 ? _b : false;
12
+ this.ip = (_c = options.ip) !== null && _c !== void 0 ? _c : '127.0.0.1';
13
+ this.port = (_d = options.port) !== null && _d !== void 0 ? _d : (this.tls ? 443 : 80);
14
+ this.user = (_e = options.user) !== null && _e !== void 0 ? _e : 'root';
15
+ this.pass = (_f = options.pass) !== null && _f !== void 0 ? _f : '';
16
+ eventemitter2_1.EventEmitter2.call(this);
17
+ }
18
+ connect() {
19
+ if (this.ws !== undefined) {
20
+ throw new Error('Websocket is already opened.');
21
+ }
22
+ const options = {
23
+ tls: this.tls,
24
+ tlsInsecure: this.tlsInsecure,
25
+ user: this.user,
26
+ pass: this.pass,
27
+ ip: this.ip,
28
+ port: this.port,
29
+ address: '/vapix/ws-data-stream?sources=events',
30
+ };
31
+ this.ws = new WsClient_1.WsClient(options);
32
+ this.ws.on('open', () => {
33
+ var _a;
34
+ const topics = [];
35
+ const eventNames = this.eventNames();
36
+ for (let i = 0; i < eventNames.length; i++) {
37
+ if (!this.isReservedEventName(eventNames[i])) {
38
+ const topic = {
39
+ topicFilter: eventNames[i],
40
+ };
41
+ topics.push(topic);
42
+ }
43
+ }
44
+ const topicFilter = {
45
+ apiVersion: '1.0',
46
+ method: 'events:configure',
47
+ params: {
48
+ eventFilterList: topics,
49
+ },
50
+ };
51
+ (_a = this.ws) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(topicFilter));
52
+ });
53
+ this.ws.on('message', (data) => {
54
+ const dataJSON = JSON.parse(data.toString());
55
+ if (dataJSON.method === 'events:configure') {
56
+ if (dataJSON.error === undefined) {
57
+ this.emit('eventsConnect');
58
+ }
59
+ else {
60
+ this.emit('eventsDisconnect', dataJSON.error);
61
+ this.disconnect();
62
+ }
63
+ return;
64
+ }
65
+ const eventName = dataJSON.params.notification.topic;
66
+ this.emit(eventName, dataJSON);
67
+ });
68
+ this.ws.on('error', (error) => {
69
+ this.emit('eventsDisconnect', error);
70
+ this.ws = undefined;
71
+ });
72
+ this.ws.on('close', () => {
73
+ if (this.ws !== undefined) {
74
+ this.emit('eventsClose');
75
+ }
76
+ this.ws = undefined;
77
+ });
78
+ this.ws.open();
79
+ }
80
+ disconnect() {
81
+ if (this.ws !== undefined) {
82
+ this.ws.close();
83
+ }
84
+ }
85
+ isReservedEventName(eventName) {
86
+ return eventName === 'eventsConnect' || eventName === 'eventsDisconnect' || eventName === 'eventsClose';
87
+ }
88
+ }
89
+ exports.VapixEvents = VapixEvents;
@@ -0,0 +1,8 @@
1
+ import { IClient, Options } from '../internal/common';
2
+ export type AcsEventsOptions = Options;
3
+ export declare class AxisCameraStationEvents {
4
+ private sourceKey;
5
+ private client;
6
+ constructor(sourceKey: string, opt?: AcsEventsOptions | IClient);
7
+ sendEvent(data: Record<string, string>, eventType: string): Promise<void>;
8
+ }
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.AxisCameraStationEvents = void 0;
13
+ const DefaultAgent_1 = require("../DefaultAgent");
14
+ const common_1 = require("../internal/common");
15
+ function pad(num, size) {
16
+ const sign = Math.sign(num) === -1 ? '-' : '';
17
+ return (sign +
18
+ new Array(size)
19
+ .concat([Math.abs(num)])
20
+ .join('0')
21
+ .slice(-size));
22
+ }
23
+ function getDate() {
24
+ const date = new Date();
25
+ const year = date.getUTCFullYear();
26
+ const month = pad(date.getUTCMonth() + 1, 2);
27
+ const day = pad(date.getUTCDate(), 2);
28
+ const hours = pad(date.getUTCHours(), 2);
29
+ const minutes = pad(date.getUTCMinutes(), 2);
30
+ const seconds = pad(date.getUTCSeconds(), 2);
31
+ return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
32
+ }
33
+ class AxisCameraStationEvents {
34
+ constructor(sourceKey, opt = {}) {
35
+ this.sourceKey = sourceKey;
36
+ if ((0, common_1.isClient)(opt)) {
37
+ this.client = opt;
38
+ }
39
+ else {
40
+ this.client = new DefaultAgent_1.DefaultAgent(opt);
41
+ }
42
+ }
43
+ sendEvent(data, eventType) {
44
+ return __awaiter(this, void 0, void 0, function* () {
45
+ const dateString = getDate();
46
+ const event = {
47
+ addExternalDataRequest: {
48
+ occurrenceTime: dateString,
49
+ source: this.sourceKey,
50
+ externalDataType: eventType,
51
+ data: data,
52
+ },
53
+ };
54
+ const eventData = JSON.stringify(event);
55
+ const res = yield this.client.post('/Acs/Api/ExternalDataFacade/AddExternalData', eventData, undefined, {
56
+ 'Content-Type': 'application/json',
57
+ 'Content-Length': eventData.length.toString(),
58
+ });
59
+ if (!res.ok) {
60
+ throw new Error(`ACS status code: ${res.status}`);
61
+ }
62
+ });
63
+ }
64
+ }
65
+ exports.AxisCameraStationEvents = AxisCameraStationEvents;
@@ -1,3 +1,5 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  export type HttpRequestOptions = {
2
4
  method?: string;
3
5
  protocol: string;
@@ -10,4 +12,4 @@ export type HttpRequestOptions = {
10
12
  headers?: Record<string, string>;
11
13
  rejectUnauthorized?: boolean;
12
14
  };
13
- export declare function sendRequest(options: HttpRequestOptions, postData?: Buffer | string): Promise<Response>;
15
+ export declare function sendRequest(options: HttpRequestOptions, postData?: Buffer | string | FormData): Promise<Response>;
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.sendRequest = sendRequest;
12
+ exports.sendRequest = void 0;
13
13
  const Digest_1 = require("./Digest");
14
14
  function getURL(options) {
15
15
  const url = new URL(options.protocol + options.host + options.path);
@@ -26,8 +26,8 @@ function getDigestHeader(options, digestHeader) {
26
26
  return Digest_1.Digest.getAuthHeader(options.user, options.pass, options.method, options.path, digestHeader);
27
27
  }
28
28
  function sendRequestWithDigest(options, digestHeader, postData) {
29
+ var _a;
29
30
  return __awaiter(this, void 0, void 0, function* () {
30
- var _a;
31
31
  const url = getURL(options);
32
32
  (_a = options.headers) !== null && _a !== void 0 ? _a : (options.headers = {});
33
33
  options.headers['Authorization'] = getDigestHeader(options, digestHeader);
@@ -35,14 +35,22 @@ function sendRequestWithDigest(options, digestHeader, postData) {
35
35
  if (options.timeout !== undefined) {
36
36
  setTimeout(() => controller.abort(new Error('Request timeout')), options.timeout);
37
37
  }
38
- const req = new Request(url, { body: postData, method: options.method, headers: options.headers });
39
- const res = yield fetch(req, { signal: controller.signal });
38
+ let res;
39
+ if (options.rejectUnauthorized) {
40
+ const req = new Request(url, { body: postData, method: options.method, headers: options.headers });
41
+ res = yield fetch(req, { signal: controller.signal });
42
+ }
43
+ else {
44
+ const myFetch = yield Promise.resolve().then(() => require('./fetchInsecure'));
45
+ const req = new myFetch.Request(url, { body: postData, method: options.method, headers: options.headers });
46
+ res = yield myFetch.fetchInsecure(req, { signal: controller.signal });
47
+ }
40
48
  return res;
41
49
  });
42
50
  }
43
51
  function sendRequest(options, postData) {
52
+ var _a;
44
53
  return __awaiter(this, void 0, void 0, function* () {
45
- var _a;
46
54
  const url = getURL(options);
47
55
  const controller = new AbortController();
48
56
  if (options.timeout !== undefined) {
@@ -52,8 +60,16 @@ function sendRequest(options, postData) {
52
60
  (_a = options.headers) !== null && _a !== void 0 ? _a : (options.headers = {});
53
61
  options.headers['Authorization'] = `Basic ${btoa(options.user + ':' + options.pass)}`;
54
62
  }
55
- const req = new Request(url, { body: postData, method: options.method, headers: options.headers });
56
- const res = yield fetch(req, { signal: controller.signal });
63
+ let res;
64
+ if (options.rejectUnauthorized) {
65
+ const req = new Request(url, { body: postData, method: options.method, headers: options.headers });
66
+ res = yield fetch(req, { signal: controller.signal });
67
+ }
68
+ else {
69
+ const myFetch = yield Promise.resolve().then(() => require('./fetchInsecure'));
70
+ const req = new myFetch.Request(url, { body: postData, method: options.method, headers: options.headers });
71
+ res = yield myFetch.fetchInsecure(req, { signal: controller.signal });
72
+ }
57
73
  const wwwAuthenticateHeader = res.headers.get('www-authenticate');
58
74
  if (res.status === 401 && wwwAuthenticateHeader !== null && wwwAuthenticateHeader.indexOf('Digest') !== -1) {
59
75
  return sendRequestWithDigest(options, wwwAuthenticateHeader, postData);
@@ -63,3 +79,4 @@ function sendRequest(options, postData) {
63
79
  }
64
80
  });
65
81
  }
82
+ exports.sendRequest = sendRequest;
@@ -1,3 +1,5 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  import * as EventEmitter from 'events';
2
4
  import { Options } from './common';
3
5
  export type WsClientOptions = Options & {
@@ -1,3 +1,5 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  export type Options = {
2
4
  ip?: string;
3
5
  port?: number;
@@ -6,3 +8,10 @@ export type Options = {
6
8
  tls?: boolean;
7
9
  tlsInsecure?: boolean;
8
10
  };
11
+ export type TGetFunction = (url: string, parameters?: Record<string, string>, headers?: Record<string, string>) => Promise<Response>;
12
+ export type TPostFunction = (url: string, data: string | Buffer | FormData, parameters?: Record<string, string>, headers?: Record<string, string>) => Promise<Response>;
13
+ export interface IClient {
14
+ get: TGetFunction;
15
+ post: TPostFunction;
16
+ }
17
+ export declare function isClient(arg?: Options | IClient): arg is IClient;
@@ -1,2 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isClient = void 0;
4
+ function isClient(arg = {}) {
5
+ return 'get' in arg && 'post' in arg;
6
+ }
7
+ exports.isClient = isClient;
@@ -0,0 +1,4 @@
1
+ /// <reference types="node" />
2
+ import * as undici from 'undici';
3
+ export declare function fetchInsecure(req: undici.Request, init: RequestInit): Promise<undici.Response>;
4
+ export declare const Request: typeof undici.Request;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Request = exports.fetchInsecure = void 0;
4
+ const undici = require("undici");
5
+ function fetchInsecure(req, init) {
6
+ const insecureAgent = new undici.Agent({
7
+ connect: {
8
+ rejectUnauthorized: false,
9
+ },
10
+ });
11
+ return undici.fetch(req, Object.assign(Object.assign({}, init), { dispatcher: insecureAgent }));
12
+ }
13
+ exports.fetchInsecure = fetchInsecure;
14
+ exports.Request = undici.Request;
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "camstreamerlib",
3
- "version": "3.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "Helper library for CamStreamer ACAP applications.",
5
5
  "prettier": "@camstreamer/prettier-config",
6
6
  "dependencies": {
7
7
  "adm-zip": "^0.5.9",
8
8
  "eventemitter2": "^5.0.1",
9
9
  "prettify-xml": "^1.2.0",
10
+ "undici": "6.13.0",
10
11
  "ws": "^7.4.2",
11
12
  "xml2js": "^0.5.0"
12
13
  },
@@ -31,7 +32,7 @@
31
32
  "prettier": "^2.7.1",
32
33
  "ts-jest": "^28.0.0",
33
34
  "ts-node": "^10.7.0",
34
- "typescript": "^5.2.2"
35
+ "typescript": "5.3.3"
35
36
  },
36
37
  "scripts": {
37
38
  "clean": "rimraf dist/*",