@niledatabase/server 1.0.0 → 2.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.
@@ -2,10 +2,12 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var syncFetch = require('sync-fetch');
6
+ require('dotenv/config');
5
7
  var isEmpty = require('lodash/isEmpty');
6
8
  var isObject = require('lodash/isObject');
7
9
  var jose = require('jose');
8
- var knex = require('knex');
10
+ var pg = require('pg');
9
11
 
10
12
  function _regeneratorRuntime() {
11
13
  _regeneratorRuntime = function () {
@@ -395,6 +397,18 @@ function _setPrototypeOf(o, p) {
395
397
  };
396
398
  return _setPrototypeOf(o, p);
397
399
  }
400
+ function _objectWithoutPropertiesLoose(source, excluded) {
401
+ if (source == null) return {};
402
+ var target = {};
403
+ var sourceKeys = Object.keys(source);
404
+ var key, i;
405
+ for (i = 0; i < sourceKeys.length; i++) {
406
+ key = sourceKeys[i];
407
+ if (excluded.indexOf(key) >= 0) continue;
408
+ target[key] = source[key];
409
+ }
410
+ return target;
411
+ }
398
412
  function _unsupportedIterableToArray(o, minLen) {
399
413
  if (!o) return;
400
414
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
@@ -427,6 +441,189 @@ function _createForOfIteratorHelperLoose(o, allowArrayLike) {
427
441
  throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
428
442
  }
429
443
 
444
+ function Logger(config) {
445
+ for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
446
+ params[_key - 1] = arguments[_key];
447
+ }
448
+ return {
449
+ info: function info() {
450
+ if (config != null && config.debug) {
451
+ var _console;
452
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
453
+ args[_key2] = arguments[_key2];
454
+ }
455
+ // eslint-disable-next-line no-console
456
+ (_console = console).info.apply(_console, ['[niledb]'].concat(params, args));
457
+ }
458
+ },
459
+ warn: function warn() {
460
+ if (config != null && config.debug) {
461
+ var _console2;
462
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
463
+ args[_key3] = arguments[_key3];
464
+ }
465
+ // eslint-disable-next-line no-console
466
+ (_console2 = console).warn.apply(_console2, ['[niledb]'].concat(params, args));
467
+ }
468
+ },
469
+ error: function error() {
470
+ if (config != null && config.debug) {
471
+ var _console3;
472
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
473
+ args[_key4] = arguments[_key4];
474
+ }
475
+ // eslint-disable-next-line no-console
476
+ (_console3 = console).error.apply(_console3, ['[niledb]', '[ERROR]'].concat(params, args));
477
+ }
478
+ }
479
+ };
480
+ }
481
+
482
+ var getDatbaseId = function getDatbaseId(cfg) {
483
+ var config = cfg.config,
484
+ logger = cfg.logger;
485
+ var _Logger = Logger(config, '[databaseId]'),
486
+ info = _Logger.info;
487
+ if (config != null && config.databaseId) {
488
+ logger && info(logger, 'config', config.databaseId);
489
+ return String(config == null ? void 0 : config.databaseId);
490
+ }
491
+ logger && info(logger, 'env', process.env.NILEDB_ID);
492
+ return process.env.NILEDB_ID;
493
+ };
494
+ var getUsername = function getUsername(cfg) {
495
+ var config = cfg.config,
496
+ logger = cfg.logger;
497
+ var _Logger2 = Logger(config, '[username]'),
498
+ info = _Logger2.info;
499
+ if (config != null && config.user) {
500
+ logger && info(logger, 'config', config.user);
501
+ return String(config == null ? void 0 : config.user);
502
+ }
503
+ logger && info(logger, '.env', process.env.NILEDB_USER);
504
+ return process.env.NILEDB_USER;
505
+ };
506
+ var getPassword = function getPassword(cfg) {
507
+ var config = cfg.config,
508
+ logger = cfg.logger;
509
+ var log = logProtector(logger);
510
+ var _Logger3 = Logger(config, '[password]'),
511
+ info = _Logger3.info;
512
+ if (config != null && config.password) {
513
+ log && info(logger, 'config', config.password);
514
+ return String(config.password);
515
+ }
516
+ log && info(logger, '.env', process.env.NILEDB_PASSWORD);
517
+ return process.env.NILEDB_PASSWORD;
518
+ };
519
+ var getInfoBearer = function getInfoBearer(cfg) {
520
+ return getUsername(cfg) + ":" + getPassword(cfg);
521
+ };
522
+ var getToken = function getToken(cfg) {
523
+ var _config$api;
524
+ var config = cfg.config,
525
+ logger = cfg.logger;
526
+ var _Logger4 = Logger(config, '[token]'),
527
+ info = _Logger4.info;
528
+ if (config != null && (_config$api = config.api) != null && _config$api.token) {
529
+ var _config$api2, _config$api3;
530
+ logger && info(logger, 'config', (_config$api2 = config.api) == null ? void 0 : _config$api2.token);
531
+ return String((_config$api3 = config.api) == null ? void 0 : _config$api3.token);
532
+ }
533
+ if (process.env.NILEDB_TOKEN) {
534
+ logger && info(logger, '.env', process.env.NILEDB_TOKEN);
535
+ return process.env.NILEDB_TOKEN;
536
+ }
537
+ return undefined;
538
+ };
539
+ var getDatabaseName = function getDatabaseName(cfg) {
540
+ var config = cfg.config,
541
+ logger = cfg.logger;
542
+ var _Logger5 = Logger(config, '[databaseName]'),
543
+ info = _Logger5.info;
544
+ if (config != null && config.databaseName) {
545
+ logger && info(logger, 'config', config.databaseName);
546
+ return String(config.databaseName);
547
+ }
548
+ if (process.env.NILEDB_NAME) {
549
+ logger && info(logger, 'config', process.env.NILEDB_NAME);
550
+ return process.env.NILEDB_NAME;
551
+ }
552
+ return null;
553
+ };
554
+ var getTenantId = function getTenantId(cfg) {
555
+ var config = cfg.config,
556
+ logger = cfg.logger;
557
+ var _Logger6 = Logger(config, '[tenantId]'),
558
+ info = _Logger6.info;
559
+ if (config != null && config.tenantId) {
560
+ logger && info(logger, 'config', config.tenantId);
561
+ return config.tenantId;
562
+ }
563
+ if (process.env.NILEDB_TENANT) {
564
+ logger && info(logger, '.env', process.env.NILEDB_TENANT);
565
+ return process.env.NILEDB_TENANT;
566
+ }
567
+ return null;
568
+ };
569
+ var getBasePath = function getBasePath(cfg) {
570
+ var _config$api4;
571
+ var config = cfg.config,
572
+ logger = cfg.logger;
573
+ var _Logger7 = Logger(config, '[basePath]'),
574
+ info = _Logger7.info;
575
+ var basePath = config == null || (_config$api4 = config.api) == null ? void 0 : _config$api4.basePath;
576
+ if (basePath) {
577
+ var _config$api5;
578
+ logger && info(logger, 'config', config == null || (_config$api5 = config.api) == null ? void 0 : _config$api5.basePath);
579
+ return basePath;
580
+ }
581
+ if (process.env.NILEDB_API) {
582
+ logger && info(logger, '.env', process.env.NILEDB_API);
583
+ return "https://" + process.env.NILEDB_API;
584
+ }
585
+ logger && info(logger, 'default', process.env.NILEDB_API);
586
+ return 'https://api.thenile.dev';
587
+ };
588
+ function getDbHost(cfg) {
589
+ var config = cfg.config,
590
+ logger = cfg.logger;
591
+ var _Logger8 = Logger(config, '[db.host]'),
592
+ info = _Logger8.info;
593
+ if (config != null && config.db && config.db.host) {
594
+ logger && info(logger, 'config', config == null ? void 0 : config.db.host);
595
+ return config.db.host;
596
+ }
597
+ if (process.env.NILEDB_HOST) {
598
+ logger && info(logger, '.env', process.env.NILEDB_HOST);
599
+ return process.env.NILEDB_HOST;
600
+ }
601
+ logger && info(logger, 'default', 'db.thenile.dev');
602
+ return 'db.thenile.dev';
603
+ }
604
+ function getDbPort(cfg) {
605
+ var _config$db;
606
+ var config = cfg.config,
607
+ logger = cfg.logger;
608
+ var _Logger9 = Logger(config, '[db.port]'),
609
+ info = _Logger9.info;
610
+ if (config != null && (_config$db = config.db) != null && _config$db.port && config.db.port != null) {
611
+ var _config$db2;
612
+ logger && info(logger, 'config', config == null ? void 0 : config.db.port);
613
+ return Number((_config$db2 = config.db) == null ? void 0 : _config$db2.port);
614
+ }
615
+ if (process.env.NILEDB_PORT) {
616
+ logger && info(logger, 'config', process.env.NILEDB_PORT);
617
+ return Number(process.env.NILEDB_PORT);
618
+ }
619
+ logger && info(logger, 'default', 5432);
620
+ return 5432;
621
+ }
622
+ // don't let people accidentally log secrets to production
623
+ var logProtector = function logProtector(logger) {
624
+ return logger ;
625
+ };
626
+
430
627
  var ApiConfig = /*#__PURE__*/function () {
431
628
  function ApiConfig(_ref) {
432
629
  var basePath = _ref.basePath,
@@ -449,39 +646,81 @@ var ApiConfig = /*#__PURE__*/function () {
449
646
  }
450
647
  }]);
