@aloma.io/integration-sdk 3.0.1-9 → 3.0.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.
@@ -1,27 +1,27 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  // @ts-nocheck
4
- require("dotenv").config();
5
- const fs = require("fs");
6
- const { Config } = require("./websocket/config.cjs");
7
- const { Connection } = require("./websocket/connection/index.cjs");
8
- const { Transport } = require("./websocket/transport/index.cjs");
9
- const { Dispatcher } = require("./dispatcher/index.cjs");
10
- const { WebsocketConnector } = require("./websocket/index.cjs");
11
- const JWE = require("./util/jwe/index.cjs");
12
- const fetch = require("node-fetch");
13
- const cuid = require("@paralleldrive/cuid2").init({ length: 32 });
4
+ require('dotenv').config();
5
+ const fs = require('fs');
6
+ const { Config } = require('./websocket/config.cjs');
7
+ const { Connection } = require('./websocket/connection/index.cjs');
8
+ const { Transport } = require('./websocket/transport/index.cjs');
9
+ const { Dispatcher } = require('./dispatcher/index.cjs');
10
+ const { WebsocketConnector } = require('./websocket/index.cjs');
11
+ const JWE = require('./util/jwe/index.cjs');
12
+ const fetch = require('node-fetch');
13
+ const cuid = require('@paralleldrive/cuid2').init({ length: 32 });
14
14
  // TODO fetch with retry
15
15
  const handlePacketError = (packet, e, transport) => {
16
16
  if (!packet.cb()) {
17
- console.dir({ msg: "packet error", e, packet }, { depth: null });
17
+ console.dir({ msg: 'packet error', e, packet }, { depth: null });
18
18
  return;
19
19
  }
20
- transport.send(transport.newPacket({ c: packet.cb(), a: { error: "" + e } }));
20
+ transport.send(transport.newPacket({ c: packet.cb(), a: { error: '' + e } }));
21
21
  };
