@aloma.io/integration-sdk 3.0.1-4 → 3.0.1-6

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 (49) hide show
  1. package/build/builder/index.d.mts +1 -1
  2. package/build/builder/index.mjs +15 -11
  3. package/build/builder/runtime-context.d.mts +1 -1
  4. package/build/builder/runtime-context.mjs +10 -7
  5. package/build/builder/transform/index.mjs +18 -18
  6. package/build/cli.mjs +26 -19
  7. package/build/controller/index.mjs +5 -5
  8. package/build/index.d.mts +2 -2
  9. package/build/index.mjs +2 -2
  10. package/build/internal/dispatcher/index.cjs +41 -30
  11. package/build/internal/index.cjs +86 -71
  12. package/build/internal/util/jwe/cli.cjs +3 -3
  13. package/build/internal/util/jwe/index.cjs +10 -10
  14. package/build/internal/websocket/config.cjs +7 -7
  15. package/build/internal/websocket/connection/constants.cjs +3 -3
  16. package/build/internal/websocket/connection/index.cjs +9 -9
  17. package/build/internal/websocket/connection/registration.cjs +7 -7
  18. package/build/internal/websocket/index.cjs +3 -3
  19. package/build/internal/websocket/transport/durable.cjs +6 -6
  20. package/build/internal/websocket/transport/index.cjs +18 -18
  21. package/build/internal/websocket/transport/packet.cjs +2 -2
  22. package/build/internal/websocket/transport/processor.cjs +5 -5
  23. package/package.json +1 -1
  24. package/src/builder/index.mts +26 -19
  25. package/src/builder/runtime-context.mts +31 -21
  26. package/src/builder/transform/index.mts +24 -19
  27. package/src/cli.mts +45 -43
  28. package/src/controller/index.mts +13 -7
  29. package/src/index.mts +2 -2
  30. package/src/internal/dispatcher/index.cjs +61 -44
  31. package/src/internal/index.cjs +125 -84
  32. package/src/internal/util/jwe/cli.cjs +3 -3
  33. package/src/internal/util/jwe/index.cjs +21 -17
  34. package/src/internal/websocket/config.cjs +12 -8
  35. package/src/internal/websocket/connection/constants.cjs +3 -3
  36. package/src/internal/websocket/connection/index.cjs +11 -11
  37. package/src/internal/websocket/connection/registration.cjs +9 -9
  38. package/src/internal/websocket/index.cjs +6 -6
  39. package/src/internal/websocket/transport/durable.cjs +9 -9
  40. package/src/internal/websocket/transport/index.cjs +30 -26
  41. package/src/internal/websocket/transport/packet.cjs +4 -4
  42. package/src/internal/websocket/transport/processor.cjs +12 -9
  43. package/template/connector/Containerfile +18 -0
  44. package/template/connector/entrypoint.sh +5 -0
  45. package/template/connector/package.json +7 -30
  46. package/template/connector/src/controller/index.mts +12 -0
  47. package/template/connector/src/index.mts +6 -0
  48. package/template/connector/tsconfig.json +27 -0
  49. package/template/connector/src/index.mjs +0 -1
@@ -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,7 +107,9 @@ 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, { forceTokenRefresh: e.status === 401 }));
110
+ resolve(await local.fetch(url, options, retries, {
111
+ forceTokenRefresh: e.status === 401,
112
+ }));
111
113
  }