451
648
  }();
452
- var niledatabase_url = 'thenile.dev';
453
649
  var Config = /*#__PURE__*/function () {
454
- function Config(_config) {
455
- var _config$api$basePath, _config$api, _config$api$cookieKey, _config$api2, _config$api3, _config$db, _config$db2, _config$db3, _config$db4, _config$db5;
456
- this.database = void 0;
457
- this.workspace = void 0;
650
+ function Config(config, allowPhoneHome) {
651
+ var _config$api$cookieKey, _config$api;
652
+ this.user = void 0;
653
+ this.password = void 0;
654
+ this.databaseId = void 0;
655
+ this.databaseName = void 0;
656
+ this.debug = void 0;
458
657
  this.db = void 0;
459
658
  this.api = void 0;
460
659
  this._tenantId = void 0;
461
660
  this._userId = void 0;
462
- // always provided
463
- this.database = String(_config == null ? void 0 : _config.database);
464
- this.workspace = String(_config == null ? void 0 : _config.workspace);
465
- // set the context
466
- this._tenantId = _config == null ? void 0 : _config.tenantId;
467
- this._userId = _config == null ? void 0 : _config.userId;
468
- // api config
661
+ var _Logger = Logger(config, '[config]'),
662
+ info = _Logger.info,
663
+ error = _Logger.error;
664
+ var envVarConfig = {
665
+ config: config
666
+ };
667
+ if (allowPhoneHome) {
668
+ envVarConfig.logger = '[config]';
669
+ }
670
+ this.databaseId = getDatbaseId(envVarConfig);
671
+ this.user = getUsername(envVarConfig);
672
+ this.password = getPassword(envVarConfig);
673
+ this.databaseName = getDatabaseName(envVarConfig);
674
+ this._tenantId = getTenantId(envVarConfig);
675
+ this.debug = Boolean(config == null ? void 0 : config.debug);
676
+ var basePath = getBasePath(envVarConfig);
677
+ var host = getDbHost(envVarConfig);
678
+ var port = getDbPort(envVarConfig);
679
+ this._userId = config == null ? void 0 : config.userId;
680
+ if (allowPhoneHome && (!host || !this.databaseName || !this.databaseId)) {
681
+ var database = getInfo(config);
682
+ info('[fetched database]', database);
683
+ {
684
+ if ('message' in database) {
685
+ if ('statusCode' in database) {
686
+ error(database);
687
+ throw new Error('HTTP error has occured');
688
+ } else {
689
+ throw new Error('Unable to auto-configure. Please set or remove NILEDB_API, NILEDB_NAME, and NILEDB_HOST in your .env file.');
690
+ }
691
+ }
692
+ if (typeof database === 'object') {
693
+ var apiHost = database.apiHost,
694
+ dbHost = database.dbHost,
695
+ name = database.name,
696
+ id = database.id;
697
+ this.databaseId = id;
698
+ this.databaseName = name;
699
+ // gotta do something dumb here
700
+ var dburl = new URL(dbHost);
701
+ var apiurl = new URL(apiHost);
702
+ host = dburl.host;
703
+ basePath = apiurl.origin;
704
+ }
705
+ }
706
+ }
469
707
  this.api = new ApiConfig({
470
- basePath: (_config$api$basePath = _config == null || (_config$api = _config.api) == null ? void 0 : _config$api.basePath) != null ? _config$api$basePath : "https://api." + niledatabase_url,
471
- cookieKey: (_config$api$cookieKey = _config == null || (_config$api2 = _config.api) == null ? void 0 : _config$api2.cookieKey) != null ? _config$api$cookieKey : 'token',
472
- token: _config == null || (_config$api3 = _config.api) == null ? void 0 : _config$api3.token
708
+ basePath: basePath,
709
+ cookieKey: (_config$api$cookieKey = config == null || (_config$api = config.api) == null ? void 0 : _config$api.cookieKey) != null ? _config$api$cookieKey : 'token',
710
+ token: getToken({
711
+ config: config
712
+ })
473
713
  });
474
- // db config
475
- var host = _config != null && _config.db && _config.db.connection && typeof ((_config$db = _config.db) == null ? void 0 : _config$db.connection) !== 'string' && 'host' in _config.db.connection ? String(_config.db.connection.host) : "db." + niledatabase_url;
476
- var port = _config != null && (_config$db2 = _config.db) != null && _config$db2.connection && typeof ((_config$db3 = _config.db) == null ? void 0 : _config$db3.connection) !== 'string' && 'port' in _config.db.connection ? Number((_config$db4 = _config.db) == null || (_config$db4 = _config$db4.connection) == null ? void 0 : _config$db4.port) : 5432;
477
- var connection = _extends({
714
+ this.db = _extends({
715
+ user: this.user,
716
+ password: this.password,
478
717
  host: host,
479
718
  port: port,
480
- database: _config == null ? void 0 : _config.database
481
- }, typeof (_config == null || (_config$db5 = _config.db) == null ? void 0 : _config$db5.connection) === 'object' ? _config.db.connection : {});
482
- this.db = _extends({}, _config == null ? void 0 : _config.db, {
483
- connection: connection
484
- });
719
+ database: this.databaseName
720
+ }, typeof (config == null ? void 0 : config.db) === 'object' ? config.db : {});
721
+ if (allowPhoneHome) {
722
+ info(this);
723
+ }
485
724
  }
486
725
  return _createClass(Config, [{
487
726
  key: "tenantId",
@@ -501,6 +740,49 @@ var Config = /*#__PURE__*/function () {
501
740
  }
502
741
  }]);
503
742
  }();
743
+ function getInfo(config) {
744
+ var basePath = getBasePath({
745
+ config: config
746
+ });
747
+ var databaseName = getDatabaseName({
748
+ config: config,
749
+ logger: 'getInfo'
750
+ });
751
+ var url = new URL(basePath + "/databases/configure");
752
+ if (databaseName) {
753
+ url.searchParams.set('databaseName', databaseName);
754
+ }
755
+ var _Logger2 = Logger(config, '[getInfo]'),
756
+ info = _Logger2.info,
757
+ error = _Logger2.error;
758
+ info(url.href);
759
+ var res = syncFetch(url, {
760
+ headers: {
761
+ Authorization: "Bearer " + getInfoBearer({
762
+ config: config
763
+ })
764
+ }
765
+ });
766
+ var possibleError = res.clone();
767
+ try {
768
+ var json = res.json();
769
+ if (res.status === 404) {
770
+ info('is the configured databaseName correct?');
771
+ }
772
+ if (json.status && json.status !== 'READY') {
773
+ return {
774
+ message: 'Database is not ready yet'
775
+ };
776
+ }
777
+ return json;
778
+ } catch (e) {
779
+ var message = possibleError.text();
780
+ error(message);
781
+ return {
782
+ message: message
783
+ };
784
+ }
785
+ }
504
786
 
505
787
  var ResponseError = function ResponseError(body, init) {
506
788
  this.response = void 0;
@@ -618,10 +900,11 @@ function _fetch(_x, _x2, _x3) {
618
900
  function _fetch2() {
619
901
  _fetch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config, path, opts) {
620
902
  var _config$api, _config$api2, _response$status;
621
- var url, cookieKey, headers, basicHeaders, authHeader, _config$api3, token, _config$api4, tenantId, userId, useableUrl, response, res, _res, message, _res2, _res2$errors, _message;
903
+ var _Logger, info, error, url, cookieKey, headers, basicHeaders, authHeader, token, tenantId, userId, useableUrl, response, res, errorHandler, msg, _res, message, _res2, _res2$errors, _message;
622
904
  return _regeneratorRuntime().wrap(function _callee$(_context) {
623
905
  while (1) switch (_context.prev = _context.next) {
624
906
  case 0:
907
+ _Logger = Logger(config, '[server]'), info = _Logger.info, error = _Logger.error;
625
908
  url = "" + ((_config$api = config.api) == null ? void 0 : _config$api.basePath) + path;
626
909
  cookieKey = (_config$api2 = config.api) == null ? void 0 : _config$api2.cookieKey;
627
910
  headers = new Headers(opts == null ? void 0 : opts.headers);
@@ -632,8 +915,12 @@ function _fetch2() {
632
915
  token = getTokenFromCookie(headers, cookieKey);
633
916
  if (token) {
634
917
  basicHeaders.set('Authorization', "Bearer " + token);
635
- } else if ((_config$api3 = config.api) != null && _config$api3.token) {
636
- basicHeaders.set('Authorization', "Bearer " + ((_config$api4 = config.api) == null ? void 0 : _config$api4.token));
918
+ } else if (getToken({
919
+ config: config
920
+ })) {
921
+ basicHeaders.set('Authorization', "Bearer " + getToken({
922
+ config: config
923
+ }));
637
924
  }
638
925
  }
639
926
  tenantId = getTenantFromHttp(headers, config);
@@ -641,66 +928,105 @@ function _fetch2() {
641
928
  userId = getUserFromHttp(headers, config);
642
929
  updateUserId(userId);
643
930
  if (!(url.includes('{tenantId}') && !tenantId)) {
644
- _context.next = 13;
931
+ _context.next = 14;
645
932
  break;
646
933
  }
647
934
  return _context.abrupt("return", new ResponseError('tenantId is not set for request', {
648
935
  status: 400
649
936
  }));
650
- case 13:
937
+ case 14:
651
938
  useableUrl = url.replace('{tenantId}', encodeURIComponent(String(tenantId))).replace('{userId}', encodeURIComponent(String(userId)));
652
- _context.next = 16;
939
+ info('[fetch]', useableUrl);
940
+ _context.next = 18;
653
941
  return fetch(useableUrl, _extends({}, opts, {
654
942
  headers: basicHeaders
655
943
  }))["catch"](function (e) {
656
- // eslint-disable-next-line no-console
657
- console.log(e);
944
+ error('[fetch]', '[response]', e);
658
945
  });
659
- case 16:
946
+ case 18:
660
947
  response = _context.sent;
661
948
  if (!(response && response.status >= 200 && response.status < 300)) {
662
- _context.next = 19;
949
+ _context.next = 27;
950
+ break;
951
+ }
952
+ if (!(typeof response.clone === 'function')) {
953
+ _context.next = 26;
663
954
  break;
664
955
  }
956
+ _context.t0 = info;
957
+ _context.next = 24;
958
+ return response.clone().json();
959
+ case 24:
960
+ _context.t1 = _context.sent;
961
+ (0, _context.t0)('[fetch]', '[response]', _context.t1);
962
+ case 26:
665
963
  return _context.abrupt("return", response);
666
- case 19:
667
- _context.prev = 19;
668
- _context.next = 22;
964
+ case 27:
965
+ errorHandler = typeof (response == null ? void 0 : response.clone) === 'function' ? response.clone() : null;
966
+ msg = '';
967
+ _context.prev = 29;
968
+ _context.next = 32;
669
969
  return response == null ? void 0 : response.json();
670
- case 22:
970
+ case 32:
671
971
  res = _context.sent;
672
- _context.next = 27;
972
+ _context.next = 43;
673
973
  break;
674
- case 25:
675
- _context.prev = 25;
676
- _context.t0 = _context["catch"](19);
677
- case 27:
974
+ case 35:
975
+ _context.prev = 35;
976
+ _context.t2 = _context["catch"](29);
977
+ if (!errorHandler) {
978
+ _context.next = 42;
979
+ break;
980
+ }
981
+ _context.next = 40;
982
+ return errorHandler.text();
983
+ case 40:
984
+ msg = _context.sent;
985
+ if (msg) {
986
+ error('[fetch]', '[response]', "[status: " + errorHandler.status + "]", msg);
987
+ }
988
+ case 42:
989
+ if (!msg) {
990
+ error('[fetch]', '[response]', _context.t2);
991
+ }
992
+ case 43:
993
+ if (!msg) {
994
+ _context.next = 45;
995
+ break;
996
+ }
997
+ return _context.abrupt("return", new ResponseError(msg, {
998
+ status: errorHandler == null ? void 0 : errorHandler.status
999
+ }));
1000
+ case 45:
678
1001
  if (!(res && 'message' in res)) {
679
- _context.next = 30;
1002
+ _context.next = 49;
680
1003
  break;
681
1004
  }
682
1005
  _res = res, message = _res.message;
1006
+ error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", message);
683
1007
  return _context.abrupt("return", new ResponseError(message, {
684
1008
  status: 400
685
1009
  }));
686
- case 30:
1010
+ case 49:
687
1011
  if (!(res && 'errors' in res)) {
688
- _context.next = 33;
1012
+ _context.next = 53;
689
1013
  break;
690
1014
  }
691
1015
  _res2 = res, _res2$errors = _res2.errors, _message = _res2$errors[0];
1016
+ error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", _message);
692
1017
  return _context.abrupt("return", new ResponseError(_message, {
693
1018
  status: 400
694
1019
  }));
695
- case 33:
1020
+ case 53:
1021
+ error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", 'UNHANDLED ERROR');
696
1022
  return _context.abrupt("return", new ResponseError(null, {
697
1023
  status: (_response$status = response == null ? void 0 : response.status) != null ? _response$status : 500
698
1024
  }));
699
- case 34:
1025
+ case 55:
700
1026
  case "end":
701
1027
  return _context.stop();
702
1028
  }
703
- }, _callee, null, [[19, 25]]);
1029
+ }, _callee, null, [[29, 35]]);
704
1030
  }));
