camstreamerlib 3.5.2 → 4.0.0-beta.2

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.
Files changed (72) hide show
  1. package/CamOverlayAPI.d.ts +11 -28
  2. package/CamOverlayAPI.js +116 -138
  3. package/CamOverlayDrawingAPI.js +26 -18
  4. package/CamOverlayPainter/Frame.js +167 -182
  5. package/CamOverlayPainter/Painter.js +80 -101
  6. package/CamOverlayPainter/ResourceManager.js +31 -46
  7. package/CamScripterAPI.d.ts +19 -0
  8. package/CamScripterAPI.js +66 -0
  9. package/CamScripterAPICameraEventsGenerator.js +22 -16
  10. package/CamStreamerAPI.d.ts +5 -27
  11. package/CamStreamerAPI.js +45 -71
  12. package/CamSwitcherAPI.d.ts +38 -71
  13. package/CamSwitcherAPI.js +329 -91
  14. package/CamSwitcherEvents.d.ts +15 -33
  15. package/CamSwitcherEvents.js +53 -97
  16. package/CreatePackage.js +5 -7
  17. package/README.md +3 -1
  18. package/VapixAPI.d.ts +66 -0
  19. package/VapixAPI.js +454 -0
  20. package/VapixEvents.js +18 -16
  21. package/errors/errors.d.ts +34 -0
  22. package/errors/errors.js +66 -0
  23. package/events/AxisCameraStationEvents.js +29 -42
  24. package/events/GenetecAgent.d.ts +14 -15
  25. package/events/GenetecAgent.js +81 -100
  26. package/internal/Digest.js +5 -11
  27. package/internal/ProxyClient.d.ts +11 -0
  28. package/internal/ProxyClient.js +40 -0
  29. package/internal/common.d.ts +19 -4
  30. package/internal/common.js +11 -26
  31. package/internal/constants.d.ts +1 -0
  32. package/internal/constants.js +1 -0
  33. package/internal/transformers.d.ts +5 -0
  34. package/internal/transformers.js +25 -0
  35. package/internal/utils.d.ts +11 -0
  36. package/internal/utils.js +34 -0
  37. package/internal/versionCompare.d.ts +6 -0
  38. package/internal/versionCompare.js +44 -0
  39. package/node/DefaultClient.d.ts +15 -0
  40. package/node/DefaultClient.js +50 -0
  41. package/{internal → node}/HttpRequestSender.d.ts +2 -2
  42. package/node/HttpRequestSender.js +85 -0
  43. package/{HttpServer.d.ts → node/HttpServer.d.ts} +1 -1
  44. package/{HttpServer.js → node/HttpServer.js} +22 -24
  45. package/{internal → node}/WsClient.d.ts +1 -1
  46. package/{internal → node}/WsClient.js +32 -39
  47. package/node/WsEventClient.d.ts +13 -0
  48. package/node/WsEventClient.js +18 -0
  49. package/package.json +7 -3
  50. package/types/CamOverlayAPI.d.ts +188 -0
  51. package/types/CamOverlayAPI.js +44 -0
  52. package/types/CamScripterAPI.d.ts +67 -0
  53. package/types/CamScripterAPI.js +17 -0
  54. package/types/CamStreamerAPI.d.ts +139 -0
  55. package/types/CamStreamerAPI.js +25 -0
  56. package/types/CamSwitcherAPI.d.ts +814 -0
  57. package/types/CamSwitcherAPI.js +134 -0
  58. package/types/CamswitcherEvents.d.ts +491 -0
  59. package/types/CamswitcherEvents.js +59 -0
  60. package/types/VapixAPI.d.ts +1704 -0
  61. package/types/VapixAPI.js +129 -0
  62. package/types/common.d.ts +37 -0
  63. package/types/common.js +11 -0
  64. package/web/DefaultClient.d.ts +6 -0
  65. package/web/DefaultClient.js +16 -0
  66. package/web/WsClient.d.ts +13 -0
  67. package/web/WsClient.js +58 -0
  68. package/CameraVapix.d.ts +0 -98
  69. package/CameraVapix.js +0 -441
  70. package/DefaultAgent.d.ts +0 -15
  71. package/DefaultAgent.js +0 -68
  72. package/internal/HttpRequestSender.js +0 -117