112
114
  catch (e) {
113
115
  reject(e);
@@ -163,36 +165,36 @@ class Connector {
163
165
  async run() {
164
166
  var local = this;
165
167
  const makeMetrics = () => {
166
- const metrics = require('prom-client');
168
+ const metrics = require("prom-client");
167
169
  const defaultLabels = {
168
170
  service: local.name,
169
171
  connectorId: local.id,
170
172
  connectorVersion: local.version,
171
- node: process.env.HOSTNAME || 'test',
173
+ node: process.env.HOSTNAME || "test",
172
174
  };
173
175
  metrics.register.setDefaultLabels(defaultLabels);
174
176
  metrics.collectDefaultMetrics();
175
177
  return metrics;
176
178
  };
177
179
  const makeMetricsServer = (metrics) => {
178
- const app = require('express')();
179
- app.get('/metrics', async (request, response, next) => {
180
+ const app = require("express")();
181
+ app.get("/metrics", async (request, response, next) => {
180
182
  response.status(200);
181
- response.set('Content-type', metrics.contentType);
183
+ response.set("Content-type", metrics.contentType);
182
184
  response.send(await metrics.register.metrics());
183
185
  response.end();
184
186
  });
185
187
  return app;
186
188
  };
187
- makeMetricsServer(makeMetrics()).listen(4050, '0.0.0.0');
189
+ makeMetricsServer(makeMetrics()).listen(4050, "0.0.0.0");
188
190
  const { processPacket, start, introspect, configSchema } = this.dispatcher.build();
189
191
  const config = new Config({
190
192
  id: this.id,
191
193
  version: this.version,
192
194
  name: process.env.HOSTNAME || this.name,
193
195
  registrationToken: process.env.REGISTRATION_TOKEN,
194
- endpoint: process.env.DEVICE_ENDPOINT || 'https://connect.aloma.io/',
195
- wsEndpoint: process.env.WEBSOCKET_ENDPOINT || 'wss://transport.aloma.io/transport/',
196
+ endpoint: process.env.DEVICE_ENDPOINT || "https://connect.aloma.io/",
197
+ wsEndpoint: process.env.WEBSOCKET_ENDPOINT || "wss://transport.aloma.io/transport/",
196
198
  privateKey: process.env.PRIVATE_KEY,
197
199
  publicKey: process.env.PUBLIC_KEY,
198
200
  introspect,
@@ -205,15 +207,15 @@ class Connector {
205
207
  catch (e) {
206
208
  const haveKey = !!process.env.PRIVATE_KEY;
207
209
  const jwe = new JWE({});
208
- var text = 'Please double check the env variables';
210
+ var text = "Please double check the env variables";
209
211
  if (!haveKey) {
210
212
  await jwe.newPair();
211
213
  text =
212
- 'fresh keys generated, set environment variables: \n\nPRIVATE_KEY: ' +
214
+ "fresh keys generated, set environment variables: \n\nPRIVATE_KEY: " +
213
215
  (await jwe.exportPrivateAsBase64()) +
214
- '\n\nPUBLIC_KEY: ' +
216
+ "\n\nPUBLIC_KEY: " +
215
217
  (await jwe.exportPublicAsBase64()) +
216
- '\n';
218
+ "\n";
217
219
  }
218
220
  console.log(`
219
221
  Error:
@@ -232,7 +234,7 @@ ${text}
232
234
  const decrypted = {};
233
235
  const fields = configSchema().fields;
234
236
  const keys = Object.keys(secrets);
235
- const jwe = await config.validateKeys('RSA-OAEP-256');
237
+ const jwe = await config.validateKeys("RSA-OAEP-256");
236
238
  for (var i = 0; i < keys.length; ++i) {
237
239
  const key = keys[i];
238
240
  const value = secrets[key];
@@ -246,17 +248,22 @@ ${text}
246
248
  decrypted[key] = await jwe.decrypt(value, config.id());
247
249
  }
248
250
  catch (e) {
249
- console.log('failed to decrypt key', key, config.id(), e);
251
+ console.log("failed to decrypt key", key, config.id(), e);
250
252
  }
251
253
  }
252
254
  }
253
255
  this.startOAuth = async function (args) {
254
256
  if (!this._oauth)
255
- throw new Error('oauth not configured');
256
- const clientId = this._oauth.clientId || process.env.OAUTH_CLIENT_ID || decrypted.clientId;
257
+ throw new Error("oauth not configured");
258
+ const clientId = this._oauth.clientId ||
259
+ process.env.OAUTH_CLIENT_ID ||
260
+ decrypted.clientId;
257
261
  if (!clientId)
258
- throw new Error('clientId not configured');
259
- const scopes = this._oauth.scope || process.env.OAUTH_SCOPE || decrypted.scope || '';
262
+ throw new Error("clientId not configured");
263
+ const scopes = this._oauth.scope ||
264
+ process.env.OAUTH_SCOPE ||
265
+ decrypted.scope ||
266
+ "";
260
267
  const useCodeChallenge = !!that._oauth.useCodeChallenge;
261
268
  return {
262
269
  url: this._oauth.authorizationURL
@@ -268,19 +275,23 @@ ${text}
268
275
  this.finishOAuth = async function (arg) {
269
276
  var that = this;
270
277
  if (!this._oauth)
271
- throw new Error('oauth not configured');
278
+ throw new Error("oauth not configured");
272
279
  if (!this._oauth.tokenURL && !this._oauth.finishOAuth)
273
- throw new Error('need tokenURL or finishOAuth(arg)');
280
+ throw new Error("need tokenURL or finishOAuth(arg)");
274
281
  var data = null;
275
282
  const doFinish = async () => {
276
283
  if (!arg.code || !arg.redirectURI)
277
- throw new Error('need code and redirectUri');
278
- const clientId = that._oauth.clientId || process.env.OAUTH_CLIENT_ID || decrypted.clientId;
284
+ throw new Error("need code and redirectUri");
285
+ const clientId = that._oauth.clientId ||
286
+ process.env.OAUTH_CLIENT_ID ||
287
+ decrypted.clientId;
279
288
  if (!clientId)
280
- throw new Error('clientId not configured');
281
- const clientSecret = that._oauth.clientSecret || process.env.OAUTH_CLIENT_SECRET || decrypted.clientSecret;
289
+ throw new Error("clientId not configured");
290
+ const clientSecret = that._oauth.clientSecret ||
291
+ process.env.OAUTH_CLIENT_SECRET ||
292
+ decrypted.clientSecret;
282
293
  if (!clientSecret)
283
- throw new Error('clientSecret not configured');
294
+ throw new Error("clientSecret not configured");
284
295
  const additionalTokenArgs = that._oauth.additionalTokenArgs || {};
285
296
  const useAuthHeader = !!that._oauth.useAuthHeader;
286
297
  const useCodeChallenge = !!that._oauth.useCodeChallenge;
@@ -293,8 +304,8 @@ ${text}
293
304
  body.code_verifier = arg.codeVerifier;
294
305
  }
295
306
  let headers = {
296
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
297
- Accept: 'application/json',
307
+ "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
308
+ Accept: "application/json",
298
309
  };
299
310
  if (useAuthHeader) {
300
311
  headers = {
@@ -310,7 +321,7 @@ ${text}
310
321
  };
311
322
  }
312
323
  const response = await fetch(that._oauth.tokenURL, {
313
- method: 'POST',
324
+ method: "POST",
314
325
  body: new URLSearchParams(body),
315
326
  headers,
316
327
  });
@@ -319,17 +330,17 @@ ${text}
319
330
  if (status === 200) {
320
331
  const ret = JSON.parse(text);
321
332
  if (ret.error) {
322
- throw new Error(`${status} ${ret.error} ${ret.error_description || ''}`);
333
+ throw new Error(`${status} ${ret.error} ${ret.error_description || ""}`);
323
334
  }
324
335
  else if (ret.access_token) {
325
336
  return { ...ret };
326
337
  }
327
338
  else {
328
- throw new Error(status + ' response has no access_token - ' + text);
339
+ throw new Error(status + " response has no access_token - " + text);
329
340
  }
330
341
  }
331
342
  else {
332
- throw new Error(status + ' ' + text);
343
+ throw new Error(status + " " + text);
333
344
  }
334
345
  };
335
346
  if (this._oauth.finishOAuth) {
@@ -342,26 +353,30 @@ ${text}
342
353
  else {
343
354
  data = await doFinish();
344
355
  }
345
- const jwe = await config.validateKeys('RSA-OAEP-256');
346
- return { value: await jwe.encrypt(data, 'none', config.id()) };
356
+ const jwe = await config.validateKeys("RSA-OAEP-256");
357
+ return { value: await jwe.encrypt(data, "none", config.id()) };
347
358
  };
348
359
  const saveOAuthResult = async (what) => {
349
- const jwe = await config.validateKeys('RSA-OAEP-256');
360
+ const jwe = await config.validateKeys("RSA-OAEP-256");
350
361
  const packet = transport.newPacket({});
351
- packet.method('connector.config-update');
362
+ packet.method("connector.config-update");
352
363
  packet.args({
353
- value: await jwe.encrypt(what, 'none', config.id()),
364
+ value: await jwe.encrypt(what, "none", config.id()),
354
365
  });
355
366
  transport.send(packet);
356
367
  };
357
368
  const that = this;
358
369
  const getRefreshToken = async (refreshToken) => {
359
- const clientId = that._oauth.clientId || process.env.OAUTH_CLIENT_ID || decrypted.clientId;
370
+ const clientId = that._oauth.clientId ||
371
+ process.env.OAUTH_CLIENT_ID ||
372
+ decrypted.clientId;
360
373
  if (!clientId)
361
- throw new Error('clientId not configured');
362
- const clientSecret = that._oauth.clientSecret || process.env.OAUTH_CLIENT_SECRET || decrypted.clientSecret;
374
+ throw new Error("clientId not configured");
375
+ const clientSecret = that._oauth.clientSecret ||
376
+ process.env.OAUTH_CLIENT_SECRET ||
377
+ decrypted.clientSecret;
363
378
  if (!clientSecret)
364
- throw new Error('clientSecret not configured');
379
+ throw new Error("clientSecret not configured");
365
380
  const useAuthHeader = !!that._oauth.useAuthHeader;
366
381
  let headers = {};
367
382
  if (useAuthHeader) {
@@ -371,16 +386,16 @@ ${text}
371
386
  };
372
387
  }
373
388
  const response = await fetch(that._oauth.tokenURL, {
374
- method: 'POST',
389
+ method: "POST",
375
390
  body: new URLSearchParams({
376
- grant_type: 'refresh_token',
391
+ grant_type: "refresh_token",
377
392
  refresh_token: refreshToken,
378
393
  client_id: clientId,
379
394
  client_secret: clientSecret,
380
395
  }),
381
396
  headers: {
382
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
383
- Accept: 'application/json',
397
+ "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
398
+ Accept: "application/json",
384
399
  ...headers,
385
400
  },
386
401
  });
@@ -390,7 +405,7 @@ ${text}
390
405
  return JSON.parse(text);
391
406
  }
392
407
  else {
393
- throw new Error('could not get refresh token ' + status + ' ' + text);
408
+ throw new Error("could not get refresh token " + status + " " + text);
394
409
  }
395
410
  };
396
411
  const theOAuth = decrypted.oauthResult
@@ -399,11 +414,11 @@ ${text}
399
414
  start({
400
415
  config: decrypted,
401
416
  oauth: theOAuth,
402
- getClient: (arg) => (theOAuth ? theOAuth.getClient(arg) : new Fetcher({ ...arg })),
417
+ getClient: (arg) => theOAuth ? theOAuth.getClient(arg) : new Fetcher({ ...arg }),
403
418
  newTask: (name, data) => {
404
419
  return new Promise((resolve, reject) => {
405
420
  const packet = transport.newPacket({}, (ret) => (ret?.error ? reject(ret.error) : resolve(ret)), `_req-${cuid()}`);
406
- packet.method('connector.task.new');
421
+ packet.method("connector.task.new");
407
422
  packet.args({
408
423
  name,
409
424
  a: data,
@@ -414,7 +429,7 @@ ${text}
414
429
  updateTask: (id, data) => {
415
430
  return new Promise((resolve, reject) => {
416
431
  const packet = transport.newPacket({}, (ret) => (ret?.error ? reject(ret.error) : resolve(ret)), `_req-${cuid()}`);
417
- packet.method('connector.task.update');
432
+ packet.method("connector.task.update");
418
433
  packet.args({
419
434
  id,
420
435
  a: data,
@@ -447,14 +462,14 @@ ${text}
447
462
  });
448
463
  process.exit(0);
449
464
  };
450
- process.on('uncaughtException', (e) => {
465
+ process.on("uncaughtException", (e) => {
451
466
  console.log(e);
452
467
  });
453
- process.on('unhandledRejection', (e) => {
468
+ process.on("unhandledRejection", (e) => {
454
469
  console.log(e);
455
470
  });
456
- process.on('SIGTERM', term);
457
- process.on('SIGINT', term);
471
+ process.on("SIGTERM", term);
472
+ process.on("SIGINT", term);
458
473
  await server.start();
459
474
  }
460
475
  }
@@ -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);