705
1031
  return _fetch2.apply(this, arguments);
706
1032
  }
@@ -1044,7 +1370,7 @@ var Auth = /*#__PURE__*/function (_Config) {
1044
1370
  };
1045
1371
  _this.loginSSOUrl = function (provider) {
1046
1372
  var _this$tenantId;
1047
- return "/workspaces/" + encodeURIComponent(_this.workspace) + "/databases/" + encodeURIComponent(_this.database) + "/tenants/" + ((_this$tenantId = _this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/auth/oidc/providers/" + provider + "/login";
1373
+ return "/databases/" + encodeURIComponent(_this.databaseId) + "/tenants/" + ((_this$tenantId = _this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/auth/oidc/providers/" + provider + "/login";
1048
1374
  };
1049
1375
  _this.signUp = /*#__PURE__*/function () {
1050
1376
  var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
@@ -1196,32 +1522,32 @@ var Auth = /*#__PURE__*/function (_Config) {
1196
1522
  } else if (param instanceof Headers) {
1197
1523
  tenantId = getTenantFromHttp(param, _this);
1198
1524
  }
1199
- return _this.api.basePath + "/workspaces/" + _this.workspace + "/databases/" + _this.database + "/tenants/" + tenantId + "/auth/oidc/callback";
1525
+ return "/databases/" + _this.databaseId + "/tenants/" + tenantId + "/auth/oidc/callback";
1200
1526
  };
1201
1527
  return _this;
1202
1528
  }
1203
1529
  _inheritsLoose(Auth, _Config);
1204
1530
  var _proto = Auth.prototype;
1205
1531
  _proto.updateProviderUrl = function updateProviderUrl(providerName) {
1206
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/tenants/" + (this.tenantId ? encodeURIComponent(this.tenantId) : '{tenantId}') + "/auth/oidc/providers/" + encodeURIComponent(providerName);
1532
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/" + (this.tenantId ? encodeURIComponent(this.tenantId) : '{tenantId}') + "/auth/oidc/providers/" + encodeURIComponent(providerName);
1207
1533
  };
1208
1534
  _proto.providerUrl = function providerUrl(email) {
1209
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/tenants/auth/oidc/providers" + (email ? "?email=" + encodeURIComponent(email) : '');
1535
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/auth/oidc/providers" + (email ? "?email=" + encodeURIComponent(email) : '');
1210
1536
  };
1211
1537
  return _createClass(Auth, [{
1212
1538
  key: "loginUrl",
1213
1539
  get: function get() {
1214
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/users/login";
1540
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/users/login";
1215
1541
  }
1216
1542
  }, {
1217
1543
  key: "signUpUrl",
1218
1544
  get: function get() {
1219
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/users";
1545
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/users";
1220
1546
  }
1221
1547
  }, {
1222
1548
  key: "listTenantProvidersUrl",
1223
1549
  get: function get() {
1224
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/tenants/" + (this.tenantId ? encodeURIComponent(this.tenantId) : '{tenantId}') + "/auth/oidc/providers";
1550
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/" + (this.tenantId ? encodeURIComponent(this.tenantId) : '{tenantId}') + "/auth/oidc/providers";
1225
1551
  }
1226
1552
  }]);
1227
1553
  }(Config);
@@ -1341,7 +1667,7 @@ var Users = /*#__PURE__*/function (_Config) {
1341
1667
  return _createClass(Users, [{
1342
1668
  key: "baseUrl",
1343
1669
  get: function get() {
1344
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database);
1670
+ return "/databases/" + encodeURIComponent(this.databaseId);
1345
1671
  }
1346
1672
  }, {
1347
1673
  key: "usersUrl",
@@ -1357,7 +1683,7 @@ var Users = /*#__PURE__*/function (_Config) {
1357
1683
  }, {
1358
1684
  key: "meUrl",
1359
1685
  get: function get() {
1360
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/users/me";
1686
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/users/me";
1361
1687
  }
1362
1688
  }]);
1363
1689
  }(Config);
@@ -1408,66 +1734,87 @@ var Tenants = /*#__PURE__*/function (_Config) {
1408
1734
  return _createClass(Tenants, [{
1409
1735
  key: "tenantsUrl",
1410
1736
  get: function get() {
1411
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/tenants";
1737
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants";
1412
1738
  }
1413
1739
  }, {
1414
1740
  key: "tenantUrl",
1415
1741
  get: function get() {
1416
1742
  var _this$tenantId;
1417
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}');
1743
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}');
1418
1744
  }
1419
1745
  }]);
1420
1746
  }(Config);