package/CameraVapix.js DELETED
@@ -1,441 +0,0 @@
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
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.CameraVapix = void 0;
24
- const prettifyXml = require("prettify-xml");
25
- const xml2js_1 = require("xml2js");
26
- const common_1 = require("./internal/common");
27
- const DefaultAgent_1 = require("./DefaultAgent");
28
- class CameraVapix {
29
- constructor(options = {}) {
30
- if ((0, common_1.isClient)(options)) {
31
- this.client = options;
32
- }
33
- else {
34
- this.client = new DefaultAgent_1.DefaultAgent(options);
35
- }
36
- }
37
- vapixGet(path, parameters) {
38
- return this.client.get(path, parameters);
39
- }
40
- vapixPost(path, data, contentType) {
41
- let headers = {};
42
- if (contentType !== undefined) {
43
- headers = { 'Content-Type': contentType };
44
- }
45
- return this.client.post(path, data, {}, headers);
46
- }
47
- getCameraImage(camera, compression, resolution, outputStream) {
48
- return __awaiter(this, void 0, void 0, function* () {
49
- const res = yield this.vapixGet('/axis-cgi/jpg/image.cgi', { resolution, compression, camera });
50
- if (res.body) {
51
- void res.body.pipeTo(outputStream);
52
- }
53
- return outputStream;
54
- });
55
- }
56
- getEventDeclarations() {
57
- return __awaiter(this, void 0, void 0, function* () {
58
- const data = '<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">' +
59
- '<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
60
- 'xmlns:xsd="http://www.w3.org/2001/XMLSchema">' +
61
- '<GetEventInstances xmlns="http://www.axis.com/vapix/ws/event1"/>' +
62
- '</s:Body>' +
63
- '</s:Envelope>';
64
- const declarations = yield (yield this.vapixPost('/vapix/services', data, 'application/soap+xml')).text();
65
- return prettifyXml(declarations);
66
- });
67
- }
68
- getSupportedAudioSampleRate() {
69
- var _a, _b;
70
- return __awaiter(this, void 0, void 0, function* () {
71
- const url = '/axis-cgi/audio/streamingcapabilities.cgi';
72
- const formData = { apiVersion: '1.0', method: 'list' };
73
- const res = yield this.vapixPost(url, JSON.stringify(formData));
74
- try {
75
- const encoders = (yield res.json()).data.encoders;
76
- const data = (_b = (_a = encoders.aac) !== null && _a !== void 0 ? _a : encoders.AAC) !== null && _b !== void 0 ? _b : [];
77
- return data.map((item) => {
78
- return {
79
- sampleRate: item.sample_rate,
80
- bitRates: item.bit_rates,
81
- };
82
- });
83
- }
84
- catch (err) {
85
- return [];
86
- }
87
- });
88
- }
89
- checkSdCard() {
90
- return __awaiter(this, void 0, void 0, function* () {
91
- const res = yield this.vapixGet('/axis-cgi/disks/list.cgi', {
92
- diskid: 'SD_DISK',
93
- });
94
- const result = yield (0, xml2js_1.parseStringPromise)(yield res.text(), {
95
- ignoreAttrs: false,
96
- mergeAttrs: true,
97
- explicitArray: false,
98
- });
99
- const data = result.root.disks.disk;
100
- return {
101
- available: data.status === 'OK',
102
- totalSize: parseInt(data.totalsize),
103
- freeSize: parseInt(data.freesize),
104
- };
105
- });
106
- }
107
- downloadCameraReport() {
108
- return __awaiter(this, void 0, void 0, function* () {
109
- const res = yield this.vapixGet('/axis-cgi/serverreport.cgi', { mode: 'text' });
110
- if (res.ok) {
111
- return res;
112
- }
113
- else {
114
- throw new Error(yield (0, common_1.responseStringify)(res));
115
- }
116
- });
117
- }
118
- getMaxFps(channel) {
119
- return __awaiter(this, void 0, void 0, function* () {
120
- const data = JSON.stringify({ apiVersion: '1.0', method: 'getCaptureModes' });
121
- const res = yield this.vapixPost('/axis-cgi/capturemode.cgi', data);
122
- if (!res.ok) {
123
- throw new Error(yield (0, common_1.responseStringify)(res));
124
- }
125
- const response = (yield res.json());
126
- const channels = response.data;
127
- if (channels === undefined) {
128
- throw new Error(`Malformed reply from camera`);
129
- }
130
- const channelData = channels.find((x) => x.channel === channel);
131
- if (channelData === undefined) {
132
- throw new Error(`Video channel '${channel}' not found`);
133
- }
134
- const captureModes = channelData.captureMode;
135
- const captureMode = captureModes.find((x) => x.enabled === true);
136
- if (captureMode === undefined) {
137
- throw new Error(`No enabled capture mode found.`);
138
- }
139
- const maxFps = parseInt(captureMode.maxFPS, 10);
140
- if (isNaN(maxFps)) {
141
- throw new Error(`Max fps not specified for given capture mode.`);
142
- }
143
- return maxFps;
144
- });
145
- }
146
- getTimezone() {
147
- var _a, _b;
148
- return __awaiter(this, void 0, void 0, function* () {
149
- const data = JSON.stringify({ apiVersion: '1.0', method: 'getDateTimeInfo' });
150
- const res = yield this.vapixPost('/axis-cgi/time.cgi', data);
151
- if (res.ok) {
152
- return (_b = (_a = ((yield res.json()))) === null || _a === void 0 ? void 0 : _a.timeZone) !== null && _b !== void 0 ? _b : 'Europe/Prague';
153
- }
154
- else {
155
- throw new Error(yield (0, common_1.responseStringify)(res));
156
- }
157
- });
158
- }
159
- getHeaders() {
160
- var _a;
161
- return __awaiter(this, void 0, void 0, function* () {
162
- try {
163
- const data = JSON.stringify({ apiVersion: '1.0', method: 'list' });
164
- const res = yield this.vapixPost('/axis-cgi/customhttpheader.cgi', data);
165
- if (res.ok) {
166
- return (_a = (yield res.json()).data) !== null && _a !== void 0 ? _a : {};
167
- }
168
- else {
169
- return {};
170
- }
171
- }
172
- catch (e) {
173
- return {};
174
- }
175
- });
176
- }
177
- setHeaders(headers) {
178
- return __awaiter(this, void 0, void 0, function* () {
179
- const data = JSON.stringify({ apiVersion: '1.0', method: 'set', params: headers });
180
- return this.vapixPost('/axis-cgi/customhttpheader.cgi', data);
181
- });
182
- }
183
- parseParameters(response) {
184
- const params = {};
185
- const lines = response.split(/[\r\n]/);
186
- for (let i = 0; i < lines.length; i++) {
187
- if (lines[i].length === 0 || lines[i].substring(0, 7) === '# Error') {
188
- continue;
189
- }
190
- const delimiterPos = lines[i].indexOf('=');
191
- if (delimiterPos !== -1) {
192
- const paramName = lines[i].substring(0, delimiterPos);
193
- const paramValue = lines[i].substring(delimiterPos + 1);
194
- params[paramName] = paramValue;
195
- }
196
- }
197
- return params;
198
- }
199
- getParameterGroup(groupNames) {
200
- return __awaiter(this, void 0, void 0, function* () {
201
- const response = yield this.vapixGet('/axis-cgi/param.cgi', { action: 'list', group: groupNames });
202
- return this.parseParameters(yield response.text());
203
- });
204
- }
205
- setParameter(params) {
206
- let postData = 'action=update&';
207
- for (const key in params) {
208
- postData += key + '=' + params[key] + '&';
209
- }
210
- postData = postData.slice(0, postData.length - 1);
211
- return this.vapixPost('/axis-cgi/param.cgi', postData);
212
- }
213
- getGuardTourList() {
214
- return __awaiter(this, void 0, void 0, function* () {
215
- const gTourList = new Array();
216
- const response = yield this.getParameterGroup('GuardTour');
217
- for (let i = 0; i < 20; i++) {
218
- const gTourBaseName = 'root.GuardTour.G' + i;
219
- if (gTourBaseName + '.CamNbr' in response) {
220
- const gTour = {
221
- id: gTourBaseName,
222
- camNbr: response[gTourBaseName + '.CamNbr'],
223
- name: response[gTourBaseName + '.Name'],
224
- randomEnabled: response[gTourBaseName + '.RandomEnabled'],
225
- running: response[gTourBaseName + '.Running'],
226
- timeBetweenSequences: response[gTourBaseName + '.TimeBetweenSequences'],
227
- tour: [],
228
- };
229
- for (let j = 0; j < 100; j++) {
230
- const tourBaseName = 'root.GuardTour.G' + i + '.Tour.T' + j;
231
- if (tourBaseName + '.MoveSpeed' in response) {
232
- const tour = {
233
- moveSpeed: response[tourBaseName + '.MoveSpeed'],
234
- position: response[tourBaseName + '.Position'],
235
- presetNbr: response[tourBaseName + '.PresetNbr'],
236
- waitTime: response[tourBaseName + '.WaitTime'],
237
- waitTimeViewType: response[tourBaseName + '.WaitTimeViewType'],
238
- };
239
- gTour.tour.push(tour);
240
- }
241
- }
242
- gTourList.push(gTour);
243
- }
244
- else {
245
- break;
246
- }
247
- }
248
- return gTourList;
249
- });
250
- }
251
- setGuardTourEnabled(guardTourID, enable) {
252
- const options = {};
253
- options[guardTourID + '.Running'] = enable ? 'yes' : 'no';
254
- return this.setParameter(options);
255
- }
256
- parsePtz(parsed) {
257
- const res = [];
258
- parsed.forEach((value) => {
259
- const delimiterPos = value.indexOf('=');
260
- if (delimiterPos === -1) {
261
- return;
262
- }
263
- if (!value.startsWith('presetposno')) {
264
- return;
265
- }
266
- const id = Number(value.substring(11, delimiterPos));
267
- if (Number.isNaN(id)) {
268
- return;
269
- }
270
- const data = value.substring(delimiterPos + 1).split(':');
271
- const getValue = (valueName) => {
272
- for (const d of data) {
273
- const p = d.split('=');
274
- if (p[0] === valueName) {
275
- return Number(p[1]);
276
- }
277
- }
278
- return 0;
279
- };
280
- res.push({
281
- id,
282
- name: data[0],
283
- data: {
284
- pan: getValue('pan'),
285
- tilt: getValue('tilt'),
286
- zoom: getValue('zoom'),
287
- },
288
- });
289
- });
290
- return res;
291
- }
292
- parseCameraPtzResponse(response) {
293
- const json = JSON.parse(response);
294
- const parsed = {};
295
- Object.keys(json).forEach((key) => {
296
- if (!key.startsWith('Camera ')) {
297
- return;
298
- }
299
- const camera = Number(key.replace('Camera ', ''));
300
- if (json[key].presets !== undefined) {
301
- parsed[camera] = this.parsePtz(json[key].presets);
302
- }
303
- });
304
- return parsed;
305
- }
306
- getPTZPresetList(channel) {
307
- return __awaiter(this, void 0, void 0, function* () {
308
- const response = yield (yield this.vapixGet('/axis-cgi/com/ptz.cgi', { query: 'presetposcam', camera: channel.toString() })).text();
309
- const positions = [];
310
- const lines = response.split(/[\r\n]/);
311
- for (const line of lines) {
312
- if (line.indexOf('presetposno') !== -1) {
313
- const delimiterPos = line.indexOf('=');
314
- if (delimiterPos !== -1) {
315
- const value = line.substring(delimiterPos + 1);
316
- positions.push(value);
317
- }
318
- }
319
- }
320
- return positions;
321
- });
322
- }
323
- listPtzVideoSourceOverview() {
324
- return __awaiter(this, void 0, void 0, function* () {
325
- try {
326
- const response = yield this.vapixGet('/axis-cgi/com/ptz.cgi', {
327
- query: 'presetposall',
328
- format: 'json',
329
- });
330
- const data = this.parseCameraPtzResponse(yield response.text());
331
- const res = {};
332
- Object.keys(data).forEach((camera) => {
333
- res[Number(camera) - 1] = data[Number(camera)].map((_a) => {
334
- var { data } = _a, d = __rest(_a, ["data"]);
335
- return d;
336
- });
337
- });
338
- return res;
339
- }
340
- catch (err) {
341
- return [];
342
- }
343
- });
344
- }
345
- goToPreset(channel, presetName) {
346
- return this.vapixGet('/axis-cgi/com/ptz.cgi', { camera: channel.toString(), gotoserverpresetname: presetName });
347
- }
348
- getPtzPosition(camera) {
349
- return __awaiter(this, void 0, void 0, function* () {
350
- try {
351
- const res = yield this.vapixGet('/axis-cgi/com/ptz.cgi', {
352
- query: 'position',
353
- camera: camera.toString(),
354
- });
355
- const params = this.parseParameters(yield res.text());
356
- return {
357
- pan: Number(params.pan),
358
- tilt: Number(params.tilt),
359
- zoom: Number(params.zoom),
360
- };
361
- }
362
- catch (err) {
363
- return { pan: 0, tilt: 0, zoom: 0 };
364
- }
365
- });
366
- }
367
- getInputState(port) {
368
- return __awaiter(this, void 0, void 0, function* () {
369
- const response = yield (yield this.vapixGet('/axis-cgi/io/port.cgi', { checkactive: port.toString() })).text();
370
- return response.split('=')[1].indexOf('active') === 0;
371
- });
372
- }
373
- setOutputState(port, active) {
374
- return __awaiter(this, void 0, void 0, function* () {
375
- return this.vapixGet('/axis-cgi/io/port.cgi', { action: active ? `${port}:/` : `${port}:\\` });
376
- });
377
- }
378
- getApplicationList() {
379
- return __awaiter(this, void 0, void 0, function* () {
380
- const xml = yield (yield this.vapixGet('/axis-cgi/applications/list.cgi')).text();
381
- const result = (yield (0, xml2js_1.parseStringPromise)(xml));
382
- const apps = [];
383
- for (let i = 0; i < result.reply.application.length; i++) {
384
- apps.push(result.reply.application[i].$);
385
- }
386
- return apps;
387
- });
388
- }
389
- startApplication(applicationID) {
390
- return __awaiter(this, void 0, void 0, function* () {
391
- const res = yield this.vapixGet('/axis-cgi/applications/control.cgi', {
392
- package: applicationID.toLowerCase(),
393
- action: 'start',
394
- });
395
- const text = (yield res.text()).trim().toLowerCase();
396
- if (res.ok && text === 'ok') {
397
- return;
398
- }
399
- else if (text.startsWith('error:') && text.substring(7) === '6') {
400
- return;
401
- }
402
- else {
403
- throw new Error(yield (0, common_1.responseStringify)(res));
404
- }
405
- });
406
- }
407
- restartApplication(applicationID) {
408
- return __awaiter(this, void 0, void 0, function* () {
409
- const res = yield this.vapixGet('/axis-cgi/applications/control.cgi', {
410
- package: applicationID.toLowerCase(),
411
- action: 'restart',
412
- });
413
- const text = (yield res.text()).trim().toLowerCase();
414
- if (res.ok && text === 'ok') {
415
- return;
416
- }
417
- else {
418
- throw new Error(yield (0, common_1.responseStringify)(res));
419
- }
420
- });
421
- }
422
- stopApplication(applicationID) {
423
- return __awaiter(this, void 0, void 0, function* () {
424
- const res = yield this.vapixGet('/axis-cgi/applications/control.cgi', {
425
- package: applicationID.toLowerCase(),
426
- action: 'stop',
427
- });
428
- const text = (yield res.text()).trim().toLowerCase();
429
- if (res.ok && text === 'ok') {
430
- return;
431
- }
432
- else if (text.startsWith('error:') && text.substring(7) === '6') {
433
- return;
434
- }
435
- else {
436
- throw new Error(yield (0, common_1.responseStringify)(res));
437
- }
438
- });
439
- }
440
- }
441
- exports.CameraVapix = CameraVapix;
package/DefaultAgent.d.ts DELETED
@@ -1,15 +0,0 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- import { IClient, HttpOptions } from './internal/common';
4
- export declare class DefaultAgent implements IClient {
5
- private tls;
6
- private ip;
7
- private port;
8
- private user;
9
- private pass;
10
- private httpRequestSender;
11
- constructor(opt?: HttpOptions);
12
- get(path: string, parameters?: Record<string, string>, headers?: Record<string, string>, timeout?: number): Promise<Response>;
13
- post(path: string, data: string | Buffer | FormData, parameters?: Record<string, string>, headers?: Record<string, string>, timeout?: number): Promise<Response>;
14
- private getBaseConnectionParams;
15
- }
package/DefaultAgent.js DELETED
@@ -1,68 +0,0 @@
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 HttpRequestSender_1 = require("./internal/HttpRequestSender");
14
- class DefaultAgent {
15
- constructor(opt = {}) {
16
- var _a, _b, _c, _d, _e;
17
- this.tls = (_a = opt.tls) !== null && _a !== void 0 ? _a : false;
18
- this.ip = (_b = opt.ip) !== null && _b !== void 0 ? _b : '127.0.0.1';
19
- this.port = (_c = opt.port) !== null && _c !== void 0 ? _c : (this.tls ? 443 : 80);
20
- this.user = (_d = opt.user) !== null && _d !== void 0 ? _d : '';
21
- this.pass = (_e = opt.pass) !== null && _e !== void 0 ? _e : '';
22
- let agentOptions;
23
- if (opt.tlsInsecure !== undefined || opt.keepAlive !== undefined) {
24
- agentOptions = {
25
- rejectUnaurhorized: !opt.tlsInsecure,
26
- keepAlive: opt.keepAlive,
27
- };
28
- }
29
- this.httpRequestSender = new HttpRequestSender_1.HttpRequestSender(agentOptions);
30
- }
31
- get(path, parameters = {}, headers, timeout) {
32
- return __awaiter(this, void 0, void 0, function* () {
33
- const options = this.getBaseConnectionParams('GET', path, parameters, timeout);
34
- options.headers = headers;
35
- return this.httpRequestSender.sendRequest(options);
36
- });
37
- }
38
- post(path, data, parameters = {}, headers, timeout) {
39
- return __awaiter(this, void 0, void 0, function* () {
40
- const options = this.getBaseConnectionParams('POST', path, parameters, timeout);
41
- options.headers = headers;
42
- return this.httpRequestSender.sendRequest(options, data);
43
- });
44
- }
45
- getBaseConnectionParams(method, path, params, timeout) {
46
- if (path.indexOf('?') === -1) {
47
- path += '?';
48
- }
49
- else {
50
- path += '&';
51
- }
52
- for (const key in params) {
53
- path += `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}&`;
54
- }
55
- path = path.slice(0, path.length - 1);
56
- return {
57
- method: method,
58
- protocol: this.tls ? 'https:' : 'http:',
59
- host: this.ip,
60
- port: this.port,
61
- path: path,
62
- user: this.user,
63
- pass: this.pass,
64
- timeout,
65
- };
66
- }
67
- }
68
- exports.DefaultAgent = DefaultAgent;
@@ -1,117 +0,0 @@
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.HttpRequestSender = void 0;
13
- const Digest_1 = require("./Digest");
14
- const undici_1 = require("undici");
15
- const common_1 = require("./common");
16
- class HttpRequestSender {
17
- constructor(agentOptions) {
18
- if ((0, common_1.isBrowserEnvironment)()) {
19
- if (agentOptions !== undefined) {
20
- throw new Error('Agent options can be specified only in Node.js environment.');
21
- }
22
- }
23
- else {
24
- this.agent = new undici_1.Agent({
25
- connect: { rejectUnauthorized: agentOptions === null || agentOptions === void 0 ? void 0 : agentOptions.rejectUnaurhorized, keepAlive: agentOptions === null || agentOptions === void 0 ? void 0 : agentOptions.keepAlive },
26
- });
27
- }
28
- }
29
- sendRequest(options, postData) {
30
- return this.sendRequestWithAuth(options, postData);
31
- }
32
- sendRequestWithAuth(options, postData, wwwAuthenticateHeader) {
33
- var _a, _b;
34
- return __awaiter(this, void 0, void 0, function* () {
35
- (_a = options.timeout) !== null && _a !== void 0 ? _a : (options.timeout = 10000);
36
- const url = HttpRequestSender.getURL(options);
37
- const controller = new AbortController();
38
- setTimeout(() => controller.abort(new Error('Request timeout')), options.timeout);
39
- const authorization = this.getAuthorization(options, wwwAuthenticateHeader);
40
- if (authorization !== undefined) {
41
- (_b = options.headers) !== null && _b !== void 0 ? _b : (options.headers = {});
42
- options.headers['Authorization'] = authorization;
43
- }
44
- let res;
45
- if (this.agent) {
46
- const req = new undici_1.Request(url, { body: postData, method: options.method, headers: options.headers });
47
- res = yield (0, undici_1.fetch)(req, { signal: controller.signal, dispatcher: this.agent });
48
- }
49
- else {
50
- const req = new Request(url, { body: postData, method: options.method, headers: options.headers });
51
- res = yield fetch(req, { signal: controller.signal });
52
- }
53
- if (!res.ok) {
54
- this.invalidateAuthorization();
55
- }
56
- if (res.status === 401) {
57
- const authenticateHeader = res.headers.get('www-authenticate');
58
- if (authenticateHeader !== null &&
59
- authenticateHeader.indexOf('Digest') !== -1 &&
60
- wwwAuthenticateHeader === undefined) {
61
- return this.sendRequestWithAuth(options, postData, authenticateHeader);
62
- }
63
- else {
64
- return res;
65
- }
66
- }
67
- else {
68
- return res;
69
- }
70
- });
71
- }
72
- static getURL(options) {
73
- const url = new URL(`${options.protocol}//${options.host}:${options.port}${options.path}`);
74
- return url.toString();
75
- }
76
- getAuthorization(options, wwwAuthenticateHeader) {
77
- if (options.user === undefined || options.pass === undefined) {
78
- this.authData = undefined;
79
- return;
80
- }
81
- if (this.authData &&
82
- (this.authData.host !== options.host ||
83
- this.authData.port !== options.port ||
84
- this.authData.user !== options.user ||
85
- this.authData.pass !== options.pass ||
86
- (wwwAuthenticateHeader !== undefined && this.authData.wwwAuthenticateHeader !== wwwAuthenticateHeader))) {
87
- this.authData = undefined;
88
- }
89
- if (this.authData === undefined) {
90
- this.authData = {
91
- host: options.host,
92
- port: options.port,
93
- user: options.user,
94
- pass: options.pass,
95
- wwwAuthenticateHeader,
96
- digest: new Digest_1.Digest(),
97
- };
98
- }
99
- return HttpRequestSender.getAuthHeader(options, this.authData);
100
- }
101
- invalidateAuthorization() {
102
- this.authData = undefined;
103
- }
104
- static getAuthHeader(options, authData) {
105
- var _a;
106
- if (options.user === undefined || options.pass === undefined) {
107
- throw new Error('No credentials found');
108
- }
109
- if (authData.wwwAuthenticateHeader !== undefined && authData.wwwAuthenticateHeader.indexOf('Digest') !== -1) {
110
- return authData.digest.getAuthHeader(options.user, options.pass, (_a = options.method) !== null && _a !== void 0 ? _a : 'GET', options.path, authData.wwwAuthenticateHeader);
111
- }
112
- else {
113
- return `Basic ${btoa(options.user + ':' + options.pass)}`;
114
- }
115
- }
116
- }
117
- exports.HttpRequestSender = HttpRequestSender;