22
22
  const reply = (arg, packet, transport) => {
23
23
  if (!packet.cb()) {
24
- console.dir({ msg: "cannot reply to packet without cb", arg, packet }, { depth: null });
24
+ console.dir({ msg: 'cannot reply to packet without cb', arg, packet }, { depth: null });
25
25
  return;
26
26
  }
27
27
  transport.send(transport.newPacket({ c: packet.cb(), a: { ...arg } }));
@@ -30,7 +30,7 @@ const unwrap = async (ret, options) => {
30
30
  if (options?.text)
31
31
  return await ret.text();
32
32
  if (options?.base64)
33
- return (await ret.buffer()).toString("base64");
33
+ return (await ret.buffer()).toString('base64');
34
34
  return await ret.json();
35
35
  };
36
36
  class Fetcher {
@@ -57,13 +57,13 @@ class Fetcher {
57
57
  if (retries == null)
58
58
  retries = local.retry;
59
59
  try {
60
- const theURL = `${baseUrl?.endsWith("/") ? baseUrl : baseUrl + "/"}${url}`.replace(/\/\/+/gi, "/");
60
+ const theURL = `${baseUrl?.endsWith('/') ? baseUrl : baseUrl + '/'}${url}`.replace(/\/\/+/gi, '/');
61
61
  await local.customize(options, args);
62
62
  const ret = await fetch(theURL, options);
63
63
  const status = await ret.status;
64
64
  if (status > 399) {
65
65
  const text = await ret.text();
66
- const e = new Error(status + " " + text);
66
+ const e = new Error(status + ' ' + text);
67
67
  e.status = status;
68
68
  throw e;
69
69
  }
@@ -92,14 +92,14 @@ class OAuthFetcher extends Fetcher {
92
92
  return oauth.accessToken();
93
93
  const refreshToken = oauth.refreshToken();
94
94
  if (!refreshToken)
95
- throw new Error("have no access_token and no refresh_token");
95
+ throw new Error('have no access_token and no refresh_token');
96
96
  const ret = await oauth.obtainViaRefreshToken(oauth.refreshToken());
97
97
  if (ret.access_token) {
98
98
  oauth.update(ret.access_token, ret.refresh_token);
99
99
  return ret.access_token;
100
100
  }
101
101
  else {
102
- throw new Error("could not obtain access token via refresh token");
102
+ throw new Error('could not obtain access token via refresh token');
103
103
  }
104
104
  }
105
105
  async onError(e, url, options, retries, args) {
@@ -107,9 +107,7 @@ class OAuthFetcher extends Fetcher {
107
107
  return new Promise((resolve, reject) => {
108
108
  setTimeout(async () => {
109
109
  try {
110
- resolve(await local.fetch(url, options, retries, {
111
- forceTokenRefresh: e.status === 401,
112
- }));
110
+ resolve(await local.fetch(url, options, retries, { forceTokenRefresh: e.status === 401 }));
113
111
  }
114
112
  catch (e) {
115
113
  reject(e);
@@ -165,36 +163,36 @@ class Connector {
165
163
  async run() {
166
164
  var local = this;
167
165
  const makeMetrics = () => {
168
- const metrics = require("prom-client");
166
+ const metrics = require('prom-client');
169
167
  const defaultLabels = {
170
168
  service: local.name,
171
169
  connectorId: local.id,
172
170
  connectorVersion: local.version,
173
- node: process.env.HOSTNAME || "test",
171
+ node: process.env.HOSTNAME || 'test',
174
172
  };
175
173
  metrics.register.setDefaultLabels(defaultLabels);
176
174
  metrics.collectDefaultMetrics();
177
175
  return metrics;
178
176
  };
179
177
  const makeMetricsServer = (metrics) => {
180
- const app = require("express")();
181
- app.get("/metrics", async (request, response, next) => {
178
+ const app = require('express')();
179
+ app.get('/metrics', async (request, response, next) => {
182
180
  response.status(200);
183
- response.set("Content-type", metrics.contentType);
181
+ response.set('Content-type', metrics.contentType);
184
182
  response.send(await metrics.register.metrics());
185
183
  response.end();
186
184
  });
187
185
  return app;
188
186
  };
189
- makeMetricsServer(makeMetrics()).listen(4050, "0.0.0.0");
187
+ makeMetricsServer(makeMetrics()).listen(4050, '0.0.0.0');
190
188
  const { processPacket, start, introspect, configSchema } = this.dispatcher.build();
191
189
  const config = new Config({
192
190
  id: this.id,
193
191
  version: this.version,
194
192
  name: process.env.HOSTNAME || this.name,
195
193
  registrationToken: process.env.REGISTRATION_TOKEN,
196
- endpoint: process.env.DEVICE_ENDPOINT || "https://connect.aloma.io/",
197
- wsEndpoint: process.env.WEBSOCKET_ENDPOINT || "wss://transport.aloma.io/transport/",
194
+ endpoint: process.env.DEVICE_ENDPOINT || 'https://connect.aloma.io/',
195
+ wsEndpoint: process.env.WEBSOCKET_ENDPOINT || 'wss://transport.aloma.io/transport/',
198
196
  privateKey: process.env.PRIVATE_KEY,
199
197
  publicKey: process.env.PUBLIC_KEY,
200
198
  introspect,
@@ -207,15 +205,15 @@ class Connector {
207
205
  catch (e) {
208
206
  const haveKey = !!process.env.PRIVATE_KEY;
209
207
  const jwe = new JWE({});
210
- var text = "Please double check the env variables";
208
+ var text = 'Please double check the env variables';
211
209
  if (!haveKey) {
212
210
  await jwe.newPair();
213
211
  text =
214
- "fresh keys generated, set environment variables: \n\nPRIVATE_KEY: " +
212
+ 'fresh keys generated, set environment variables: \n\nPRIVATE_KEY: ' +
215
213
  (await jwe.exportPrivateAsBase64()) +
216
- "\n\nPUBLIC_KEY: " +
214
+ '\n\nPUBLIC_KEY: ' +
217
215
  (await jwe.exportPublicAsBase64()) +
218
- "\n";
216
+ '\n';
219
217
  }
220
218
  console.log(`
221
219
  Error:
@@ -234,7 +232,7 @@ ${text}
234
232
  const decrypted = {};
235
233
  const fields = configSchema().fields;
236
234
  const keys = Object.keys(secrets);
237
- const jwe = await config.validateKeys("RSA-OAEP-256");
235
+ const jwe = await config.validateKeys('RSA-OAEP-256');
238
236
  for (var i = 0; i < keys.length; ++i) {
239
237
  const key = keys[i];
240
238
  const value = secrets[key];
@@ -248,22 +246,17 @@ ${text}
248
246
  decrypted[key] = await jwe.decrypt(value, config.id());
249
247
  }
250
248
  catch (e) {
251
- console.log("failed to decrypt key", key, config.id(), e);
249
+ console.log('failed to decrypt key', key, config.id(), e);
252
250
  }
253
251
  }
254
252
  }
255
253
  this.startOAuth = async function (args) {
256
254
  if (!this._oauth)
257
- throw new Error("oauth not configured");
258
- const clientId = this._oauth.clientId ||
259
- process.env.OAUTH_CLIENT_ID ||
260
- decrypted.clientId;
255
+ throw new Error('oauth not configured');
256
+ const clientId = this._oauth.clientId || process.env.OAUTH_CLIENT_ID || decrypted.clientId;
261
257
  if (!clientId)
262
- throw new Error("clientId not configured");
263
- const scopes = this._oauth.scope ||
264
- process.env.OAUTH_SCOPE ||
265
- decrypted.scope ||
266
- "";
258
+ throw new Error('clientId not configured');
259
+ const scopes = this._oauth.scope || process.env.OAUTH_SCOPE || decrypted.scope || '';
267
260
  const useCodeChallenge = !!that._oauth.useCodeChallenge;
268
261
  return {
269
262
  url: this._oauth.authorizationURL
@@ -275,23 +268,19 @@ ${text}
275
268
  this.finishOAuth = async function (arg) {
276
269
  var that = this;
277
270
  if (!this._oauth)
278
- throw new Error("oauth not configured");
271
+ throw new Error('oauth not configured');
279
272
  if (!this._oauth.tokenURL && !this._oauth.finishOAuth)
280
- throw new Error("need tokenURL or finishOAuth(arg)");
273
+ throw new Error('need tokenURL or finishOAuth(arg)');
281
274
  var data = null;
282
275
  const doFinish = async () => {
283
276
  if (!arg.code || !arg.redirectURI)
284
- throw new Error("need code and redirectUri");
285
- const clientId = that._oauth.clientId ||
286
- process.env.OAUTH_CLIENT_ID ||
287
- decrypted.clientId;
277
+ throw new Error('need code and redirectUri');
278
+ const clientId = that._oauth.clientId || process.env.OAUTH_CLIENT_ID || decrypted.clientId;
288
279
  if (!clientId)
289
- throw new Error("clientId not configured");
290
- const clientSecret = that._oauth.clientSecret ||
291
- process.env.OAUTH_CLIENT_SECRET ||
292
- decrypted.clientSecret;
280
+ throw new Error('clientId not configured');
281
+ const clientSecret = that._oauth.clientSecret || process.env.OAUTH_CLIENT_SECRET || decrypted.clientSecret;
293
282
  if (!clientSecret)
294
- throw new Error("clientSecret not configured");
283
+ throw new Error('clientSecret not configured');
295
284
  const additionalTokenArgs = that._oauth.additionalTokenArgs || {};
296
285
  const useAuthHeader = !!that._oauth.useAuthHeader;
297
286
  const useCodeChallenge = !!that._oauth.useCodeChallenge;
@@ -304,8 +293,8 @@ ${text}
304
293
  body.code_verifier = arg.codeVerifier;
305
294
  }
306
295
  let headers = {
307
- "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
308
- Accept: "application/json",
296
+ 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
297
+ Accept: 'application/json',
309
298
  };
310
299
  if (useAuthHeader) {
311
300
  headers = {
@@ -321,7 +310,7 @@ ${text}
321
310
  };
322
311
  }
323
312
  const response = await fetch(that._oauth.tokenURL, {
324
- method: "POST",
313
+ method: 'POST',
325
314
  body: new URLSearchParams(body),
326
315
  headers,
327
316
  });
@@ -330,17 +319,17 @@ ${text}
330
319
  if (status === 200) {
331
320
  const ret = JSON.parse(text);
332
321
  if (ret.error) {
333
- throw new Error(`${status} ${ret.error} ${ret.error_description || ""}`);
322
+ throw new Error(`${status} ${ret.error} ${ret.error_description || ''}`);
334
323
  }
335
324
  else if (ret.access_token) {
336
325
  return { ...ret };
337
326
  }
338
327
  else {
339
- throw new Error(status + " response has no access_token - " + text);
328
+ throw new Error(status + ' response has no access_token - ' + text);
340
329
  }
341
330
  }
342
331
  else {
343
- throw new Error(status + " " + text);
332
+ throw new Error(status + ' ' + text);
344
333
  }
345
334
  };
346
335
  if (this._oauth.finishOAuth) {
@@ -353,30 +342,26 @@ ${text}
353
342
  else {
354
343
  data = await doFinish();
355
344
  }
356
- const jwe = await config.validateKeys("RSA-OAEP-256");
357
- return { value: await jwe.encrypt(data, "none", config.id()) };
345
+ const jwe = await config.validateKeys('RSA-OAEP-256');
346
+ return { value: await jwe.encrypt(data, 'none', config.id()) };
358
347
  };
359
348
  const saveOAuthResult = async (what) => {
360
- const jwe = await config.validateKeys("RSA-OAEP-256");
349
+ const jwe = await config.validateKeys('RSA-OAEP-256');
361
350
  const packet = transport.newPacket({});
362
- packet.method("connector.config-update");
351
+ packet.method('connector.config-update');
363
352
  packet.args({
364
- value: await jwe.encrypt(what, "none", config.id()),
353
+ value: await jwe.encrypt(what, 'none', config.id()),
365
354
  });
366
355
  transport.send(packet);
367
356
  };
368
357
  const that = this;
369
358
  const getRefreshToken = async (refreshToken) => {
370
- const clientId = that._oauth.clientId ||
371
- process.env.OAUTH_CLIENT_ID ||
372
- decrypted.clientId;
359
+ const clientId = that._oauth.clientId || process.env.OAUTH_CLIENT_ID || decrypted.clientId;
373
360
  if (!clientId)
374
- throw new Error("clientId not configured");
375
- const clientSecret = that._oauth.clientSecret ||
376
- process.env.OAUTH_CLIENT_SECRET ||
377
- decrypted.clientSecret;
361
+ throw new Error('clientId not configured');
362
+ const clientSecret = that._oauth.clientSecret || process.env.OAUTH_CLIENT_SECRET || decrypted.clientSecret;
378
363
  if (!clientSecret)
379
- throw new Error("clientSecret not configured");
364
+ throw new Error('clientSecret not configured');
380
365
  const useAuthHeader = !!that._oauth.useAuthHeader;
381
366
  let headers = {};
382
367
  if (useAuthHeader) {
@@ -386,16 +371,16 @@ ${text}
386
371
  };
387
372
  }
388
373
  const response = await fetch(that._oauth.tokenURL, {
389
- method: "POST",
374
+ method: 'POST',
390
375
  body: new URLSearchParams({
391
- grant_type: "refresh_token",
376
+ grant_type: 'refresh_token',
392
377
  refresh_token: refreshToken,
393
378
  client_id: clientId,
394
379
  client_secret: clientSecret,
395
380
  }),
396
381
  headers: {
397
- "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
398
- Accept: "application/json",
382
+ 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
383
+ Accept: 'application/json',
399
384
  ...headers,
400
385
  },
401
386
  });
@@ -405,7 +390,7 @@ ${text}
405
390
  return JSON.parse(text);
406
391
  }
407
392
  else {
408
- throw new Error("could not get refresh token " + status + " " + text);
393
+ throw new Error('could not get refresh token ' + status + ' ' + text);
409
394
  }
410
395
  };
411
396
  const theOAuth = decrypted.oauthResult
@@ -414,11 +399,11 @@ ${text}
414
399
  start({
415
400
  config: decrypted,
416
401
  oauth: theOAuth,
417
- getClient: (arg) => theOAuth ? theOAuth.getClient(arg) : new Fetcher({ ...arg }),
402
+ getClient: (arg) => (theOAuth ? theOAuth.getClient(arg) : new Fetcher({ ...arg })),
418
403
  newTask: (name, data) => {
419
404
  return new Promise((resolve, reject) => {
420
405
  const packet = transport.newPacket({}, (ret) => (ret?.error ? reject(ret.error) : resolve(ret)), `_req-${cuid()}`);
421
- packet.method("connector.task.new");
406
+ packet.method('connector.task.new');
422
407
  packet.args({
423
408
  name,
424
409
  a: data,
@@ -429,7 +414,7 @@ ${text}
429
414
  updateTask: (id, data) => {
430
415
  return new Promise((resolve, reject) => {
431
416
  const packet = transport.newPacket({}, (ret) => (ret?.error ? reject(ret.error) : resolve(ret)), `_req-${cuid()}`);
432
- packet.method("connector.task.update");
417
+ packet.method('connector.task.update');
433
418
  packet.args({
434
419
  id,
435
420
  a: data,
@@ -462,14 +447,14 @@ ${text}
462
447
  });
463
448
  process.exit(0);
464
449
  };
465
- process.on("uncaughtException", (e) => {
450
+ process.on('uncaughtException', (e) => {
466
451
  console.log(e);
467
452
  });
468
- process.on("unhandledRejection", (e) => {
453
+ process.on('unhandledRejection', (e) => {
469
454
  console.log(e);
470
455
  });
471
- process.on("SIGTERM", term);
472
- process.on("SIGINT", term);
456
+ process.on('SIGTERM', term);
457
+ process.on('SIGINT', term);
473
458
  await server.start();
474
459
  }
475
460
  }
@@ -1,12 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const JWE = require("./index");
3
+ const JWE = require('./index');
4
4
  const main = async () => {
5
5
  const jwe = new JWE({});
6
6
  await jwe.newPair();
7
- console.log("private key");
7
+ console.log('private key');
8
8
  console.log(await jwe.exportPrivateAsBase64());
9
- console.log("public key");
9
+ console.log('public key');
10
10
  console.log(await jwe.exportPublicAsBase64());
11
11
  };
12
12
  setTimeout(() => null, 100);
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const jose = require("jose");
3
+ const jose = require('jose');
4
4
  class JWE {
5
- constructor({ algorithm = "PS256" }) {
6
- this.issuer = "home.aloma.io";
5
+ constructor({ algorithm = 'PS256' }) {
6
+ this.issuer = 'home.aloma.io';
7
7
  this.algorithm = algorithm;
8
8
  }
9
9
  async newPair() {
@@ -17,11 +17,11 @@ class JWE {
17
17
  }
18
18
  async exportPrivateAsBase64() {
19
19
  const pair = await this.exportPair();
20
- return Buffer.from(pair.privateKey).toString("base64");
20
+ return Buffer.from(pair.privateKey).toString('base64');
21
21
  }
22
22
  async exportPublicAsBase64() {
23
23
  const pair = await this.exportPair();
24
- return Buffer.from(pair.publicKey).toString("base64");
24
+ return Buffer.from(pair.publicKey).toString('base64');
25
25
  }
26
26
  async importPair({ publicKey, privateKey, algorithm }) {
27
27
  this.pair = {
@@ -31,18 +31,18 @@ class JWE {
31
31
  }
32
32
  async importBase64Pair({ publicKey, privateKey, algorithm }) {
33
33
  this.importPair({
34
- publicKey: Buffer.from(publicKey, "base64").toString(),
35
- privateKey: Buffer.from(privateKey, "base64").toString(),
34
+ publicKey: Buffer.from(publicKey, 'base64').toString(),
35
+ privateKey: Buffer.from(privateKey, 'base64').toString(),
36
36
  algorithm,
37
37
  });
38
38
  }
39
- async encrypt(what, expiration = "7d", audience, algorithm = "RSA-OAEP-256") {
39
+ async encrypt(what, expiration = '7d', audience, algorithm = 'RSA-OAEP-256') {
40
40
  const item = new jose.EncryptJWT({ _data: { ...what } })
41
- .setProtectedHeader({ alg: algorithm, enc: "A256GCM" })
41
+ .setProtectedHeader({ alg: algorithm, enc: 'A256GCM' })
42
42
  .setIssuedAt()
43
43
  .setIssuer(this.issuer)
44
44
  .setAudience(audience);
45
- if (expiration && expiration !== "none")
45
+ if (expiration && expiration !== 'none')
46
46
  item.setExpirationTime(expiration);
47
47
  return await item.encrypt(this.pair.publicKey);
48
48
  }
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const C = require("./connection/constants.cjs");
4
- const JWE = require("../util/jwe/index.cjs");
3
+ const C = require('./connection/constants.cjs');
4
+ const JWE = require('../util/jwe/index.cjs');
5
5
  class Config {
6
6
  constructor({ registrationToken, version, name, id, endpoint, wsEndpoint, privateKey, publicKey, introspect, configSchema, }) {
7
7
  this._token = null;
@@ -18,17 +18,17 @@ class Config {
18
18
  this._introspect = introspect;
19
19
  this._configSchema = configSchema;
20
20
  if (!registrationToken)
21
- throw new Error("empty registration token (set env.REGISTRATION_TOKEN)");
21
+ throw new Error('empty registration token (set env.REGISTRATION_TOKEN)');
22
22
  if (!endpoint)
23
- throw new Error("empty endpoint (set env.DEVICE_ENDPOINT)");
23
+ throw new Error('empty endpoint (set env.DEVICE_ENDPOINT)');
24
24
  if (!wsEndpoint)
25
- throw new Error("empty registration token (set env.WEBSOCKET_ENDPOINT)");
25
+ throw new Error('empty registration token (set env.WEBSOCKET_ENDPOINT)');
26
26
  if (!this._id || !this._version)
27
- throw new Error("need connector id and version");
27
+ throw new Error('need connector id and version');
28
28
  }
29
29
  async validateKeys(algorithm) {
30
30
  if (!this._privateKey || !this._publicKey)
31
- throw new Error("need private and public key");
31
+ throw new Error('need private and public key');
32
32
  await this._jwe.importBase64Pair({
33
33
  publicKey: this._publicKey,
34
34
  privateKey: this._privateKey,
@@ -1,11 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const AUTHORIZATION = "Authorization";
3
+ const AUTHORIZATION = 'Authorization';
4
4
  module.exports = {
5
5
  augmentRequest: (what, config) => {
6
6
  what.headers = {
7
7
  ...what.headers,
8
- "User-Agent": config.id() + "/" + config.version(),
8
+ 'User-Agent': config.id() + '/' + config.version(),
9
9
  };
10
10
  what.headers[AUTHORIZATION] = `Connector ${config.token()}`;
11
11
  return what;
@@ -13,7 +13,7 @@ module.exports = {
13
13
  augmentRegistration: (what, config) => {
14
14
  what.headers = {
15
15
  ...what.headers,
16
- "User-Agent": config.id() + "/" + config.version(),
16
+ 'User-Agent': config.id() + '/' + config.version(),
17
17
  };
18
18
  what.headers[AUTHORIZATION] = `Connector ${config.registrationToken()}`;
19
19
  return what;
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const fetch = require("node-fetch");
4
- const { Registration } = require("./registration.cjs");
5
- const C = require("./constants.cjs");
3
+ const fetch = require('node-fetch');
4
+ const { Registration } = require('./registration.cjs');
5
+ const C = require('./constants.cjs');
6
6
  class Connection {
7
7
  constructor({ config, onStart }) {
8
8
  this.config = config;
@@ -11,10 +11,10 @@ class Connection {
11
11
  async start() {
12
12
  var local = this, config = local.config;
13
13
  try {
14
- const response = await fetch(config.url() + "connect", C.augmentRequest({
15
- method: "POST",
14
+ const response = await fetch(config.url() + 'connect', C.augmentRequest({
15
+ method: 'POST',
16
16
  body: JSON.stringify({}),
17
- headers: { "Content-Type": "application/json" },
17
+ headers: { 'Content-Type': 'application/json' },
18
18
  }, config));
19
19
  if (response.status === 401) {
20
20
  config.setToken(await new Registration(local.config).run());
@@ -39,10 +39,10 @@ class Connection {
39
39
  }
40
40
  async close() {
41
41
  try {
42
- await fetch(this.config.url() + "disconnect", C.augmentRequest({
43
- method: "POST",
42
+ await fetch(this.config.url() + 'disconnect', C.augmentRequest({
43
+ method: 'POST',
44
44
  body: JSON.stringify({}),
45
- headers: { "Content-Type": "application/json" },
45
+ headers: { 'Content-Type': 'application/json' },
46
46
  }, this.config));
47
47
  }
48
48
  catch (e) {
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const fetch = require("node-fetch");
4
- const C = require("./constants.cjs");
3
+ const fetch = require('node-fetch');
4
+ const C = require('./constants.cjs');
5
5
  class Registration {
6
6
  constructor(config) {
7
7
  this.config = config;
@@ -11,21 +11,21 @@ class Registration {
11
11
  const config = this.config;
12
12
  const configSchema = config.configSchema();
13
13
  const intro = await config.introspect();
14
- const response = await fetch(config.url() + "register", C.augmentRegistration({
15
- method: "POST",
14
+ const response = await fetch(config.url() + 'register', C.augmentRegistration({
15
+ method: 'POST',
16
16
  body: JSON.stringify({
17
- deployment: process.env.DEPLOYMENT || "",
17
+ deployment: process.env.DEPLOYMENT || '',
18
18
  name: config.name(),
19
19
  version: config.version(),
20
20
  id: config.id(),
21
21
  publicKey: config.publicKey(),
22
22
  schema: { configSchema, introspect: intro },
23
23
  }),
24
- headers: { "Content-Type": "application/json" },
24
+ headers: { 'Content-Type': 'application/json' },
25
25
  }, config));
26
26
  if (response.status === 200)
27
27
  return (await response.json()).key;
28
- throw new Error("authentication failed");
28
+ throw new Error('authentication failed');
29
29
  }
30
30
  }
31
31
  module.exports = { Registration };
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const WebSocket = require("ws");
4
- const { Connection } = require("./connection/index.cjs");
5
- const { Transport } = require("./transport/index.cjs");
3
+ const WebSocket = require('ws');
4
+ const { Connection } = require('./connection/index.cjs');
5
+ const { Transport } = require('./transport/index.cjs');
6
6
  class WebsocketConnector {
7
7
  constructor({ config, onMessage, onConnect }) {
8
8
  var local = this;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const WebSocket = require("ws");
3
+ const WebSocket = require('ws');
4
4
  class DurableWebsocket {
5
5
  constructor({ endpoint, secret, onConnect, onMessage }) {
6
6
  this.endpoint = endpoint;
@@ -28,7 +28,7 @@ class DurableWebsocket {
28
28
  rejectUnauthorized: false,
29
29
  headers: { Authorization: `Bearer ${local.secret}` },
30
30
  }));
31
- ws.on("open", () => {
31
+ ws.on('open', () => {
32
32
  local.connecting = false;
33
33
  local.fails = 0;
34
34
  var item;
@@ -37,15 +37,15 @@ class DurableWebsocket {
37
37
  }
38
38
  local.onConnect(local);
39
39
  });
40
- ws.on("message", (message) => {
40
+ ws.on('message', (message) => {
41
41
  setImmediate(() => local.onMessage(JSON.parse(message)));
42
42
  });
43
- ws.on("error", (message) => {
43
+ ws.on('error', (message) => {
44
44
  if (local.fails > 50)
45
- console.log("error:", message.message);
45
+ console.log('error:', message.message);
46
46
  ++local.fails;
47
47
  });
48
- ws.on("close", (message) => {
48
+ ws.on('close', (message) => {
49
49
  local.connecting = false;
50
50
  if (!local.closed)
51
51
  setTimeout(() => local.start(), 5000);