1421
1747
 
1748
+ var _excluded = ["afterCreate"];
1422
1749
  var NileDatabase = /*#__PURE__*/function () {
1423
1750
  function NileDatabase(config, id) {
1424
- var _config$db$connection,
1425
- _config$db$connection2,
1426
- _config$db$pool,
1427
- _this = this;
1428
- this.knex = void 0;
1751
+ var _this = this;
1752
+ this.pool = void 0;
1429
1753
  this.tenantId = void 0;
1430
1754
  this.userId = void 0;
1431
1755
  this.id = void 0;
1432
1756
  this.config = void 0;
1433
1757
  this.timer = void 0;
1758
+ var _Logger = Logger(config, '[NileInstance]'),
1759
+ warn = _Logger.warn,
1760
+ info = _Logger.info;
1434
1761
  this.id = id;
1435
1762
  var poolConfig = _extends({
1436
1763
  min: 0,
1437
1764
  max: 10,
1438
1765
  idleTimeoutMillis: 30000
1439
- }, config.db.pool);
1440
- var database = (_config$db$connection = (_config$db$connection2 = config.db.connection) == null ? void 0 : _config$db$connection2.database) != null ? _config$db$connection : config.database;
1441
- this.config = _extends({}, config, {
1442
- db: _extends({}, config.db, {
1443
- connection: _extends({}, config.db.connection, {
1444
- database: database
1445
- }),
1446
- pool: poolConfig
1447
- })
1448
- });
1449
- this.knex = knex(_extends({}, this.config.db, {
1450
- client: 'pg'
1451
- }));
1452
- if ((_config$db$pool = config.db.pool) != null && _config$db$pool.afterCreate) {
1453
- console.log('Providing an pool configuration will stop automatic tenant context setting.');
1454
- } else {
1455
- var afterCreate = makeAfterCreate(config);
1456
- poolConfig.afterCreate = afterCreate;
1766
+ }, config.db);
1767
+ var afterCreate = poolConfig.afterCreate,
1768
+ remaining = _objectWithoutPropertiesLoose(poolConfig, _excluded);
1769
+ config.db = poolConfig;
1770
+ this.config = config;
1771
+ info(this.config);
1772
+ this.pool = new pg.Pool(remaining);
1773
+ if (typeof afterCreate === 'function') {
1774
+ warn('Providing an pool configuration will stop automatic tenant context setting.');
1457
1775
  }
1458
1776
  // start the timer for cleanup
1459
1777
  this.startTimeout();
1460
- this.knex.on('query', /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
1461
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1462
- while (1) switch (_context.prev = _context.next) {
1463
- case 0:
1464
- _this.startTimeout();
1465
- case 1:
1466
- case "end":
1467
- return _context.stop();
1468
- }
1469
- }, _callee);
1470
- })));
1778
+ this.pool.on('connect', /*#__PURE__*/function () {
1779
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(client) {
1780
+ var afterCreate;
1781
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1782
+ while (1) switch (_context.prev = _context.next) {
1783
+ case 0:
1784
+ info('pool connected');
1785
+ afterCreate = makeAfterCreate(config);
1786
+ afterCreate(client, function (err, _client) {
1787
+ if (err) {
1788
+ _client.release();
1789
+ }
1790
+ });
1791
+ _this.startTimeout();
1792
+ case 4:
1793
+ case "end":
1794
+ return _context.stop();
1795
+ }
1796
+ }, _callee);
1797
+ }));
1798
+ return function (_x) {
1799
+ return _ref.apply(this, arguments);
1800
+ };
1801
+ }());
1802
+ this.pool.on('error', /*#__PURE__*/function () {
1803
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(e) {
1804
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1805
+ while (1) switch (_context2.prev = _context2.next) {
1806
+ case 0:
1807
+ info('pool failed', e);
1808
+ case 1:
1809
+ case "end":
1810
+ return _context2.stop();
1811
+ }
1812
+ }, _callee2);
1813
+ }));
1814
+ return function (_x2) {
1815
+ return _ref2.apply(this, arguments);
1816
+ };
1817
+ }());
1471
1818
  }
1472
1819
  var _proto = NileDatabase.prototype;
1473
1820
  _proto.startTimeout = function startTimeout() {
@@ -1475,43 +1822,48 @@ var NileDatabase = /*#__PURE__*/function () {
1475
1822
  if (this.timer) {
1476
1823
  clearTimeout(this.timer);
1477
1824
  }
1478
- this.timer = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
1479
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1480
- while (1) switch (_context2.prev = _context2.next) {
1825
+ this.timer = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
1826
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1827
+ while (1) switch (_context3.prev = _context3.next) {
1481
1828
  case 0:
1482
- _context2.next = 2;
1483
- return _this2.knex.client.pool.destroy();
1829
+ _context3.next = 2;
1830
+ return _this2.pool.end();
1484
1831
  case 2:
1485
- _context2.next = 4;
1486
- return _this2.knex.destroy();
1487
- case 4:
1488
1832
  evictPool(_this2.id);
1489
- case 5:
1833
+ case 3:
1490
1834
  case "end":
1491
- return _context2.stop();
1835
+ return _context3.stop();
1492
1836
  }
1493
- }, _callee2);
1494
- })), this.config.db.pool.idleTimeoutMillis);
1837
+ }, _callee3);
1838
+ })), this.config.db.idleTimeoutMillis);
1495
1839
  };
1496
1840
  return NileDatabase;
1497
1841
  }();
1498
1842
  function makeAfterCreate(config) {
1843
+ var _Logger2 = Logger(config, '[afterCreate]'),
1844
+ warn = _Logger2.warn,
1845
+ info = _Logger2.info;
1499
1846
  return function (conn, done) {
1500
1847
  conn.on('error', function errorHandler(error) {
1501
- console.log('Connection was terminated by server', error);
1848
+ warn('Connection was terminated by server', error);
1502
1849
  done(error, conn);
1503
1850
  });
1504
1851
  if (config.tenantId) {
1505
1852
  var query = ["SET nile.tenant_id = '" + config.tenantId + "'"];
1506
1853
  if (config.userId) {
1507
1854
  if (!config.tenantId) {
1508
- console.warn('A user id cannot be set in context without a tenant id');
1855
+ warn('A user id cannot be set in context without a tenant id');
1509
1856
  }
1510
1857
  query.push("SET nile.user_id = '" + config.userId + "'");
1511
1858
  }
1512
1859
  // in this example we use pg driver's connection API
1513
1860
  conn.query(query.join(';'), function (err) {
1514
- console.log('tenant id and user id set', config.userId, config.tenantId);
1861
+ if (config.tenantId) {
1862
+ info('[tenant id]', config.tenantId);
1863
+ }
1864
+ if (config.userId) {
1865
+ info('[user id]', config.userId);
1866
+ }
1515
1867
  done(err, conn);
1516
1868
  });
1517
1869
  }
@@ -1523,9 +1875,12 @@ var DBManager = /*#__PURE__*/function () {
1523
1875
  function DBManager(config) {
1524
1876
  var _this = this;
1525
1877
  this.connections = void 0;
1878
+ var _Logger = Logger(config, '[DBManager]'),
1879
+ info = _Logger.info;
1526
1880
  this.connections = new Map();
1527
1881
  // add the base one, so you can at least query
1528
1882
  var id = this.makeId();
1883
+ info('constructor', id);
1529
1884
  this.connections.set(id, new NileDatabase(new Config(config), id));
1530
1885
  watchEvictPool(function (id) {
1531
1886
  if (id && _this.connections.has(id)) {
@@ -1544,13 +1899,20 @@ var DBManager = /*#__PURE__*/function () {
1544
1899
  return 'base';
1545
1900
  };
1546
1901
  _proto.getConnection = function getConnection(config) {
1902
+ var _Logger2 = Logger(config, '[DBManager]'),
1903
+ info = _Logger2.info;
1547
1904
  var id = this.makeId(config.tenantId, config.userId);
1548
1905
  var existing = this.connections.get(id);
1906
+ info('# of instances:', this.connections.size);
1549
1907
  if (existing) {
1550
- return existing;
1908
+ info('returning existing', id);
1909
+ return existing.pool;
1551
1910
  }
1552
- this.connections.set(id, new NileDatabase(new Config(config), id));
1553
- return this.connections.get(id);
1911
+ var newOne = new NileDatabase(new Config(config), id);
1912
+ this.connections.set(id, newOne);
1913
+ info('created new', id);
1914
+ info('# of instances:', this.connections.size);
1915
+ return newOne.pool;
1554
1916
  };
1555
1917
  return DBManager;
1556
1918
  }();
@@ -1580,7 +1942,7 @@ var Server = /*#__PURE__*/function () {
1580
1942
  this.api = void 0;
1581
1943
  this.manager = void 0;
1582
1944
  this.servers = void 0;
1583
- this.config = new Config(config);
1945
+ this.config = new Config(config, true);
1584
1946
  this.servers = new Map();
1585
1947
  var _init = init(this.config),
1586
1948
  api = _init[0];
@@ -1598,7 +1960,7 @@ var Server = /*#__PURE__*/function () {
1598
1960
  }
1599
1961
  var _proto = Server.prototype;
1600
1962
  _proto.setConfig = function setConfig(cfg) {
1601
- this.config = new Config(cfg);
1963
+ this.config = new Config(cfg, false);
1602
1964
  };
1603
1965
  /**
1604
1966
  * A utility function if you want to manage different NileDB instances yourself
@@ -1615,38 +1977,26 @@ var Server = /*#__PURE__*/function () {
1615
1977
  var existing = this.servers.get(serverId);
1616
1978
  if (existing) {
1617
1979
  // be sure the config is up to date
1618
- var updatedConfig = new Config(_config);
1980
+ var updatedConfig = new Config(_config, false);
1619
1981
  existing.setConfig(updatedConfig);
1620
1982
  // propagage special config items
1621
1983
  existing.tenantId = updatedConfig.tenantId;
1622
1984
  existing.userId = updatedConfig.userId;
1623
1985
  existing.token = updatedConfig.api.token;
1624
- existing.workspace = updatedConfig.workspace;
1625
- existing.database = updatedConfig.database;
1986
+ existing.databaseId = updatedConfig.databaseId;
1626
1987
  return existing;
1627
1988
  }
1628
1989
  this.servers.set(serverId, new Server(_config));
1629
1990
  return this.servers.get(serverId);
1630
1991
  };
1631
1992
  return _createClass(Server, [{
1632
- key: "database",
1633
- set: function set(val) {
1634
- if (val) {
1635
- this.config.database = val;
1636
- this.config.db.connection.database = val;
1637
- this.api.auth.database = val;
1638
- this.api.users.database = val;
1639
- this.api.tenants.database = val;
1640
- }
1641
- }
1642
- }, {
1643
- key: "workspace",
1993
+ key: "databaseId",
1644
1994
  set: function set(val) {
1645
1995
  if (val) {
1646
- this.config.workspace = val;
1647
- this.api.auth.workspace = val;
1648
- this.api.users.workspace = val;
1649
- this.api.tenants.workspace = val;
1996
+ this.config.databaseId = val;
1997
+ this.api.auth.databaseId = val;
1998
+ this.api.users.databaseId = val;
1999
+ this.api.tenants.databaseId = val;
1650
2000
  }
1651
2001
  }
1652
2002
  }, {
@@ -1655,7 +2005,7 @@ var Server = /*#__PURE__*/function () {
1655
2005
  return this.config.userId;
1656
2006
  },
1657
2007
  set: function set(userId) {
1658
- this.database = this.config.database;
2008
+ this.databaseId = this.config.databaseId;
1659
2009
  this.config.userId = userId;
1660
2010
  if (this.api) {
1661
2011
  this.api.auth.userId = this.config.userId;
@@ -1669,7 +2019,7 @@ var Server = /*#__PURE__*/function () {
1669
2019
  return this.config.tenantId;
1670
2020
  },
1671
2021
  set: function set(tenantId) {
1672
- this.database = this.config.database;
2022
+ this.databaseId = this.config.databaseId;
1673
2023
  this.config.tenantId = tenantId;
1674
2024
  if (this.api) {
1675
2025
  this.api.auth.tenantId = tenantId;
@@ -1697,14 +2047,13 @@ var Server = /*#__PURE__*/function () {
1697
2047
  key: "db",
1698
2048
  get: function get() {
1699
2049
  // only need to interact with the knex object
1700
- //@ts-expect-error - because that's where it is in the proxy
1701
- return this.manager.getConnection(this.config).knex;
2050
+ return this.manager.getConnection(this.config);
1702
2051
  }
1703
2052
  }]);
1704
2053
  }(); // export default Server;
1705
2054
  function Nile(config) {
1706
2055
  var server = new Server(config);
1707
- server.setConfig(new Config(config));
2056
+ // server.setConfig(new Config(config as ServerConfig, false));
1708
2057
  return server;
1709
2058
  }
1710
2059