@niledatabase/server 2.4.2-alpha.4 → 3.0.0-alpha.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.
Files changed (52) hide show
  1. package/dist/Server.d.ts +17 -4
  2. package/dist/api/handlers/DELETE.d.ts +3 -0
  3. package/dist/api/handlers/GET.d.ts +3 -0
  4. package/dist/api/handlers/POST.d.ts +3 -0
  5. package/dist/api/handlers/PUT.d.ts +3 -0
  6. package/dist/api/handlers/index.d.ts +8 -0
  7. package/dist/api/routes/auth/callback.d.ts +3 -0
  8. package/dist/api/routes/auth/csrf.d.ts +3 -0
  9. package/dist/api/routes/auth/error.d.ts +3 -0
  10. package/dist/api/routes/auth/index.d.ts +7 -0
  11. package/dist/api/routes/auth/providers.d.ts +3 -0
  12. package/dist/api/routes/auth/session.d.ts +3 -0
  13. package/dist/api/routes/auth/signin.d.ts +33 -0
  14. package/dist/api/routes/auth/signout.d.ts +3 -0
  15. package/dist/api/routes/me/index.d.ts +4 -0
  16. package/dist/api/routes/tenants/GET.d.ts +32 -0
  17. package/dist/api/routes/tenants/POST.d.ts +45 -0
  18. package/dist/api/routes/tenants/[tenantId]/DELETE.d.ts +34 -0
  19. package/dist/api/routes/tenants/[tenantId]/users/GET.d.ts +35 -0
  20. package/dist/api/routes/tenants/[tenantId]/users/POST.d.ts +44 -0
  21. package/dist/api/routes/tenants/[tenantId]/users/PUT.d.ts +30 -0
  22. package/dist/api/routes/tenants/[tenantId]/users/[userId]/DELETE.d.ts +30 -0
  23. package/dist/api/routes/tenants/[tenantId]/users/index.d.ts +4 -0
  24. package/dist/api/routes/tenants/index.d.ts +4 -0
  25. package/dist/api/routes/users/GET.d.ts +34 -0
  26. package/dist/api/routes/users/POST.d.ts +66 -0
  27. package/dist/api/routes/users/[userId]/PUT.d.ts +40 -0
  28. package/dist/api/routes/users/index.d.ts +4 -0
  29. package/dist/api/swagger.d.ts +152 -0
  30. package/dist/api/types.d.ts +18 -0
  31. package/dist/api/utils/auth.d.ts +6 -0
  32. package/dist/api/utils/request.d.ts +3 -0
  33. package/dist/api/utils/routes/apiRoutes.d.ts +14 -0
  34. package/dist/api/utils/routes/defaultRoutes.d.ts +2 -0
  35. package/dist/api/utils/routes/makeRestUrl.d.ts +1 -0
  36. package/dist/api/utils/routes/proxyRoutes.d.ts +12 -0
  37. package/dist/api/utils/routes/urlMatches.d.ts +1 -0
  38. package/dist/auth/index.d.ts +12 -38
  39. package/dist/server.cjs.development.js +2240 -643
  40. package/dist/server.cjs.development.js.map +1 -1
  41. package/dist/server.cjs.production.min.js +1 -1
  42. package/dist/server.cjs.production.min.js.map +1 -1
  43. package/dist/server.esm.js +2240 -643
  44. package/dist/server.esm.js.map +1 -1
  45. package/dist/tenants/index.d.ts +3 -1
  46. package/dist/types.d.ts +9 -0
  47. package/dist/users/index.d.ts +15 -5
  48. package/dist/utils/Config/envVars.d.ts +6 -1
  49. package/dist/utils/Config/index.d.ts +17 -1
  50. package/dist/utils/Requester/index.d.ts +2 -1
  51. package/dist/utils/fetch.d.ts +3 -3
  52. package/package.json +5 -3
@@ -474,7 +474,7 @@ function Logger(config) {
474
474
  };
475
475
  }
476
476
 
477
- var getDatbaseId = function getDatbaseId(cfg) {
477
+ var getDatabaseId = function getDatabaseId(cfg) {
478
478
  var config = cfg.config,
479
479
  logger = cfg.logger;
480
480
  var _Logger = Logger(config, '[databaseId]'),
@@ -565,43 +565,62 @@ var getTenantId = function getTenantId(cfg) {
565
565
  }
566
566
  return null;
567
567
  };
568
+ var getLocal = function getLocal(cfg) {
569
+ var config = cfg.config,
570
+ logger = cfg.logger;
571
+ if (process.env.NILEDB_LOCAL) {
572
+ var _Logger7 = Logger(config, '[local]'),
573
+ info = _Logger7.info;
574
+ logger && info(logger, 'NILEDB_LOCAL', process.env.NILEDB_LOCAL);
575
+ var apiUrl = new URL(process.env.NILEDB_LOCAL);
576
+ return apiUrl.href;
577
+ }
578
+ return 'http://localhost:3000';
579
+ };
580
+ /**
581
+ * @param cfg various overrides
582
+ * @returns the url for REST to use
583
+ */
568
584
  var getBasePath = function getBasePath(cfg) {
569
585
  var _config$api4;
570
586
  var config = cfg.config,
571
587
  logger = cfg.logger;
572
- var _Logger7 = Logger(config, '[basePath]'),
573
- info = _Logger7.info;
588
+ var _Logger8 = Logger(config, '[basePath]'),
589
+ info = _Logger8.info;
574
590
  var basePath = config == null || (_config$api4 = config.api) == null ? void 0 : _config$api4.basePath;
591
+ var version = '';
592
+ if (!/\/v\d\//.test(String(basePath))) {
593
+ var _config$api5, _config$api$version, _config$api6;
594
+ version = (config == null || (_config$api5 = config.api) == null ? void 0 : _config$api5.version) === 1 ? '' : "/v" + ((_config$api$version = config == null || (_config$api6 = config.api) == null ? void 0 : _config$api6.version) != null ? _config$api$version : 2);
595
+ }
575
596
  if (basePath) {
576
- var _config$api5;
577
- logger && info(logger, 'config', config == null || (_config$api5 = config.api) == null ? void 0 : _config$api5.basePath);
578
- return basePath;
597
+ logger && info(logger, 'config', basePath);
598
+ return "" + basePath + version;
579
599
  }
580
600
  if (process.env.NILEDB_API_URL) {
581
601
  logger && info(logger, 'NILEDB_API_URL', process.env.NILEDB_API_URL);
582
602
  var apiUrl = new URL(process.env.NILEDB_API_URL);
583
- return apiUrl.origin;
603
+ return apiUrl.href;
584
604
  }
585
- logger && info(logger, 'default', 'https://api.thenile.dev');
586
- return 'https://api.thenile.dev';
605
+ throw new Error('NILEDB_API_URL is missing.');
587
606
  };
588
607
  var getControlPlane = function getControlPlane(cfg) {
589
608
  var config = cfg.config,
590
609
  logger = cfg.logger;
591
- var _Logger8 = Logger(config, '[basePath]'),
592
- info = _Logger8.info;
610
+ var _Logger9 = Logger(config, '[basePath]'),
611
+ info = _Logger9.info;
593
612
  if (process.env.NILEDB_CONFIGURE) {
594
613
  logger && info(logger, 'NILEDB_CONFIGURE', process.env.NILEDB_CONFIGURE);
595
- return "https://" + process.env.NILEDB_CONFIGURE;
614
+ return process.env.NILEDB_CONFIGURE;
596
615
  }
597
616
  logger && info(logger, 'default', process.env.NILEDB_CONFIGURE);
598
- return 'https://api.thenile.dev';
617
+ return 'https://global.thenile.dev';
599
618
  };
600
619
  function getDbHost(cfg) {
601
620
  var config = cfg.config,
602
621
  logger = cfg.logger;
603
- var _Logger9 = Logger(config, '[db.host]'),
604
- info = _Logger9.info;
622
+ var _Logger10 = Logger(config, '[db.host]'),
623
+ info = _Logger10.info;
605
624
  if (config != null && config.db && config.db.host) {
606
625
  logger && info(logger, 'config', config == null ? void 0 : config.db.host);
607
626
  return config.db.host;
@@ -622,8 +641,8 @@ function getDbPort(cfg) {
622
641
  var _config$db;
623
642
  var config = cfg.config,
624
643
  logger = cfg.logger;
625
- var _Logger10 = Logger(config, '[db.port]'),
626
- info = _Logger10.info;
644
+ var _Logger11 = Logger(config, '[db.port]'),
645
+ info = _Logger11.info;
627
646
  if (config != null && (_config$db = config.db) != null && _config$db.port && config.db.port != null) {
628
647
  var _config$db2;
629
648
  logger && info(logger, 'config', config == null ? void 0 : config.db.port);
@@ -641,19 +660,25 @@ var logProtector = function logProtector(logger) {
641
660
  return logger ;
642
661
  };
643
662
 
644
- var _excluded$1 = ["host", "port"],
663
+ var _excluded$2 = ["host", "port"],
645
664
  _excluded2 = ["host", "port"];
646
665
  var ApiConfig = /*#__PURE__*/function () {
647
666
  function ApiConfig(_ref) {
648
667
  var basePath = _ref.basePath,
649
668
  cookieKey = _ref.cookieKey,
650
- token = _ref.token;
669
+ token = _ref.token,
670
+ version = _ref.version,
671
+ localPath = _ref.localPath;
651
672
  this.cookieKey = void 0;
652
673
  this.basePath = void 0;
674
+ this.version = void 0;
675
+ this.localPath = void 0;
653
676
  this._token = void 0;
654
677
  this.basePath = basePath;
655
678
  this.cookieKey = cookieKey;
679
+ this.version = version;
656
680
  this._token = token;
681
+ this.localPath = localPath != null ? localPath : 'http://localhost:3000';
657
682
  }
658
683
  return _createClass(ApiConfig, [{
659
684
  key: "token",
@@ -670,11 +695,15 @@ var Config = /*#__PURE__*/function () {
670
695
  var _this = this,
671
696
  _config$db2,
672
697
  _config$api$cookieKey2,
673
- _config$api2;
698
+ _config$api3,
699
+ _config$api$version2,
700
+ _config$api4;
674
701
  this.user = void 0;
675
702
  this.password = void 0;
676
703
  this.databaseId = void 0;
677
704
  this.databaseName = void 0;
705
+ this.routePrefix = void 0;
706
+ this.routes = void 0;
678
707
  this.debug = void 0;
679
708
  this.db = void 0;
680
709
  this.api = void 0;
@@ -682,8 +711,8 @@ var Config = /*#__PURE__*/function () {
682
711
  this._userId = void 0;
683
712
  this.configure = /*#__PURE__*/function () {
684
713
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config) {
685
- var _config$db, _config$api$cookieKey, _config$api;
686
- var _Logger, info, error, envVarConfig, _ref3, host, port, dbConfig, configuredHost, configuredPort, basePath, cp, databaseName, url, res, database, possibleError, json, message, _database, apiHost, dbHost, name, id, dburl, apiurl;
714
+ var _config$db, _envVarConfig$config, _config$api$cookieKey, _config$api, _config$api$version, _config$api2;
715
+ var _Logger, info, error, envVarConfig, _ref3, host, port, dbConfig, configuredHost, configuredPort, basePath, cp, databaseName, url, res, database, possibleError, json, message, _database, apiHost, dbHost, name, id, duckApiHost, dburl;
687
716
  return _regeneratorRuntime().wrap(function _callee$(_context) {
688
717
  while (1) switch (_context.prev = _context.next) {
689
718
  case 0:
@@ -691,14 +720,14 @@ var Config = /*#__PURE__*/function () {
691
720
  envVarConfig = {
692
721
  config: config
693
722
  };
694
- _ref3 = (_config$db = config.db) != null ? _config$db : {}, host = _ref3.host, port = _ref3.port, dbConfig = _objectWithoutPropertiesLoose(_ref3, _excluded$1);
723
+ _ref3 = (_config$db = config.db) != null ? _config$db : {}, host = _ref3.host, port = _ref3.port, dbConfig = _objectWithoutPropertiesLoose(_ref3, _excluded$2);
695
724
  configuredHost = host != null ? host : getDbHost(envVarConfig);
696
725
  configuredPort = port != null ? port : getDbPort(envVarConfig);
697
726
  if (!(configuredHost && _this.databaseName && _this.databaseId)) {
698
727
  _context.next = 8;
699
728
  break;
700
729
  }
701
- info('Alreaady configured, aborting fetch');
730
+ info('Already configured, aborting fetch');
702
731
  return _context.abrupt("return", _this);
703
732
  case 8:
704
733
  basePath = getBasePath(envVarConfig);
@@ -711,7 +740,7 @@ var Config = /*#__PURE__*/function () {
711
740
  if (databaseName) {
712
741
  url.searchParams.set('databaseName', databaseName);
713
742
  }
714
- info(url.href);
743
+ info('configuring from', url.href);
715
744
  _context.next = 16;
716
745
  return fetch(url, {
717
746
  headers: {
@@ -762,26 +791,30 @@ var Config = /*#__PURE__*/function () {
762
791
  break;
763
792
  }
764
793
  error(database);
765
- throw new Error('HTTP error has occured');
794
+ throw new Error('HTTP error has occurred');
766
795
  case 41:
767
796
  throw new Error('Unable to auto-configure. Please remove NILEDB_NAME, NILEDB_API_URL, NILEDB_POSTGRES_URL, and/or NILEDB_HOST from your environment variables.');
768
797
  case 42:
769
798
  if (typeof database === 'object') {
770
799
  _database = database, apiHost = _database.apiHost, dbHost = _database.dbHost, name = _database.name, id = _database.id;
800
+ duckApiHost = getBasePath(envVarConfig) || apiHost; // this needs changed in the control plane response
771
801
  _this.databaseId = id;
772
802
  _this.databaseName = name;
773
803
  dburl = new URL(dbHost);
774
- apiurl = new URL(apiHost);
775
804
  configuredHost = dburl.host;
776
- basePath = apiurl.origin;
805
+ basePath = duckApiHost;
777
806
  }
778
807
  case 43:
808
+ (_envVarConfig$config = envVarConfig.config) == null || (_envVarConfig$config = _envVarConfig$config.api) == null || delete _envVarConfig$config.basePath;
809
+ basePath = getBasePath(envVarConfig);
779
810
  _this.api = new ApiConfig({
780
811
  basePath: basePath,
781
812
  cookieKey: (_config$api$cookieKey = config == null || (_config$api = config.api) == null ? void 0 : _config$api.cookieKey) != null ? _config$api$cookieKey : 'token',
782
813
  token: getToken({
783
814
  config: config
784
- })
815
+ }),
816
+ version: (_config$api$version = config == null || (_config$api2 = config.api) == null ? void 0 : _config$api2.version) != null ? _config$api$version : 2,
817
+ localPath: getLocal(envVarConfig)
785
818
  });
786
819
  _this.db = _extends({
787
820
  user: _this.user,
@@ -792,7 +825,7 @@ var Config = /*#__PURE__*/function () {
792
825
  }, dbConfig);
793
826
  info('[config set]', _this);
794
827
  return _context.abrupt("return", _this);
795
- case 47:
828
+ case 49:
796
829
  case "end":
797
830
  return _context.stop();
798
831
  }
@@ -816,7 +849,7 @@ var Config = /*#__PURE__*/function () {
816
849
  throw new Error('Password is required. Set NILEDB_PASSWORD as an environment variable or set `password` in the config options.');
817
850
  }
818
851
  }
819
- this.databaseId = getDatbaseId(_envVarConfig);
852
+ this.databaseId = getDatabaseId(_envVarConfig);
820
853
  this.databaseName = getDatabaseName(_envVarConfig);
821
854
  this._tenantId = getTenantId(_envVarConfig);
822
855
  this.debug = Boolean(_config == null ? void 0 : _config.debug);
@@ -830,10 +863,12 @@ var Config = /*#__PURE__*/function () {
830
863
  var _configuredPort = _port != null ? _port : getDbPort(_envVarConfig);
831
864
  this.api = new ApiConfig({
832
865
  basePath: _basePath,
833
- cookieKey: (_config$api$cookieKey2 = _config == null || (_config$api2 = _config.api) == null ? void 0 : _config$api2.cookieKey) != null ? _config$api$cookieKey2 : 'token',
866
+ cookieKey: (_config$api$cookieKey2 = _config == null || (_config$api3 = _config.api) == null ? void 0 : _config$api3.cookieKey) != null ? _config$api$cookieKey2 : 'token',
834
867
  token: getToken({
835
868
  config: _config
836
- })
869
+ }),
870
+ version: (_config$api$version2 = _config == null || (_config$api4 = _config.api) == null ? void 0 : _config$api4.version) != null ? _config$api$version2 : 2,
871
+ localPath: getLocal(_envVarConfig)
837
872
  });
838
873
  this.db = _extends({
839
874
  user: this.user,
@@ -926,9 +961,6 @@ var updateUserId = function updateUserId(userId) {
926
961
  var watchUserId = function watchUserId(cb) {
927
962
  return eventer.subscribe(Events.User, cb);
928
963
  };
929
- var updateToken = function updateToken(val) {
930
- eventer.publish(Events.Token, val);
931
- };
932
964
  var watchToken = function watchToken(cb) {
933
965
  return eventer.subscribe(Events.Token, cb);
934
966
  };
@@ -942,8 +974,8 @@ var evictPool = function evictPool(val) {
942
974
  eventer.publish(Events.EvictPool, val);
943
975
  };
944
976
 
945
- var X_NILE_TENANT = 'x-nile-tenantId';
946
- var X_NILE_USER_ID = 'x-nile-userId';
977
+ var X_NILE_TENANT = 'niledb-tenant-id';
978
+ var X_NILE_USER_ID = 'niledb-user-id';
947
979
  function getTokenFromCookie(headers, cookieKey) {
948
980
  var _headers$get;
949
981
  var cookie = (_headers$get = headers.get('cookie')) == null ? void 0 : _headers$get.split('; ');
@@ -973,8 +1005,8 @@ function getTokenFromCookie(headers, cookieKey) {
973
1005
  }
974
1006
  function getTenantFromHttp(headers, config) {
975
1007
  var _ref;
976
- var cookieTenant = getTokenFromCookie(headers, 'tenantId');
977
- return (_ref = cookieTenant != null ? cookieTenant : headers == null ? void 0 : headers.get(X_NILE_TENANT)) != null ? _ref : config.tenantId;
1008
+ var cookieTenant = getTokenFromCookie(headers, X_NILE_TENANT);
1009
+ return (_ref = cookieTenant != null ? cookieTenant : headers == null ? void 0 : headers.get(X_NILE_TENANT)) != null ? _ref : config == null ? void 0 : config.tenantId;
978
1010
  }
979
1011
  function getUserFromHttp(headers, config) {
980
1012
  var _headers$get2;
@@ -991,7 +1023,7 @@ function _fetch(_x, _x2, _x3) {
991
1023
  function _fetch2() {
992
1024
  _fetch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config, path, opts) {
993
1025
  var _config$api, _config$api2, _response$status;
994
- var _Logger, info, error, url, cookieKey, headers, basicHeaders, authHeader, token, tenantId, userId, useableUrl, response, res, errorHandler, msg, _res, message, _res2, _res2$errors, _message;
1026
+ var _Logger, info, error, url, cookieKey, headers, basicHeaders, creds, authHeader, token, tenantId, userId, useableUrl, response, res, errorHandler, msg, _res, message, _res2, _res2$errors, _message;
995
1027
  return _regeneratorRuntime().wrap(function _callee$(_context) {
996
1028
  while (1) switch (_context.prev = _context.next) {
997
1029
  case 0:
@@ -999,8 +1031,10 @@ function _fetch2() {
999
1031
  url = "" + ((_config$api = config.api) == null ? void 0 : _config$api.basePath) + path;
1000
1032
  cookieKey = (_config$api2 = config.api) == null ? void 0 : _config$api2.cookieKey;
1001
1033
  headers = new Headers(opts == null ? void 0 : opts.headers);
1002
- basicHeaders = new Headers();
1034
+ basicHeaders = new Headers(opts == null ? void 0 : opts.headers);
1003
1035
  basicHeaders.set('content-type', 'application/json; charset=utf-8');
1036
+ creds = Buffer.from(process.env.NILEDB_USER + ":" + process.env.NILEDB_PASSWORD, 'utf8').toString('base64');
1037
+ basicHeaders.set('niledb-creds', creds);
1004
1038
  authHeader = headers.get('Authorization');
1005
1039
  if (!authHeader) {
1006
1040
  token = getTokenFromCookie(headers, cookieKey);
@@ -1019,78 +1053,106 @@ function _fetch2() {
1019
1053
  userId = getUserFromHttp(headers, config);
1020
1054
  updateUserId(userId);
1021
1055
  if (!(url.includes('{tenantId}') && !tenantId)) {
1022
- _context.next = 14;
1056
+ _context.next = 16;
1023
1057
  break;
1024
1058
  }
1025
1059
  return _context.abrupt("return", new ResponseError('tenantId is not set for request', {
1026
1060
  status: 400
1027
1061
  }));
1028
- case 14:
1062
+ case 16:
1029
1063
  useableUrl = url.replace('{tenantId}', encodeURIComponent(String(tenantId))).replace('{userId}', encodeURIComponent(String(userId)));
1030
1064
  info('[fetch]', useableUrl);
1031
- _context.next = 18;
1065
+ _context.next = 20;
1032
1066
  return fetch(useableUrl, _extends({}, opts, {
1033
1067
  headers: basicHeaders
1034
1068
  }))["catch"](function (e) {
1035
1069
  error('[fetch]', '[response]', e);
1036
1070
  });
1037
- case 18:
1071
+ case 20:
1038
1072
  response = _context.sent;
1039
1073
  if (!(response && response.status >= 200 && response.status < 300)) {
1040
- _context.next = 27;
1074
+ _context.next = 39;
1041
1075
  break;
1042
1076
  }
1043
1077
  if (!(typeof response.clone === 'function')) {
1044
- _context.next = 26;
1078
+ _context.next = 38;
1045
1079
  break;
1046
1080
  }
1081
+ _context.prev = 23;
1047
1082
  _context.t0 = info;
1048
- _context.next = 24;
1083
+ _context.next = 27;
1049
1084
  return response.clone().json();
1050
- case 24:
1085
+ case 27:
1051
1086
  _context.t1 = _context.sent;
1052
1087
  (0, _context.t0)('[fetch]', '[response]', _context.t1);
1053
- case 26:
1088
+ _context.next = 38;
1089
+ break;
1090
+ case 31:
1091
+ _context.prev = 31;
1092
+ _context.t2 = _context["catch"](23);
1093
+ _context.t3 = info;
1094
+ _context.next = 36;
1095
+ return response.clone().text();
1096
+ case 36:
1097
+ _context.t4 = _context.sent;
1098
+ (0, _context.t3)('[fetch]', '[response]', _context.t4);
1099
+ case 38:
1054
1100
  return _context.abrupt("return", response);
1055
- case 27:
1101
+ case 39:
1102
+ if (!((response == null ? void 0 : response.status) === 401)) {
1103
+ _context.next = 41;
1104
+ break;
1105
+ }
1106
+ return _context.abrupt("return", new ResponseError('Unauthorized', {
1107
+ status: 401
1108
+ }));
1109
+ case 41:
1110
+ if (!((response == null ? void 0 : response.status) === 405)) {
1111
+ _context.next = 43;
1112
+ break;
1113
+ }
1114
+ return _context.abrupt("return", new ResponseError('Method not allowed', {
1115
+ status: 405
1116
+ }));
1117
+ case 43:
1056
1118
  errorHandler = typeof (response == null ? void 0 : response.clone) === 'function' ? response.clone() : null;
1057
1119
  msg = '';
1058
- _context.prev = 29;
1059
- _context.next = 32;
1120
+ _context.prev = 45;
1121
+ _context.next = 48;
1060
1122
  return response == null ? void 0 : response.json();
1061
- case 32:
1123
+ case 48:
1062
1124
  res = _context.sent;
1063
- _context.next = 43;
1125
+ _context.next = 59;
1064
1126
  break;
1065
- case 35:
1066
- _context.prev = 35;
1067
- _context.t2 = _context["catch"](29);
1127
+ case 51:
1128
+ _context.prev = 51;
1129
+ _context.t5 = _context["catch"](45);
1068
1130
  if (!errorHandler) {
1069
- _context.next = 42;
1131
+ _context.next = 58;
1070
1132
  break;
1071
1133
  }
1072
- _context.next = 40;
1134
+ _context.next = 56;
1073
1135
  return errorHandler.text();
1074
- case 40:
1136
+ case 56:
1075
1137
  msg = _context.sent;
1076
1138
  if (msg) {
1077
1139
  error('[fetch]', '[response]', "[status: " + errorHandler.status + "]", msg);
1078
1140
  }
1079
- case 42:
1141
+ case 58:
1080
1142
  if (!msg) {
1081
- error('[fetch]', '[response]', _context.t2);
1143
+ error('[fetch]', '[response]', _context.t5);
1082
1144
  }
1083
- case 43:
1145
+ case 59:
1084
1146
  if (!msg) {
1085
- _context.next = 45;
1147
+ _context.next = 61;
1086
1148
  break;
1087
1149
  }
1088
1150
  return _context.abrupt("return", new ResponseError(msg, {
1089
1151
  status: errorHandler == null ? void 0 : errorHandler.status
1090
1152
  }));
1091
- case 45:
1153
+ case 61:
1092
1154
  if (!(res && 'message' in res)) {
1093
- _context.next = 49;
1155
+ _context.next = 65;
1094
1156
  break;
1095
1157
  }
1096
1158
  _res = res, message = _res.message;
@@ -1098,9 +1160,9 @@ function _fetch2() {
1098
1160
  return _context.abrupt("return", new ResponseError(message, {
1099
1161
  status: 400
1100
1162
  }));
1101
- case 49:
1163
+ case 65:
1102
1164
  if (!(res && 'errors' in res)) {
1103
- _context.next = 53;
1165
+ _context.next = 69;
1104
1166
  break;
1105
1167
  }
1106
1168
  _res2 = res, _res2$errors = _res2.errors, _message = _res2$errors[0];
@@ -1108,16 +1170,16 @@ function _fetch2() {
1108
1170
  return _context.abrupt("return", new ResponseError(_message, {
1109
1171
  status: 400
1110
1172
  }));
1111
- case 53:
1173
+ case 69:
1112
1174
  error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", 'UNHANDLED ERROR');
1113
1175
  return _context.abrupt("return", new ResponseError(null, {
1114
1176
  status: (_response$status = response == null ? void 0 : response.status) != null ? _response$status : 500
1115
1177
  }));
1116
- case 55:
1178
+ case 71:
1117
1179
  case "end":
1118
1180
  return _context.stop();
1119
1181
  }
1120
- }, _callee, null, [[29, 35]]);
1182
+ }, _callee, null, [[23, 31], [45, 51]]);
1121
1183
  }));
1122
1184
  return _fetch2.apply(this, arguments);
1123
1185
  }
@@ -1183,38 +1245,57 @@ var Requester = /*#__PURE__*/function (_Config) {
1183
1245
  return _ref3.apply(this, arguments);
1184
1246
  };
1185
1247
  }();
1248
+ _this["delete"] = /*#__PURE__*/function () {
1249
+ var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, url, init) {
1250
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1251
+ while (1) switch (_context4.prev = _context4.next) {
1252
+ case 0:
1253
+ _context4.next = 2;
1254
+ return _this.request('DELETE', url, req, init);
1255
+ case 2:
1256
+ return _context4.abrupt("return", _context4.sent);
1257
+ case 3:
1258
+ case "end":
1259
+ return _context4.stop();
1260
+ }
1261
+ }, _callee4);
1262
+ }));
1263
+ return function (_x10, _x11, _x12) {
1264
+ return _ref4.apply(this, arguments);
1265
+ };
1266
+ }();
1186
1267
  return _this;
1187
1268
  }
1188
1269
  _inheritsLoose(Requester, _Config);
1189
1270
  var _proto = Requester.prototype;
1190
1271
  _proto.rawRequest = /*#__PURE__*/function () {
1191
- var _rawRequest = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(method, url, init, body) {
1272
+ var _rawRequest = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(method, url, init, body) {
1192
1273
  var _init, res;
1193
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1194
- while (1) switch (_context4.prev = _context4.next) {
1274
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1275
+ while (1) switch (_context5.prev = _context5.next) {
1195
1276
  case 0:
1196
1277
  _init = _extends({}, init, {
1197
1278
  body: body,
1198
1279
  method: method
1199
1280
  });
1200
- _context4.next = 3;
1281
+ _context5.next = 3;
1201
1282
  return _fetch(this, url, _init);
1202
1283
  case 3:
1203
- res = _context4.sent;
1284
+ res = _context5.sent;
1204
1285
  if (!(res instanceof ResponseError)) {
1205
- _context4.next = 6;
1286
+ _context5.next = 6;
1206
1287
  break;
1207
1288
  }
1208
- return _context4.abrupt("return", res.response);
1289
+ return _context5.abrupt("return", res.response);
1209
1290
  case 6:
1210
- return _context4.abrupt("return", res);
1291
+ return _context5.abrupt("return", res);
1211
1292
  case 7:
1212
1293
  case "end":
1213
- return _context4.stop();
1294
+ return _context5.stop();
1214
1295
  }
1215
- }, _callee4, this);
1296
+ }, _callee5, this);
1216
1297
  }));
1217
- function rawRequest(_x10, _x11, _x12, _x13) {
1298
+ function rawRequest(_x13, _x14, _x15, _x16) {
1218
1299
  return _rawRequest.apply(this, arguments);
1219
1300
  }
1220
1301
  return rawRequest;
@@ -1234,10 +1315,10 @@ var Requester = /*#__PURE__*/function (_Config) {
1234
1315
  _proto.request =
1235
1316
  /*#__PURE__*/
1236
1317
  function () {
1237
- var _request = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(method, url, req, init) {
1318
+ var _request = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(method, url, req, init) {
1238
1319
  var headers, tenantId, cookie, _headers, _tenantId, _cookie, body, _init;
1239
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1240
- while (1) switch (_context5.prev = _context5.next) {
1320
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1321
+ while (1) switch (_context6.prev = _context6.next) {
1241
1322
  case 0:
1242
1323
  // set the headers
1243
1324
  headers = new Headers(init ? init == null ? void 0 : init.headers : {});
@@ -1265,22 +1346,22 @@ var Requester = /*#__PURE__*/function (_Config) {
1265
1346
  // default the body - may be the actual payload for the API
1266
1347
  body = JSON.stringify(req); // comes from next/some server
1267
1348
  if (!(method === 'GET')) {
1268
- _context5.next = 7;
1349
+ _context6.next = 7;
1269
1350
  break;
1270
1351
  }
1271
1352
  body = undefined;
1272
- _context5.next = 14;
1353
+ _context6.next = 14;
1273
1354
  break;
1274
1355
  case 7:
1275
1356
  if (!(req instanceof Request)) {
1276
- _context5.next = 13;
1357
+ _context6.next = 13;
1277
1358
  break;
1278
1359
  }
1279
- _context5.next = 10;
1360
+ _context6.next = 10;
1280
1361
  return new Response(req.body).text();
1281
1362
  case 10:
1282
- body = _context5.sent;
1283
- _context5.next = 14;
1363
+ body = _context6.sent;
1364
+ _context6.next = 14;
1284
1365
  break;
1285
1366
  case 13:
1286
1367
  if (
@@ -1292,17 +1373,17 @@ var Requester = /*#__PURE__*/function (_Config) {
1292
1373
  _init = _extends({}, init, {
1293
1374
  headers: headers
1294
1375
  });
1295
- _context5.next = 17;
1376
+ _context6.next = 17;
1296
1377
  return this.rawRequest(method, url, _init, body);
1297
1378
  case 17:
1298
- return _context5.abrupt("return", _context5.sent);
1379
+ return _context6.abrupt("return", _context6.sent);
1299
1380
  case 18:
1300
1381
  case "end":
1301
- return _context5.stop();
1382
+ return _context6.stop();
1302
1383
  }
1303
- }, _callee5, this);
1384
+ }, _callee6, this);
1304
1385
  }));
1305
- function request(_x14, _x15, _x16, _x17) {
1386
+ function request(_x17, _x18, _x19, _x20) {
1306
1387
  return _request.apply(this, arguments);
1307
1388
  }
1308
1389
  return request;
@@ -1310,103 +1391,24 @@ var Requester = /*#__PURE__*/function (_Config) {
1310
1391
  return Requester;
1311
1392
  }(Config);
1312
1393
 
1313
- var Auth = /*#__PURE__*/function (_Config) {
1314
- function Auth(config) {
1394
+ var Users = /*#__PURE__*/function (_Config) {
1395
+ function Users(config, headers) {
1315
1396
  var _this;
1316
1397
  _this = _Config.call(this, config) || this;
1317
- _this.login = /*#__PURE__*/function () {
1398
+ _this.headers = void 0;
1399
+ _this.createUser = /*#__PURE__*/function () {
1318
1400
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
1319
- var headers, _requester, params, sso, providerRes, providers, res, _this$api, token, cookie, tenants, tenant, tenantId, text;
1401
+ var _requester, _init;
1320
1402
  return _regeneratorRuntime().wrap(function _callee$(_context) {
1321
1403
  while (1) switch (_context.prev = _context.next) {
1322
1404
  case 0:
1323
- headers = new Headers({
1324
- 'content-type': 'application/json'
1325
- });
1326
1405
  _requester = new Requester(_this);
1327
- params = req instanceof Request ? new URL(req.url).searchParams : new URLSearchParams();
1328
- sso = params.get('sso');
1329
- if (!(sso === 'true')) {
1330
- _context.next = 18;
1331
- break;
1332
- }
1333
- _context.next = 7;
1334
- return _this.listProviders(req.clone(), init);
1335
- case 7:
1336
- providerRes = _context.sent;
1337
- if (!(providerRes && providerRes.status >= 200 && providerRes.status < 300)) {
1338
- _context.next = 18;
1339
- break;
1340
- }
1341
- _context.next = 11;
1342
- return new Response(providerRes.body).json();
1343
- case 11:
1344
- providers = _context.sent;
1345
- if (!(providers.length > 0)) {
1346
- _context.next = 18;
1347
- break;
1348
- }
1349
- if (!(providers.length > 1)) {
1350
- _context.next = 15;
1351
- break;
1352
- }
1353
- return _context.abrupt("return", new Response(JSON.stringify(providers), {
1354
- status: 200
1355
- }));
1356
- case 15:
1357
- // is there a way to do this? probably not.
1358
- headers.set(X_NILE_TENANT, providers[0].tenantId);
1359
- headers.append('set-cookie', "tenantId=" + providers[0].tenantId + "; path=/; httponly;");
1360
- // const ssoResp = await this.loginSSO(req);
1361
- return _context.abrupt("return", new Response(JSON.stringify({
1362
- redirectURI: "" + _this.api.basePath + _this.loginSSOUrl('okta')
1363
- }), {
1364
- status: 200
1365
- }));
1366
- case 18:
1367
- _context.next = 20;
1368
- return _requester.post(req, _this.loginUrl, init)["catch"](function (e) {
1369
- // eslint-disable-next-line no-console
1370
- console.error(e);
1371
- return e;
1372
- });
1373
- case 20:
1374
- res = _context.sent;
1375
- if (!(res instanceof ResponseError)) {
1376
- _context.next = 23;
1377
- break;
1378
- }
1379
- return _context.abrupt("return", res.response);
1380
- case 23:
1381
- if (!(res && res.status >= 200 && res.status < 300)) {
1382
- _context.next = 36;
1383
- break;
1384
- }
1385
- _context.next = 26;
1386
- return res.json();
1387
- case 26:
1388
- token = _context.sent;
1389
- cookie = ((_this$api = _this.api) == null ? void 0 : _this$api.cookieKey) + "=" + token.token.jwt + "; path=/; samesite=lax; httponly;";
1390
- headers.append('set-cookie', cookie);
1391
- tenants = token.tenants;
1392
- tenant = tenants == null ? void 0 : tenants.values();
1393
- tenantId = tenant == null ? void 0 : tenant.next().value;
1394
- headers.set(X_NILE_TENANT, tenantId);
1395
- headers.append('set-cookie', "tenantId=" + tenantId + "; path=/; httponly;");
1396
- updateToken(token.token.jwt);
1397
- return _context.abrupt("return", new Response(JSON.stringify(token), {
1398
- status: 200,
1399
- headers: headers
1400
- }));
1401
- case 36:
1402
- _context.next = 38;
1403
- return res.text();
1404
- case 38:
1405
- text = _context.sent;
1406
- return _context.abrupt("return", new Response(text, {
1407
- status: res.status
1408
- }));
1409
- case 40:
1406
+ _init = _this.handleHeaders(init);
1407
+ _context.next = 4;
1408
+ return _requester.post(req, _this.usersUrl, _init);
1409
+ case 4:
1410
+ return _context.abrupt("return", _context.sent);
1411
+ case 5:
1410
1412
  case "end":
1411
1413
  return _context.stop();
1412
1414
  }
@@ -1416,249 +1418,215 @@ var Auth = /*#__PURE__*/function (_Config) {
1416
1418
  return _ref.apply(this, arguments);
1417
1419
  };
1418
1420
  }();
1419
- _this.loginSSO = function (redirectUrl) {
1420
- var ssoLogin = /*#__PURE__*/function () {
1421
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req) {
1422
- var _this$api2;
1423
- var headers, body, accessToken, tenantId, cookie;
1424
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1425
- while (1) switch (_context2.prev = _context2.next) {
1426
- case 0:
1427
- headers = new Headers();
1428
- _context2.next = 3;
1429
- return req.formData();
1430
- case 3:
1431
- body = _context2.sent;
1432
- _context2.next = 6;
1433
- return body.get('access_token');
1434
- case 6:
1435
- accessToken = _context2.sent;
1436
- _context2.next = 9;
1437
- return body.get('tenantId');
1438
- case 9:
1439
- tenantId = _context2.sent;
1440
- cookie = ((_this$api2 = _this.api) == null ? void 0 : _this$api2.cookieKey) + "=" + accessToken + "; path=/; samesite=lax; httponly;";
1441
- updateToken(accessToken);
1442
- headers.append('set-cookie', cookie);
1443
- headers.set(X_NILE_TENANT, tenantId);
1444
- headers.append('set-cookie', "tenantId=" + tenantId + "; path=/; httponly;");
1445
- headers.set('Location', redirectUrl);
1446
- return _context2.abrupt("return", new Response(null, {
1447
- headers: headers,
1448
- status: 303
1449
- }));
1450
- case 17:
1451
- case "end":
1452
- return _context2.stop();
1453
- }
1454
- }, _callee2);
1455
- }));
1456
- return function ssoLogin(_x3) {
1457
- return _ref2.apply(this, arguments);
1458
- };
1459
- }();
1460
- return ssoLogin;
1461
- };
1462
- _this.loginSSOUrl = function (provider) {
1463
- var _this$tenantId;
1464
- return "/databases/" + encodeURIComponent(_this.databaseId) + "/tenants/" + ((_this$tenantId = _this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/auth/oidc/providers/" + provider + "/login";
1465
- };
1466
- _this.signUp = /*#__PURE__*/function () {
1421
+ _this.updateUser = /*#__PURE__*/function () {
1422
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(userId, req, init) {
1423
+ var _requester, _init;
1424
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1425
+ while (1) switch (_context2.prev = _context2.next) {
1426
+ case 0:
1427
+ _requester = new Requester(_this);
1428
+ _init = _this.handleHeaders(init);
1429
+ _context2.next = 4;
1430
+ return _requester.put(req, _this.usersUrl + "/" + userId, _init);
1431
+ case 4:
1432
+ return _context2.abrupt("return", _context2.sent);
1433
+ case 5:
1434
+ case "end":
1435
+ return _context2.stop();
1436
+ }
1437
+ }, _callee2);
1438
+ }));
1439
+ return function (_x3, _x4, _x5) {
1440
+ return _ref2.apply(this, arguments);
1441
+ };
1442
+ }();
1443
+ _this.listUsers = /*#__PURE__*/function () {
1467
1444
  var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
1468
- var headers, _requester, res, _this$api3, _token$token, _token$token2, token, cookie, id, text;
1445
+ var _requester, _init;
1469
1446
  return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1470
1447
  while (1) switch (_context3.prev = _context3.next) {
1471
1448
  case 0:
1472
- headers = new Headers();
1473
1449
  _requester = new Requester(_this);
1450
+ _init = _this.handleHeaders(init);
1474
1451
  _context3.next = 4;
1475
- return _requester.post(req, _this.signUpUrl, init)["catch"](function (e) {
1476
- // eslint-disable-next-line no-console
1477
- console.error(e);
1478
- return e;
1479
- });
1452
+ return _requester.get(req, _this.tenantUsersUrl, _init);
1480
1453
  case 4:
1481
- res = _context3.sent;
1482
- if (!(res instanceof ResponseError)) {
1483
- _context3.next = 7;
1484
- break;
1485
- }
1486
- return _context3.abrupt("return", res.response);
1487
- case 7:
1488
- if (!(res && res.status >= 200 && res.status < 300)) {
1489
- _context3.next = 19;
1490
- break;
1491
- }
1492
- _context3.next = 10;
1493
- return res.json();
1494
- case 10:
1495
- token = _context3.sent;
1496
- cookie = ((_this$api3 = _this.api) == null ? void 0 : _this$api3.cookieKey) + "=" + ((_token$token = token.token) == null ? void 0 : _token$token.jwt) + "; path=/; samesite=lax; httponly;";
1497
- headers.append('set-cookie', cookie);
1498
- id = token.id;
1499
- updateToken((_token$token2 = token.token) == null ? void 0 : _token$token2.jwt);
1500
- updateUserId(id);
1501
- headers.set(X_NILE_USER_ID, id);
1502
- headers.append('set-cookie', "userId=" + id + "; path=/; httponly;");
1503
- return _context3.abrupt("return", new Response(JSON.stringify(token), {
1504
- status: 201,
1505
- headers: headers
1506
- }));
1507
- case 19:
1508
- _context3.next = 21;
1509
- return res.text();
1510
- case 21:
1511
- text = _context3.sent;
1512
- return _context3.abrupt("return", new Response(text, {
1513
- status: res.status
1514
- }));
1515
- case 23:
1454
+ return _context3.abrupt("return", _context3.sent);
1455
+ case 5:
1516
1456
  case "end":
1517
1457
  return _context3.stop();
1518
1458
  }
1519
1459
  }, _callee3);
1520
1460
  }));
1521
- return function (_x4, _x5) {
1461
+ return function (_x6, _x7) {
1522
1462
  return _ref3.apply(this, arguments);
1523
1463
  };
1524
1464
  }();
1525
- _this.listTenantProviders = /*#__PURE__*/function () {
1465
+ _this.linkUser = /*#__PURE__*/function () {
1526
1466
  var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, init) {
1527
- var _requester;
1467
+ var _requester, _init;
1528
1468
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1529
1469
  while (1) switch (_context4.prev = _context4.next) {
1530
1470
  case 0:
1531
1471
  _requester = new Requester(_this);
1532
- return _context4.abrupt("return", _requester.get(req, _this.listTenantProvidersUrl, init));
1533
- case 2:
1472
+ _init = _this.handleHeaders(init);
1473
+ _context4.next = 4;
1474
+ return _requester.put(req, _this.tenantUsersUrl, _init);
1475
+ case 4:
1476
+ return _context4.abrupt("return", _context4.sent);
1477
+ case 5:
1534
1478
  case "end":
1535
1479
  return _context4.stop();
1536
1480
  }
1537
1481
  }, _callee4);
1538
1482
  }));
1539
- return function (_x6, _x7) {
1483
+ return function (_x8, _x9) {
1540
1484
  return _ref4.apply(this, arguments);
1541
1485
  };
1542
1486
  }();
1543
- _this.createProvider = /*#__PURE__*/function () {
1544
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req, init) {
1545
- var _requester, providerName;
1487
+ _this.tenantUsersDeleteUrl = function (userId) {
1488
+ var _this$tenantId;
1489
+ return "/tenants/" + ((_this$tenantId = _this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/users/" + (userId != null ? userId : '{userId}');
1490
+ };
1491
+ _this.getUserId = /*#__PURE__*/function () {
1492
+ var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req) {
1493
+ var body;
1546
1494
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1547
1495
  while (1) switch (_context5.prev = _context5.next) {
1548
1496
  case 0:
1549
- _requester = new Requester(_this);
1550
- providerName = 'okta';
1551
- return _context5.abrupt("return", _requester.post(req, _this.updateProviderUrl(providerName), init));
1497
+ if (!(req instanceof Request)) {
1498
+ _context5.next = 6;
1499
+ break;
1500
+ }
1501
+ _context5.next = 3;
1502
+ return new Response(req == null ? void 0 : req.body).json();
1552
1503
  case 3:
1504
+ body = _context5.sent;
1505
+ if (!body) {
1506
+ _context5.next = 6;
1507
+ break;
1508
+ }
1509
+ return _context5.abrupt("return", body.id);
1510
+ case 6:
1511
+ if (!('id' in req)) {
1512
+ _context5.next = 8;
1513
+ break;
1514
+ }
1515
+ return _context5.abrupt("return", req.id);
1516
+ case 8:
1517
+ return _context5.abrupt("return", null);
1518
+ case 9:
1553
1519
  case "end":
1554
1520
  return _context5.stop();
1555
1521
  }
1556
1522
  }, _callee5);
1557
1523
  }));
1558
- return function (_x8, _x9) {
1524
+ return function (_x10) {
1559
1525
  return _ref5.apply(this, arguments);
1560
1526
  };
1561
1527
  }();
1562
- _this.updateProvider = /*#__PURE__*/function () {
1528
+ _this.unlinkUser = /*#__PURE__*/function () {
1563
1529
  var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(req, init) {
1564
- var _requester, providerName;
1530
+ var _requester, userId, _init;
1565
1531
  return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1566
1532
  while (1) switch (_context6.prev = _context6.next) {
1567
1533
  case 0:
1568
1534
  _requester = new Requester(_this);
1569
- providerName = 'okta';
1570
- return _context6.abrupt("return", _requester.put(req, _this.updateProviderUrl(providerName), init));
1535
+ _context6.next = 3;
1536
+ return _this.getUserId(req);
1571
1537
  case 3:
1538
+ userId = _context6.sent;
1539
+ _init = _this.handleHeaders(init);
1540
+ _context6.next = 7;
1541
+ return _requester["delete"](req, _this.tenantUsersDeleteUrl(userId), _init);
1542
+ case 7:
1543
+ return _context6.abrupt("return", _context6.sent);
1544
+ case 8:
1572
1545
  case "end":
1573
1546
  return _context6.stop();
1574
1547
  }
1575
1548
  }, _callee6);
1576
1549
  }));
1577
- return function (_x10, _x11) {
1550
+ return function (_x11, _x12) {
1578
1551
  return _ref6.apply(this, arguments);
1579
1552
  };
1580
1553
  }();
1581
- _this.listProviders = /*#__PURE__*/function () {
1554
+ _this.me = /*#__PURE__*/function () {
1582
1555
  var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(req, init) {
1583
- var _body;
1584
- var _requester, body;
1556
+ var _requester, _init;
1585
1557
  return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1586
1558
  while (1) switch (_context7.prev = _context7.next) {
1587
1559
  case 0:
1588
1560
  _requester = new Requester(_this);
1589
- if (!(req && 'body' in req)) {
1590
- _context7.next = 5;
1591
- break;
1592
- }
1561
+ _init = _this.handleHeaders(init);
1593
1562
  _context7.next = 4;
1594
- return new Response(req.body).json();
1563
+ return _requester.get(req, _this.meUrl, _init);
1595
1564
  case 4:
1596
- body = _context7.sent;
1565
+ return _context7.abrupt("return", _context7.sent);
1597
1566
  case 5:
1598
- return _context7.abrupt("return", _requester.get(req, _this.providerUrl((_body = body) == null ? void 0 : _body.email), init));
1599
- case 6:
1600
1567
  case "end":
1601
1568
  return _context7.stop();
1602
1569
  }
1603
1570
  }, _callee7);
1604
1571
  }));
1605
- return function (_x12, _x13) {
1572
+ return function (_x13, _x14) {
1606
1573
  return _ref7.apply(this, arguments);
1607
1574
  };
1608
1575
  }();
1609
- _this.getSSOCallbackUrl = function (param) {
1610
- var tenantId;
1611
- if (typeof tenantId === 'string') {
1612
- tenantId = param;
1613
- } else if (param instanceof Headers) {
1614
- tenantId = getTenantFromHttp(param, _this);
1615
- }
1616
- return "/databases/" + _this.databaseId + "/tenants/" + tenantId + "/auth/oidc/callback";
1617
- };
1576
+ _this.headers = headers;
1618
1577
  return _this;
1619
1578
  }
1620
- _inheritsLoose(Auth, _Config);
1621
- var _proto = Auth.prototype;
1622
- _proto.updateProviderUrl = function updateProviderUrl(providerName) {
1623
- return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/" + (this.tenantId ? encodeURIComponent(this.tenantId) : '{tenantId}') + "/auth/oidc/providers/" + encodeURIComponent(providerName);
1624
- };
1625
- _proto.providerUrl = function providerUrl(email) {
1626
- return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/auth/oidc/providers" + (email ? "?email=" + encodeURIComponent(email) : '');
1579
+ _inheritsLoose(Users, _Config);
1580
+ var _proto = Users.prototype;
1581
+ _proto.handleHeaders = function handleHeaders(init) {
1582
+ if (this.headers) {
1583
+ if (init) {
1584
+ var _init2;
1585
+ init.headers = new Headers(_extends({}, this.headers, (_init2 = init) == null ? void 0 : _init2.headers));
1586
+ return init;
1587
+ } else {
1588
+ init = {
1589
+ headers: this.headers
1590
+ };
1591
+ return init;
1592
+ }
1593
+ }
1594
+ return undefined;
1627
1595
  };
1628
- return _createClass(Auth, [{
1629
- key: "loginUrl",
1596
+ return _createClass(Users, [{
1597
+ key: "usersUrl",
1630
1598
  get: function get() {
1631
- return "/databases/" + encodeURIComponent(this.databaseId) + "/users/login";
1599
+ return '/users';
1632
1600
  }
1633
1601
  }, {
1634
- key: "signUpUrl",
1602
+ key: "tenantUsersUrl",
1635
1603
  get: function get() {
1636
- return "/databases/" + encodeURIComponent(this.databaseId) + "/users";
1604
+ var _this$tenantId2;
1605
+ return "/tenants/" + ((_this$tenantId2 = this.tenantId) != null ? _this$tenantId2 : '{tenantId}') + "/users";
1637
1606
  }
1638
1607
  }, {
1639
- key: "listTenantProvidersUrl",
1608
+ key: "meUrl",
1640
1609
  get: function get() {
1641
- return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/" + (this.tenantId ? encodeURIComponent(this.tenantId) : '{tenantId}') + "/auth/oidc/providers";
1610
+ return '/me';
1642
1611
  }
1643
1612
  }]);
1644
1613
  }(Config);
1645
1614
 
1646
- var Users = /*#__PURE__*/function (_Config) {
1647
- function Users(config) {
1615
+ var Tenants = /*#__PURE__*/function (_Config) {
1616
+ function Tenants(config, headers) {
1648
1617
  var _this;
1649
1618
  _this = _Config.call(this, config) || this;
1650
- _this.createTenantUser = /*#__PURE__*/function () {
1619
+ _this.headers = void 0;
1620
+ _this.createTenant = /*#__PURE__*/function () {
1651
1621
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
1652
- var _requester;
1622
+ var _requester, _init;
1653
1623
  return _regeneratorRuntime().wrap(function _callee$(_context) {
1654
1624
  while (1) switch (_context.prev = _context.next) {
1655
1625
  case 0:
1656
1626
  _requester = new Requester(_this);
1657
- _context.next = 3;
1658
- return _requester.post(req, _this.tenantUsersUrl, init);
1627
+ _init = _this.handleHeaders(init);
1628
+ return _context.abrupt("return", _requester.post(req, _this.tenantsUrl, _init));
1659
1629
  case 3:
1660
- return _context.abrupt("return", _context.sent);
1661
- case 4:
1662
1630
  case "end":
1663
1631
  return _context.stop();
1664
1632
  }
@@ -1668,18 +1636,16 @@ var Users = /*#__PURE__*/function (_Config) {
1668
1636
  return _ref.apply(this, arguments);
1669
1637
  };
1670
1638
  }();
1671
- _this.listUsers = /*#__PURE__*/function () {
1639
+ _this.getTenant = /*#__PURE__*/function () {
1672
1640
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req, init) {
1673
- var _requester;
1641
+ var _requester, _init;
1674
1642
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1675
1643
  while (1) switch (_context2.prev = _context2.next) {
1676
1644
  case 0:
1677
1645
  _requester = new Requester(_this);
1678
- _context2.next = 3;
1679
- return _requester.get(req, _this.usersUrl, init);
1646
+ _init = _this.handleHeaders(init);
1647
+ return _context2.abrupt("return", _requester.get(req, _this.tenantUrl, _init));
1680
1648
  case 3:
1681
- return _context2.abrupt("return", _context2.sent);
1682
- case 4:
1683
1649
  case "end":
1684
1650
  return _context2.stop();
1685
1651
  }
@@ -1689,166 +1655,53 @@ var Users = /*#__PURE__*/function (_Config) {
1689
1655
  return _ref2.apply(this, arguments);
1690
1656
  };
1691
1657
  }();
1692
- _this.updateUser = /*#__PURE__*/function () {
1693
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(userId, req, init) {
1694
- var _requester;
1695
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1696
- while (1) switch (_context3.prev = _context3.next) {
1697
- case 0:
1698
- _requester = new Requester(_this);
1699
- _context3.next = 3;
1700
- return _requester.put(req, _this.usersUrl + "/" + userId, init);
1701
- case 3:
1702
- return _context3.abrupt("return", _context3.sent);
1703
- case 4:
1704
- case "end":
1705
- return _context3.stop();
1706
- }
1707
- }, _callee3);
1708
- }));
1709
- return function (_x5, _x6, _x7) {
1710
- return _ref3.apply(this, arguments);
1711
- };
1712
- }();
1713
- _this.listTenantUsers = /*#__PURE__*/function () {
1714
- var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, init) {
1715
- var _requester;
1716
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1717
- while (1) switch (_context4.prev = _context4.next) {
1718
- case 0:
1719
- _requester = new Requester(_this);
1720
- _context4.next = 3;
1721
- return _requester.get(req, _this.tenantUsersUrl, init);
1722
- case 3:
1723
- return _context4.abrupt("return", _context4.sent);
1724
- case 4:
1725
- case "end":
1726
- return _context4.stop();
1727
- }
1728
- }, _callee4);
1729
- }));
1730
- return function (_x8, _x9) {
1731
- return _ref4.apply(this, arguments);
1732
- };
1733
- }();
1734
- _this.me = /*#__PURE__*/function () {
1735
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req, init) {
1736
- var _requester;
1737
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1738
- while (1) switch (_context5.prev = _context5.next) {
1739
- case 0:
1740
- _requester = new Requester(_this);
1741
- _context5.next = 3;
1742
- return _requester.get(req, _this.meUrl, init);
1743
- case 3:
1744
- return _context5.abrupt("return", _context5.sent);
1745
- case 4:
1746
- case "end":
1747
- return _context5.stop();
1748
- }
1749
- }, _callee5);
1750
- }));
1751
- return function (_x10, _x11) {
1752
- return _ref5.apply(this, arguments);
1753
- };
1754
- }();
1658
+ _this.headers = headers;
1755
1659
  return _this;
1756
1660
  }
1757
- _inheritsLoose(Users, _Config);
1758
- return _createClass(Users, [{
1759
- key: "baseUrl",
1760
- get: function get() {
1761
- return "/databases/" + encodeURIComponent(this.databaseId);
1661
+ _inheritsLoose(Tenants, _Config);
1662
+ var _proto = Tenants.prototype;
1663
+ _proto.handleHeaders = function handleHeaders(init) {
1664
+ if (this.headers) {
1665
+ if (init) {
1666
+ var _init2;
1667
+ init.headers = new Headers(_extends({}, this.headers, (_init2 = init) == null ? void 0 : _init2.headers));
1668
+ return init;
1669
+ } else {
1670
+ init = {
1671
+ headers: this.headers
1672
+ };
1673
+ return init;
1674
+ }
1762
1675
  }
1763
- }, {
1764
- key: "usersUrl",
1676
+ return undefined;
1677
+ };
1678
+ return _createClass(Tenants, [{
1679
+ key: "tenantsUrl",
1765
1680
  get: function get() {
1766
- return this.baseUrl + "/users";
1681
+ return '/tenants';
1767
1682
  }
1768
1683
  }, {
1769
- key: "tenantUsersUrl",
1684
+ key: "tenantUrl",
1770
1685
  get: function get() {
1771
1686
  var _this$tenantId;
1772
- return this.baseUrl + "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/users";
1773
- }
1774
- }, {
1775
- key: "meUrl",
1776
- get: function get() {
1777
- return "/databases/" + encodeURIComponent(this.databaseId) + "/users/me";
1687
+ return "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}');
1778
1688
  }
1779
1689
  }]);
1780
1690
  }(Config);
1781
1691
 
1782
- var Tenants = /*#__PURE__*/function (_Config) {
1783
- function Tenants(config) {
1784
- var _this;
1785
- _this = _Config.call(this, config) || this;
1786
- _this.createTenant = /*#__PURE__*/function () {
1787
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
1788
- var _requester;
1789
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1790
- while (1) switch (_context.prev = _context.next) {
1791
- case 0:
1792
- _requester = new Requester(_this);
1793
- return _context.abrupt("return", _requester.post(req, _this.tenantsUrl, init));
1794
- case 2:
1795
- case "end":
1796
- return _context.stop();
1797
- }
1798
- }, _callee);
1799
- }));
1800
- return function (_x, _x2) {
1801
- return _ref.apply(this, arguments);
1802
- };
1803
- }();
1804
- _this.getTenant = /*#__PURE__*/function () {
1805
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req, init) {
1806
- var _requester;
1807
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1808
- while (1) switch (_context2.prev = _context2.next) {
1809
- case 0:
1810
- _requester = new Requester(_this);
1811
- return _context2.abrupt("return", _requester.get(req, _this.tenantUrl, init));
1812
- case 2:
1813
- case "end":
1814
- return _context2.stop();
1815
- }
1816
- }, _callee2);
1817
- }));
1818
- return function (_x3, _x4) {
1819
- return _ref2.apply(this, arguments);
1820
- };
1821
- }();
1822
- return _this;
1823
- }
1824
- _inheritsLoose(Tenants, _Config);
1825
- return _createClass(Tenants, [{
1826
- key: "tenantsUrl",
1827
- get: function get() {
1828
- return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants";
1829
- }
1830
- }, {
1831
- key: "tenantUrl",
1832
- get: function get() {
1833
- var _this$tenantId;
1834
- return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}');
1835
- }
1836
- }]);
1837
- }(Config);
1838
-
1839
- function createProxyForPool(pool, config) {
1840
- var _Logger = Logger(config, '[pool]'),
1841
- info = _Logger.info,
1842
- error = _Logger.error;
1843
- return new Proxy(pool, {
1844
- get: function get(target, property) {
1845
- if (property === 'query') {
1846
- // give connection string a pass for these problems
1847
- if (!config.db.connectionString) {
1848
- if (!config.user || !config.password) {
1849
- error('Cannot connect to the database. User and/or password are missing. Generate them at https://console.thenile.dev');
1850
- } else if (!config.db.database) {
1851
- error('Database name is missing from the config. Call `nile.init()` or set NILEDB_ID in your .env');
1692
+ function createProxyForPool(pool, config) {
1693
+ var _Logger = Logger(config, '[pool]'),
1694
+ info = _Logger.info,
1695
+ error = _Logger.error;
1696
+ return new Proxy(pool, {
1697
+ get: function get(target, property) {
1698
+ if (property === 'query') {
1699
+ // give connection string a pass for these problems
1700
+ if (!config.db.connectionString) {
1701
+ if (!config.user || !config.password) {
1702
+ error('Cannot connect to the database. User and/or password are missing. Generate them at https://console.thenile.dev');
1703
+ } else if (!config.db.database) {
1704
+ error('Database name is missing from the config. Call `nile.init()` or set NILEDB_ID in your .env');
1852
1705
  }
1853
1706
  }
1854
1707
  var caller = target[property];
@@ -1867,7 +1720,7 @@ function createProxyForPool(pool, config) {
1867
1720
  });
1868
1721
  }
1869
1722
 
1870
- var _excluded = ["afterCreate"];
1723
+ var _excluded$1 = ["afterCreate"];
1871
1724
  var NileDatabase = /*#__PURE__*/function () {
1872
1725
  function NileDatabase(config, id) {
1873
1726
  var _this = this;
@@ -1887,10 +1740,10 @@ var NileDatabase = /*#__PURE__*/function () {
1887
1740
  idleTimeoutMillis: 30000
1888
1741
  }, config.db);
1889
1742
  var afterCreate = poolConfig.afterCreate,
1890
- remaining = _objectWithoutPropertiesLoose(poolConfig, _excluded);
1743
+ remaining = _objectWithoutPropertiesLoose(poolConfig, _excluded$1);
1891
1744
  config.db = poolConfig;
1892
1745
  this.config = config;
1893
- info(this.config);
1746
+ info(this.config.db);
1894
1747
  this.pool = createProxyForPool(new pg.Pool(remaining), this.config);
1895
1748
  if (typeof afterCreate === 'function') {
1896
1749
  warn('Providing an pool configuration will stop automatic tenant context setting.');
@@ -2082,176 +1935,1920 @@ var makeServerId = function makeServerId(config) {
2082
1935
  return Buffer.from(JSON.stringify(config), 'base64').toString();
2083
1936
  };
2084
1937
 
2085
- var _init = function init(config) {
2086
- var auth = new Auth(config);
2087
- var users = new Users(config);
2088
- var tenants = new Tenants(config);
2089
- return {
2090
- auth: auth,
2091
- users: users,
2092
- tenants: tenants
2093
- };
2094
- };
2095
- var Server = /*#__PURE__*/function () {
2096
- function Server(config) {
2097
- var _this = this;
2098
- this.config = void 0;
2099
- this.api = void 0;
2100
- this.manager = void 0;
2101
- this.servers = void 0;
2102
- this.config = new Config(config, '[initial config]');
2103
- this.servers = new Map();
2104
- this.api = _init(this.config);
2105
- this.manager = new DBManager(this.config);
2106
- watchTenantId(function (tenantId) {
2107
- _this.tenantId = tenantId;
2108
- });
2109
- watchUserId(function (userId) {
2110
- _this.userId = userId;
2111
- });
2112
- watchToken(function (token) {
2113
- _this.token = token;
2114
- });
2115
- }
2116
- var _proto = Server.prototype;
2117
- _proto.setConfig = function setConfig(cfg) {
2118
- this.config = new Config(cfg);
2119
- };
2120
- _proto.init = /*#__PURE__*/function () {
2121
- var _init2 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(cfg) {
2122
- var updatedConfig;
1938
+ /**
1939
+ * a helper function to log in server side.
1940
+ */
1941
+ function serverAuth(config, handlers) {
1942
+ return /*#__PURE__*/function () {
1943
+ var _login = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
1944
+ var _yield$csrfRes$json, _exec;
1945
+ var email, password, sessionUrl, sessionReq, sessionRes, providers, csrf, csrfReq, csrfRes, _ref2, csrfToken, credentials, csrfCookie, signInUrl, postReq, loginRes, authCookie, _ref3, token;
2123
1946
  return _regeneratorRuntime().wrap(function _callee$(_context) {
2124
1947
  while (1) switch (_context.prev = _context.next) {
2125
1948
  case 0:
2126
- _context.next = 2;
2127
- return this.config.configure(_extends({}, this.config, cfg));
2128
- case 2:
2129
- updatedConfig = _context.sent;
2130
- this.setConfig(updatedConfig);
2131
- this.manager.clear(this.config);
2132
- this.manager = new DBManager(this.config);
2133
- this.api = _init(this.config);
2134
- return _context.abrupt("return", this);
1949
+ email = _ref.email, password = _ref.password;
1950
+ sessionUrl = new URL(config.api.localPath + "/api/auth/providers");
1951
+ sessionReq = new Request(sessionUrl, {
1952
+ method: 'GET',
1953
+ headers: new Headers({
1954
+ host: sessionUrl.host
1955
+ })
1956
+ });
1957
+ _context.next = 5;
1958
+ return handlers.POST(sessionReq);
1959
+ case 5:
1960
+ sessionRes = _context.sent;
1961
+ _context.next = 8;
1962
+ return sessionRes == null ? void 0 : sessionRes.json();
2135
1963
  case 8:
1964
+ providers = _context.sent;
1965
+ csrf = new URL(config.api.localPath + "/api/auth/csrf");
1966
+ csrfReq = new Request(csrf, {
1967
+ method: 'GET',
1968
+ headers: new Headers({
1969
+ host: sessionUrl.host
1970
+ })
1971
+ });
1972
+ _context.next = 13;
1973
+ return handlers.POST(csrfReq);
1974
+ case 13:
1975
+ csrfRes = _context.sent;
1976
+ _context.next = 16;
1977
+ return csrfRes == null ? void 0 : csrfRes.json();
1978
+ case 16:
1979
+ _context.t0 = _yield$csrfRes$json = _context.sent;
1980
+ if (!(_context.t0 != null)) {
1981
+ _context.next = 21;
1982
+ break;
1983
+ }
1984
+ _context.t1 = _yield$csrfRes$json;
1985
+ _context.next = 22;
1986
+ break;
1987
+ case 21:
1988
+ _context.t1 = {};
1989
+ case 22:
1990
+ _ref2 = _context.t1;
1991
+ csrfToken = _ref2.csrfToken;
1992
+ credentials = providers.credentials;
1993
+ csrfCookie = csrfRes == null ? void 0 : csrfRes.headers.get('set-cookie');
1994
+ expect(csrfCookie).toContain('nile.csrf-token=');
1995
+ signInUrl = new URL(credentials.callbackUrl);
1996
+ if (csrfCookie) {
1997
+ _context.next = 30;
1998
+ break;
1999
+ }
2000
+ throw new Error('unable to authenticate REST');
2001
+ case 30:
2002
+ postReq = new Request(signInUrl, {
2003
+ method: 'POST',
2004
+ headers: new Headers({
2005
+ 'content-type': 'application/json',
2006
+ cookie: csrfCookie
2007
+ }),
2008
+ body: JSON.stringify({
2009
+ email: email,
2010
+ password: password,
2011
+ csrfToken: csrfToken,
2012
+ callbackUrl: credentials.callbackUrl
2013
+ })
2014
+ });
2015
+ _context.next = 33;
2016
+ return handlers.POST(postReq);
2017
+ case 33:
2018
+ loginRes = _context.sent;
2019
+ authCookie = loginRes == null ? void 0 : loginRes.headers.get('set-cookie');
2020
+ if (authCookie) {
2021
+ _context.next = 37;
2022
+ break;
2023
+ }
2024
+ throw new Error('authentication failed');
2025
+ case 37:
2026
+ expect(authCookie).toContain('nile.session-token=');
2027
+ _ref3 = (_exec = /(nile\.session-token=.+?);/.exec(authCookie)) != null ? _exec : [], token = _ref3[1];
2028
+ return _context.abrupt("return", new Headers({
2029
+ cookie: [token, csrfCookie].join('; ')
2030
+ }));
2031
+ case 40:
2136
2032
  case "end":
2137
2033
  return _context.stop();
2138
2034
  }
2139
- }, _callee, this);
2035
+ }, _callee);
2140
2036
  }));
2141
- function init(_x) {
2142
- return _init2.apply(this, arguments);
2037
+ function login(_x) {
2038
+ return _login.apply(this, arguments);
2143
2039
  }
2144
- return init;
2040
+ return login;
2145
2041
  }();
2146
- /**
2147
- * A utility function if you want to manage different NileDB instances yourself
2148
- * returns the global Server object, an existing server that's already been configured,
2149
- * or a new one if the config isn't in the cache
2150
- */
2151
- _proto.getInstance = function getInstance(config) {
2152
- var _config = _extends({}, this.config, config);
2153
- var serverId = getServerId(_config);
2154
- var currentServerId = makeServerId(this.config);
2155
- if (serverId === currentServerId) {
2156
- return this;
2157
- }
2158
- var existing = this.servers.get(serverId);
2159
- if (existing) {
2160
- // be sure the config is up to date
2161
- var updatedConfig = new Config(_config);
2162
- existing.setConfig(updatedConfig);
2163
- // propagage special config items
2164
- existing.tenantId = updatedConfig.tenantId;
2165
- existing.userId = updatedConfig.userId;
2166
- existing.token = updatedConfig.api.token;
2167
- existing.databaseId = updatedConfig.databaseId;
2168
- return existing;
2169
- }
2170
- this.servers.set(serverId, new Server(_config));
2171
- return this.servers.get(serverId);
2042
+ }
2043
+
2044
+ var appRoutes = function appRoutes(prefix) {
2045
+ if (prefix === void 0) {
2046
+ prefix = '/api';
2047
+ }
2048
+ return {
2049
+ SIGNIN: prefix + "/auth/signin",
2050
+ PROVIDERS: prefix + "/auth/providers",
2051
+ SESSION: prefix + "/auth/session",
2052
+ CSRF: prefix + "/auth/csrf",
2053
+ CALLBACK: prefix + "/auth/callback",
2054
+ SIGNOUT: prefix + "/auth/signout",
2055
+ ERROR: prefix + "/auth/error",
2056
+ ME: prefix + "/me",
2057
+ USERS: prefix + "/users",
2058
+ TENANTS: prefix + "/tenants",
2059
+ TENANT_USER: prefix + "/tenants/{tenantId}/users/{userId}",
2060
+ TENANT_USERS: prefix + "/tenants/{tenantId}/users",
2061
+ SIGNUP: prefix + "/signup"
2172
2062
  };
2173
- return _createClass(Server, [{
2174
- key: "databaseId",
2175
- set: function set(val) {
2176
- if (val) {
2177
- this.config.databaseId = val;
2178
- this.api.auth.databaseId = val;
2179
- this.api.users.databaseId = val;
2180
- this.api.tenants.databaseId = val;
2181
- }
2182
- }
2183
- }, {
2184
- key: "userId",
2185
- get: function get() {
2186
- return this.config.userId;
2187
- },
2188
- set: function set(userId) {
2189
- this.databaseId = this.config.databaseId;
2190
- this.config.userId = userId;
2191
- if (this.api) {
2192
- this.api.auth.userId = this.config.userId;
2193
- this.api.users.userId = this.config.userId;
2194
- this.api.tenants.userId = this.config.userId;
2195
- }
2196
- }
2197
- }, {
2198
- key: "tenantId",
2199
- get: function get() {
2200
- return this.config.tenantId;
2201
- },
2202
- set: function set(tenantId) {
2203
- this.databaseId = this.config.databaseId;
2204
- this.config.tenantId = tenantId;
2205
- if (this.api) {
2206
- this.api.auth.tenantId = tenantId;
2207
- this.api.users.tenantId = tenantId;
2208
- this.api.tenants.tenantId = tenantId;
2063
+ };
2064
+
2065
+ var NILEDB_API_URL = process.env.NILEDB_API_URL;
2066
+ function makeRestUrl(path, qp) {
2067
+ if (!NILEDB_API_URL) {
2068
+ throw new Error('An API url is required. Set it via NILEDB_API_URL.');
2069
+ }
2070
+ var params = new URLSearchParams(qp);
2071
+ return "" + [NILEDB_API_URL, path.substring(1, path.length)].join('/') + (qp ? "?" + params.toString() : '');
2072
+ }
2073
+
2074
+ var apiRoutes = {
2075
+ ME: /*#__PURE__*/makeRestUrl('/me'),
2076
+ USERS: function USERS(tenantId) {
2077
+ return makeRestUrl('/users', tenantId ? {
2078
+ tenantId: tenantId
2079
+ } : undefined);
2080
+ },
2081
+ USER: function USER(userId) {
2082
+ return makeRestUrl("/users/" + userId);
2083
+ },
2084
+ TENANTS: /*#__PURE__*/makeRestUrl('/tenants'),
2085
+ TENANT: function TENANT(tenantId) {
2086
+ return makeRestUrl("/tenants/" + tenantId);
2087
+ },
2088
+ SIGNUP: /*#__PURE__*/makeRestUrl('/signup'),
2089
+ TENANT_USERS: function TENANT_USERS(tenantId) {
2090
+ return makeRestUrl("/tenants/" + tenantId + "/users");
2091
+ },
2092
+ TENANT_USER: function TENANT_USER(tenantId, userId) {
2093
+ return makeRestUrl("/tenants/" + tenantId + "/users/" + userId);
2094
+ },
2095
+ USER_TENANTS: function USER_TENANTS(userId) {
2096
+ return makeRestUrl("/users/" + userId + "/tenants");
2097
+ }
2098
+ };
2099
+
2100
+ function urlMatches(requestUrl, route) {
2101
+ var url = new URL(requestUrl);
2102
+ return url.pathname.startsWith(route);
2103
+ }
2104
+
2105
+ var _excluded = ["request"];
2106
+ // const { log } = console;
2107
+ function request(_x, _x2) {
2108
+ return _request.apply(this, arguments);
2109
+ }
2110
+ function _request() {
2111
+ _request = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(url, _init) {
2112
+ var request, init, requestUrl, updatedHeaders, params, _init$body, res;
2113
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2114
+ while (1) switch (_context.prev = _context.next) {
2115
+ case 0:
2116
+ request = _init.request, init = _objectWithoutPropertiesLoose(_init, _excluded);
2117
+ requestUrl = new URL(request.url);
2118
+ updatedHeaders = new Headers(request.headers); // updatedHeaders.delete('content-length');
2119
+ // updatedHeaders.delete('transfer-encoding');
2120
+ updatedHeaders.set('niledb-origin', requestUrl.origin);
2121
+ updatedHeaders.set('niledb-creds', Buffer.from(process.env.NILEDB_USER + ":" + process.env.NILEDB_PASSWORD).toString('base64'));
2122
+ params = _extends({}, init, {
2123
+ headers: updatedHeaders
2124
+ });
2125
+ if (params.method === 'POST' || params.method === 'PUT') {
2126
+ updatedHeaders.set('content-type', 'text/plain;charset=UTF-8');
2127
+ params.body = (_init$body = init.body) != null ? _init$body : request.body;
2128
+ // @ts-expect-error - its there
2129
+ params.duplex = 'half';
2130
+ }
2131
+ // log(`[${params.method ?? 'GET'}]`, url);
2132
+ _context.next = 9;
2133
+ return fetch(url, _extends({}, params))["catch"](function () {
2134
+ // log('An error has occurred in the fetch', e);
2135
+ });
2136
+ case 9:
2137
+ res = _context.sent;
2138
+ return _context.abrupt("return", res);
2139
+ case 11:
2140
+ case "end":
2141
+ return _context.stop();
2209
2142
  }
2210
- }
2211
- }, {
2212
- key: "token",
2213
- get: function get() {
2214
- var _this$config;
2215
- return (_this$config = this.config) == null || (_this$config = _this$config.api) == null ? void 0 : _this$config.token;
2216
- },
2217
- set: function set(token) {
2218
- if (token) {
2219
- this.config.api.token = token;
2220
- if (this.api) {
2221
- this.api.auth.api.token = token;
2222
- this.api.users.api.token = token;
2223
- this.api.tenants.api.token = token;
2224
- }
2143
+ }, _callee);
2144
+ }));
2145
+ return _request.apply(this, arguments);
2146
+ }
2147
+
2148
+ var key$6 = 'ME';
2149
+ var url = apiRoutes[key$6];
2150
+ /**
2151
+ * @swagger
2152
+ * /api/me:
2153
+ * get:
2154
+ * summary: Identify the principal
2155
+ * description: Returns information about the principal associated with the session
2156
+ * provided
2157
+ * operationId: me
2158
+ * responses:
2159
+ * "200":
2160
+ * description: Identified user
2161
+ * content:
2162
+ * application/json:
2163
+ * schema:
2164
+ * $ref: '#/components/schemas/User'
2165
+ * "400":
2166
+ * description: API/Database failures
2167
+ * content:
2168
+ * text/plain:
2169
+ * schema:
2170
+ * type: string
2171
+ * "404":
2172
+ * description: Not found
2173
+ * content: {}
2174
+ * "401":
2175
+ * description: Unauthorized
2176
+ * content: {}
2177
+ */
2178
+ function GET$3(_x, _x2) {
2179
+ return _GET$3.apply(this, arguments);
2180
+ }
2181
+ function _GET$3() {
2182
+ _GET$3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(init, log) {
2183
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2184
+ while (1) switch (_context.prev = _context.next) {
2185
+ case 0:
2186
+ log('[GET]');
2187
+ _context.next = 3;
2188
+ return request(url, init);
2189
+ case 3:
2190
+ return _context.abrupt("return", _context.sent);
2191
+ case 4:
2192
+ case "end":
2193
+ return _context.stop();
2225
2194
  }
2226
- }
2227
- }, {
2228
- key: "db",
2229
- get: function get() {
2230
- // only need to interact with the knex object
2231
- return this.manager.getConnection(this.config);
2232
- }
2233
- }]);
2234
- }();
2235
- function create(_x2) {
2236
- return _create.apply(this, arguments);
2195
+ }, _callee);
2196
+ }));
2197
+ return _GET$3.apply(this, arguments);
2237
2198
  }
2238
- function _create() {
2239
- _create = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(config) {
2240
- var server;
2199
+ function route$a(_x3, _x4) {
2200
+ return _route$a.apply(this, arguments);
2201
+ }
2202
+ function _route$a() {
2203
+ _route$a = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(request, config) {
2204
+ var _Logger, info;
2241
2205
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
2242
2206
  while (1) switch (_context2.prev = _context2.next) {
2243
2207
  case 0:
2244
- server = new Server(config);
2245
- _context2.next = 3;
2246
- return server.init();
2247
- case 3:
2248
- return _context2.abrupt("return", _context2.sent);
2208
+ _Logger = Logger(_extends({}, config, {
2209
+ debug: config.debug
2210
+ }), '[ROUTES]', "[" + key$6 + "]"), info = _Logger.info;
2211
+ _context2.t0 = request.method;
2212
+ _context2.next = _context2.t0 === 'GET' ? 4 : 7;
2213
+ break;
2249
2214
  case 4:
2215
+ _context2.next = 6;
2216
+ return GET$3({
2217
+ request: request
2218
+ }, info);
2219
+ case 6:
2220
+ return _context2.abrupt("return", _context2.sent);
2221
+ case 7:
2222
+ return _context2.abrupt("return", new Response('method not allowed', {
2223
+ status: 405
2224
+ }));
2225
+ case 8:
2250
2226
  case "end":
2251
2227
  return _context2.stop();
2252
2228
  }
2253
2229
  }, _callee2);
2254
2230
  }));
2231
+ return _route$a.apply(this, arguments);
2232
+ }
2233
+ function matches$a(configRoutes, request) {
2234
+ return urlMatches(request.url, configRoutes[key$6]);
2235
+ }
2236
+
2237
+ function auth(_x, _x2) {
2238
+ return _auth.apply(this, arguments);
2239
+ }
2240
+ function _auth() {
2241
+ _auth = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, config) {
2242
+ var _Logger, info, sessionUrl, res;
2243
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2244
+ while (1) switch (_context.prev = _context.next) {
2245
+ case 0:
2246
+ _Logger = Logger(_extends({}, config, {
2247
+ debug: true
2248
+ }), '[nileauth]'), info = _Logger.info;
2249
+ info('checking auth');
2250
+ sessionUrl = config.api.basePath + "/auth/session";
2251
+ info('using session', sessionUrl);
2252
+ _context.next = 6;
2253
+ return request(sessionUrl, {
2254
+ request: req
2255
+ });
2256
+ case 6:
2257
+ res = _context.sent;
2258
+ if (res) {
2259
+ _context.next = 10;
2260
+ break;
2261
+ }
2262
+ info('no session found');
2263
+ return _context.abrupt("return", undefined);
2264
+ case 10:
2265
+ info('session active');
2266
+ _context.next = 13;
2267
+ return new Response(res.body).json();
2268
+ case 13:
2269
+ return _context.abrupt("return", _context.sent);
2270
+ case 14:
2271
+ case "end":
2272
+ return _context.stop();
2273
+ }
2274
+ }, _callee);
2275
+ }));
2276
+ return _auth.apply(this, arguments);
2277
+ }
2278
+
2279
+ /**
2280
+ * @swagger
2281
+ * /api/users:
2282
+ * post:
2283
+ * tags:
2284
+ * - users
2285
+ * summary: Creates a user
2286
+ * description: Creates a user in the database
2287
+ * operationId: createUser
2288
+ * parameters:
2289
+ * - name: tenantId
2290
+ * description: A tenant id to add the user to when they are created
2291
+ * in: query
2292
+ * schema:
2293
+ * type: string
2294
+ * - name: newTenantName
2295
+ * description: A tenant name to create, then the user to when they are created
2296
+ * in: query
2297
+ * schema:
2298
+ * type: string
2299
+ * requestBody:
2300
+ * description: |-
2301
+ * The email and password combination the user will use to authenticate.
2302
+ * The `name` is optional; if provided it will be recorded in the `users` table.
2303
+ * The `newTenant` is optional; if provided, it is used as the name of a new tenant record associated with the newly created user.
2304
+ * content:
2305
+ * application/json:
2306
+ * schema:
2307
+ * $ref: '#/components/schemas/CreateBasicUserRequest'
2308
+ * examples:
2309
+ * Create User Request:
2310
+ * summary: Creates a user with basic credentials
2311
+ * description: Create User Request
2312
+ * value:
2313
+ * email: a.user@somedomain.com
2314
+ * password: somepassword
2315
+ * name: A. User
2316
+ * Create User Request with Tenant:
2317
+ * summary: Creates a user and a new tenant for that user
2318
+ * description: Create User Request with Tenant
2319
+ * value:
2320
+ * email: a.user@somedomain.com
2321
+ * password: somepassword
2322
+ * name: A. User
2323
+ * newTenant: My Sandbox
2324
+ * responses:
2325
+ * "201":
2326
+ * description: User created
2327
+ * content:
2328
+ * application/json:
2329
+ * schema:
2330
+ * $ref: "#/components/schemas/User"
2331
+ * "400":
2332
+ * description: API/Database failures
2333
+ * content:
2334
+ * text/plain:
2335
+ * schema:
2336
+ * type: string
2337
+ * "401":
2338
+ * description: Unauthorized
2339
+ * content: {}
2340
+ */
2341
+ function POST$2(_x, _x2, _x3) {
2342
+ return _POST$2.apply(this, arguments);
2343
+ }
2344
+ function _POST$2() {
2345
+ _POST$2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2346
+ var yurl, tenantId, tenant, url;
2347
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2348
+ while (1) switch (_context.prev = _context.next) {
2349
+ case 0:
2350
+ if (session) {
2351
+ _context.next = 2;
2352
+ break;
2353
+ }
2354
+ return _context.abrupt("return", new Response(null, {
2355
+ status: 401
2356
+ }));
2357
+ case 2:
2358
+ init.body = init.request.body;
2359
+ init.method = 'POST';
2360
+ yurl = new URL(init.request.url);
2361
+ tenantId = yurl.searchParams.get('tenantId');
2362
+ tenant = tenantId != null ? tenantId : getTenantFromHttp(init.request.headers);
2363
+ url = apiRoutes.USERS(tenant ? tenant : undefined);
2364
+ log && log('[POST]', url);
2365
+ _context.next = 11;
2366
+ return request(url, init);
2367
+ case 11:
2368
+ return _context.abrupt("return", _context.sent);
2369
+ case 12:
2370
+ case "end":
2371
+ return _context.stop();
2372
+ }
2373
+ }, _callee);
2374
+ }));
2375
+ return _POST$2.apply(this, arguments);
2376
+ }
2377
+
2378
+ /**
2379
+ * @swagger
2380
+ * /api/users:
2381
+ * get:
2382
+ * tags:
2383
+ * - users
2384
+ * summary: lists users in the tenant
2385
+ * description: Returns information about the users within the tenant
2386
+ * provided. You can also pass the a `niledb-tenantId` in the header or in a cookie.
2387
+ * operationId: listUsers
2388
+ * parameters:
2389
+ * - name: tenantId
2390
+ * in: query
2391
+ * schema:
2392
+ * type: string
2393
+ * responses:
2394
+ * "200":
2395
+ * description: A list of users
2396
+ * content:
2397
+ * application/json:
2398
+ * schema:
2399
+ * type: array
2400
+ * items:
2401
+ * $ref: '#/components/schemas/TenantUser'
2402
+ * "404":
2403
+ * description: Not found
2404
+ * content: {}
2405
+ * "401":
2406
+ * description: Unauthorized
2407
+ * content: {}
2408
+ */
2409
+ function GET$2(_x, _x2) {
2410
+ return _GET$2.apply(this, arguments);
2411
+ }
2412
+ function _GET$2() {
2413
+ _GET$2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(init, log) {
2414
+ var yurl, tenantId, tenant, url;
2415
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2416
+ while (1) switch (_context.prev = _context.next) {
2417
+ case 0:
2418
+ yurl = new URL(init.request.url);
2419
+ tenantId = yurl.searchParams.get('tenantId');
2420
+ tenant = tenantId != null ? tenantId : getTenantFromHttp(init.request.headers);
2421
+ if (tenant) {
2422
+ _context.next = 6;
2423
+ break;
2424
+ }
2425
+ log('[GET]', '[ERROR]', 'No tenant id provided.');
2426
+ return _context.abrupt("return", new Response(null, {
2427
+ status: 404
2428
+ }));
2429
+ case 6:
2430
+ url = apiRoutes.TENANT_USERS(tenant);
2431
+ log('[GET]', url);
2432
+ init.method = 'GET';
2433
+ _context.next = 11;
2434
+ return request(url, init);
2435
+ case 11:
2436
+ return _context.abrupt("return", _context.sent);
2437
+ case 12:
2438
+ case "end":
2439
+ return _context.stop();
2440
+ }
2441
+ }, _callee);
2442
+ }));
2443
+ return _GET$2.apply(this, arguments);
2444
+ }
2445
+
2446
+ /**
2447
+ * @swagger
2448
+ * /api/users/{userid}:
2449
+ * put:
2450
+ * tags:
2451
+ * - users
2452
+ * summary: update a user
2453
+ * description: updates a user within the tenant
2454
+ * operationId: updateUser
2455
+ * parameters:
2456
+ * - name: userid
2457
+ * in: path
2458
+ * required: true
2459
+ * schema:
2460
+ * type: string
2461
+ * requestBody:
2462
+ * description: |-
2463
+ * Update a user
2464
+ * content:
2465
+ * application/json:
2466
+ * schema:
2467
+ * $ref: '#/components/schemas/UpdateUserRequest'
2468
+ * responses:
2469
+ * "200":
2470
+ * description: An updated user
2471
+ * content:
2472
+ * application/json:
2473
+ * schema:
2474
+ * $ref: '#/components/schemas/User'
2475
+ * "404":
2476
+ * description: Not found
2477
+ * content: {}
2478
+ * "401":
2479
+ * description: Unauthorized
2480
+ * content: {}
2481
+ */
2482
+ function PUT$1(_x, _x2, _x3) {
2483
+ return _PUT$1.apply(this, arguments);
2484
+ }
2485
+ function _PUT$1() {
2486
+ _PUT$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2487
+ var _URL$pathname$split$r, userId, url;
2488
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2489
+ while (1) switch (_context.prev = _context.next) {
2490
+ case 0:
2491
+ if (session) {
2492
+ _context.next = 2;
2493
+ break;
2494
+ }
2495
+ return _context.abrupt("return", new Response(null, {
2496
+ status: 401
2497
+ }));
2498
+ case 2:
2499
+ init.body = init.request.body;
2500
+ init.method = 'PUT';
2501
+ // update the user
2502
+ _URL$pathname$split$r = new URL(init.request.url).pathname.split('/').reverse(), userId = _URL$pathname$split$r[0];
2503
+ url = apiRoutes.USER(userId);
2504
+ log('[PUT]', url);
2505
+ _context.next = 9;
2506
+ return request(url, init);
2507
+ case 9:
2508
+ return _context.abrupt("return", _context.sent);
2509
+ case 10:
2510
+ case "end":
2511
+ return _context.stop();
2512
+ }
2513
+ }, _callee);
2514
+ }));
2515
+ return _PUT$1.apply(this, arguments);
2516
+ }
2517
+
2518
+ var key$5 = 'USERS';
2519
+ function route$9(_x, _x2) {
2520
+ return _route$9.apply(this, arguments);
2521
+ }
2522
+ function _route$9() {
2523
+ _route$9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request, config) {
2524
+ var _Logger, info, session;
2525
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2526
+ while (1) switch (_context.prev = _context.next) {
2527
+ case 0:
2528
+ _Logger = Logger(_extends({}, config, {
2529
+ debug: config.debug
2530
+ }), '[ROUTES]', "[" + key$5 + "]"), info = _Logger.info;
2531
+ _context.next = 3;
2532
+ return auth(request, config);
2533
+ case 3:
2534
+ session = _context.sent;
2535
+ _context.t0 = request.method;
2536
+ _context.next = _context.t0 === 'GET' ? 7 : _context.t0 === 'POST' ? 10 : _context.t0 === 'PUT' ? 13 : 16;
2537
+ break;
2538
+ case 7:
2539
+ _context.next = 9;
2540
+ return GET$2({
2541
+ request: request
2542
+ }, info);
2543
+ case 9:
2544
+ return _context.abrupt("return", _context.sent);
2545
+ case 10:
2546
+ _context.next = 12;
2547
+ return POST$2(session, {
2548
+ request: request
2549
+ }, info);
2550
+ case 12:
2551
+ return _context.abrupt("return", _context.sent);
2552
+ case 13:
2553
+ _context.next = 15;
2554
+ return PUT$1(session, {
2555
+ request: request
2556
+ }, info);
2557
+ case 15:
2558
+ return _context.abrupt("return", _context.sent);
2559
+ case 16:
2560
+ return _context.abrupt("return", new Response('method not allowed', {
2561
+ status: 405
2562
+ }));
2563
+ case 17:
2564
+ case "end":
2565
+ return _context.stop();
2566
+ }
2567
+ }, _callee);
2568
+ }));
2569
+ return _route$9.apply(this, arguments);
2570
+ }
2571
+ function matches$9(configRoutes, request) {
2572
+ return urlMatches(request.url, configRoutes[key$5]);
2573
+ }
2574
+
2575
+ /**
2576
+ * @swagger
2577
+ * /api/tenants/{tenantId}/users:
2578
+ * get:
2579
+ * tags:
2580
+ * - users
2581
+ * summary: List tenant users
2582
+ * description: Lists users that are associated with the specified tenant.
2583
+ * operationId: listTenantUsers
2584
+ * parameters:
2585
+ * - name: tenantId
2586
+ * in: path
2587
+ * required: true
2588
+ * schema:
2589
+ * type: string
2590
+ * responses:
2591
+ * "200":
2592
+ * description: Users found
2593
+ * content:
2594
+ * application/json:
2595
+ * schema:
2596
+ * type: array
2597
+ * items:
2598
+ * $ref: '#/components/schemas/User'
2599
+ * "401":
2600
+ * description: Unauthorized
2601
+ * content:
2602
+ * application/json:
2603
+ * schema:
2604
+ * $ref: '#/components/schemas/APIError'
2605
+ */
2606
+ function GET$1(_x, _x2, _x3) {
2607
+ return _GET$1.apply(this, arguments);
2608
+ }
2609
+ function _GET$1() {
2610
+ _GET$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2611
+ var yurl, _yurl$pathname$split$, tenantId, url;
2612
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2613
+ while (1) switch (_context.prev = _context.next) {
2614
+ case 0:
2615
+ yurl = new URL(init.request.url);
2616
+ _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[1];
2617
+ if (tenantId) {
2618
+ _context.next = 4;
2619
+ break;
2620
+ }
2621
+ return _context.abrupt("return", new Response(null, {
2622
+ status: 404
2623
+ }));
2624
+ case 4:
2625
+ url = "" + apiRoutes.TENANT_USERS(tenantId);
2626
+ log('[GET]', '[TENANT_USERS]', url);
2627
+ _context.next = 8;
2628
+ return request(url, init);
2629
+ case 8:
2630
+ return _context.abrupt("return", _context.sent);
2631
+ case 9:
2632
+ case "end":
2633
+ return _context.stop();
2634
+ }
2635
+ }, _callee);
2636
+ }));
2637
+ return _GET$1.apply(this, arguments);
2638
+ }
2639
+
2640
+ /**
2641
+ * @swagger
2642
+ * /api/tenants/{tenantId}/users:
2643
+ * post:
2644
+ * tags:
2645
+ * - users
2646
+ * summary: Create a user in a tenant
2647
+ * description: Creates a new user and associates that user with the specified
2648
+ * tenant.
2649
+ * operationId: createTenantUser
2650
+ * parameters:
2651
+ * - name: tenantId
2652
+ * in: path
2653
+ * required: true
2654
+ * schema:
2655
+ * type: string
2656
+ * requestBody:
2657
+ * description: |
2658
+ * The email and password combination the user will use to authenticate.
2659
+ * The `name` is optional; if provided it will be recorded in the `users` table.
2660
+ * content:
2661
+ * application/json:
2662
+ * schema:
2663
+ * $ref: '#/components/schemas/CreateBasicUserRequest'
2664
+ * examples:
2665
+ * Create User Request:
2666
+ * summary: Creates a user with basic credentials
2667
+ * description: Create User Request
2668
+ * value:
2669
+ * email: a.user@somedomain.com
2670
+ * password: somepassword
2671
+ * name: A. User
2672
+ * responses:
2673
+ * "201":
2674
+ * description: User created
2675
+ * content:
2676
+ * application/json:
2677
+ * schema:
2678
+ * $ref: '#/components/schemas/User'
2679
+ */
2680
+ function POST$1(_x, _x2, _x3) {
2681
+ return _POST$1.apply(this, arguments);
2682
+ }
2683
+ function _POST$1() {
2684
+ _POST$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2685
+ var yurl, _yurl$pathname$split$, tenantId, url;
2686
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2687
+ while (1) switch (_context.prev = _context.next) {
2688
+ case 0:
2689
+ yurl = new URL(init.request.url);
2690
+ _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[1]; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2691
+ // @ts-ignore
2692
+ init.body = JSON.stringify({
2693
+ email: session.email
2694
+ });
2695
+ init.method = 'PUT';
2696
+ url = apiRoutes.TENANT_USERS(tenantId);
2697
+ log('[PUT]', url);
2698
+ _context.next = 8;
2699
+ return request(url, init);
2700
+ case 8:
2701
+ return _context.abrupt("return", _context.sent);
2702
+ case 9:
2703
+ case "end":
2704
+ return _context.stop();
2705
+ }
2706
+ }, _callee);
2707
+ }));
2708
+ return _POST$1.apply(this, arguments);
2709
+ }
2710
+
2711
+ /**
2712
+ * @swagger
2713
+ * /api/tenants/{tenantId}/users/{userId}:
2714
+ * delete:
2715
+ * tags:
2716
+ * - tenants
2717
+ * summary: removes a user from a tenant
2718
+ * description: removes an associated user from a specified
2719
+ * tenant.
2720
+ * operationId: unlinkUser
2721
+ * parameters:
2722
+ * - name: tenantId
2723
+ * in: path
2724
+ * required: true
2725
+ * schema:
2726
+ * type: string
2727
+ * - name: userId
2728
+ * in: path
2729
+ * required: true
2730
+ * schema:
2731
+ * type: string
2732
+
2733
+ * responses:
2734
+ * "204":
2735
+ * description: User removed
2736
+ */
2737
+ function DELETE$1(_x, _x2, _x3) {
2738
+ return _DELETE$1.apply(this, arguments);
2739
+ }
2740
+ function _DELETE$1() {
2741
+ _DELETE$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2742
+ var yurl, _yurl$pathname$split$, userId, tenantId, url;
2743
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2744
+ while (1) switch (_context.prev = _context.next) {
2745
+ case 0:
2746
+ yurl = new URL(init.request.url); // eslint-disable-next-line @typescript-eslint/no-unused-vars
2747
+ _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), userId = _yurl$pathname$split$[0], tenantId = _yurl$pathname$split$[2];
2748
+ if (tenantId) {
2749
+ _context.next = 4;
2750
+ break;
2751
+ }
2752
+ return _context.abrupt("return", new Response(null, {
2753
+ status: 404
2754
+ }));
2755
+ case 4:
2756
+ init.method = 'DELETE';
2757
+ url = "" + apiRoutes.TENANT_USER(tenantId, userId);
2758
+ log('[DELETE]', url);
2759
+ _context.next = 9;
2760
+ return request(url, init);
2761
+ case 9:
2762
+ return _context.abrupt("return", _context.sent);
2763
+ case 10:
2764
+ case "end":
2765
+ return _context.stop();
2766
+ }
2767
+ }, _callee);
2768
+ }));
2769
+ return _DELETE$1.apply(this, arguments);
2770
+ }
2771
+
2772
+ /**
2773
+ * @swagger
2774
+ * /api/tenants/{tenantId}/users:
2775
+ * put:
2776
+ * tags:
2777
+ * - tenants
2778
+ * summary: associates an existing user with the tenant
2779
+ * operationId: linkUser
2780
+ * parameters:
2781
+ * - name: tenantId
2782
+ * in: path
2783
+ * required: true
2784
+ * schema:
2785
+ * type: string
2786
+ * requestBody:
2787
+ * description: |
2788
+ * The email and password combination the user will use to authenticate.
2789
+ * The `name` is optional; if provided it will be recorded in the `users` table.
2790
+ * content:
2791
+ * application/json:
2792
+ * schema:
2793
+ * $ref: '#/components/schemas/AssociateUserRequest'
2794
+ * responses:
2795
+ * "201":
2796
+ * description: add user to tenant
2797
+ */
2798
+ function PUT(_x, _x2, _x3) {
2799
+ return _PUT.apply(this, arguments);
2800
+ }
2801
+ function _PUT() {
2802
+ _PUT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2803
+ var yurl, _yurl$pathname$split$, tenantId, url;
2804
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2805
+ while (1) switch (_context.prev = _context.next) {
2806
+ case 0:
2807
+ yurl = new URL(init.request.url);
2808
+ _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[1];
2809
+ if (tenantId) {
2810
+ _context.next = 4;
2811
+ break;
2812
+ }
2813
+ return _context.abrupt("return", new Response(null, {
2814
+ status: 404
2815
+ }));
2816
+ case 4:
2817
+ init.method = 'PUT';
2818
+ url = "" + apiRoutes.TENANT_USERS(tenantId);
2819
+ log('[PUT]', url);
2820
+ _context.next = 9;
2821
+ return request(url, init);
2822
+ case 9:
2823
+ return _context.abrupt("return", _context.sent);
2824
+ case 10:
2825
+ case "end":
2826
+ return _context.stop();
2827
+ }
2828
+ }, _callee);
2829
+ }));
2830
+ return _PUT.apply(this, arguments);
2831
+ }
2832
+
2833
+ var key$4 = 'TENANT_USERS';
2834
+ function route$8(_x, _x2) {
2835
+ return _route$8.apply(this, arguments);
2836
+ }
2837
+ function _route$8() {
2838
+ _route$8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request, config) {
2839
+ var _Logger, info, session;
2840
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2841
+ while (1) switch (_context.prev = _context.next) {
2842
+ case 0:
2843
+ _Logger = Logger(_extends({}, config, {
2844
+ debug: config.debug
2845
+ }), '[ROUTES]', "[" + key$4 + "]"), info = _Logger.info;
2846
+ _context.next = 3;
2847
+ return auth(request, config);
2848
+ case 3:
2849
+ session = _context.sent;
2850
+ if (session) {
2851
+ _context.next = 7;
2852
+ break;
2853
+ }
2854
+ info('401');
2855
+ return _context.abrupt("return", new Response(null, {
2856
+ status: 401
2857
+ }));
2858
+ case 7:
2859
+ _context.t0 = request.method;
2860
+ _context.next = _context.t0 === 'GET' ? 10 : _context.t0 === 'POST' ? 13 : _context.t0 === 'PUT' ? 16 : _context.t0 === 'DELETE' ? 19 : 22;
2861
+ break;
2862
+ case 10:
2863
+ _context.next = 12;
2864
+ return GET$1(session, {
2865
+ request: request
2866
+ }, info);
2867
+ case 12:
2868
+ return _context.abrupt("return", _context.sent);
2869
+ case 13:
2870
+ _context.next = 15;
2871
+ return POST$1(session, {
2872
+ request: request
2873
+ }, info);
2874
+ case 15:
2875
+ return _context.abrupt("return", _context.sent);
2876
+ case 16:
2877
+ _context.next = 18;
2878
+ return PUT(session, {
2879
+ request: request
2880
+ }, info);
2881
+ case 18:
2882
+ return _context.abrupt("return", _context.sent);
2883
+ case 19:
2884
+ _context.next = 21;
2885
+ return DELETE$1(session, {
2886
+ request: request
2887
+ }, info);
2888
+ case 21:
2889
+ return _context.abrupt("return", _context.sent);
2890
+ case 22:
2891
+ return _context.abrupt("return", new Response('method not allowed', {
2892
+ status: 405
2893
+ }));
2894
+ case 23:
2895
+ case "end":
2896
+ return _context.stop();
2897
+ }
2898
+ }, _callee);
2899
+ }));
2900
+ return _route$8.apply(this, arguments);
2901
+ }
2902
+ function matches$8(configRoutes, request) {
2903
+ var url = new URL(request.url);
2904
+ var _url$pathname$split$r = url.pathname.split('/').reverse(),
2905
+ userId = _url$pathname$split$r[0],
2906
+ possibleTenantId = _url$pathname$split$r[1],
2907
+ tenantId = _url$pathname$split$r[2];
2908
+ var route = configRoutes[key$4].replace('{tenantId}', tenantId).replace('{userId}', userId);
2909
+ if (userId === 'users') {
2910
+ route = configRoutes[key$4].replace('{tenantId}', possibleTenantId);
2911
+ }
2912
+ return urlMatches(request.url, route);
2913
+ }
2914
+
2915
+ /**
2916
+ * @swagger
2917
+ * /api/tenants:
2918
+ * get:
2919
+ * tags:
2920
+ * - tenants
2921
+ * summary: list tenants by user
2922
+ * description: Creates a user in the database
2923
+ * operationId: listTenants
2924
+ * responses:
2925
+ * "200":
2926
+ * description: a list of tenants
2927
+ * content:
2928
+ * application/json:
2929
+ * schema:
2930
+ * type: array
2931
+ * items:
2932
+ * $ref: "#/components/schemas/Tenant"
2933
+ * "400":
2934
+ * description: API/Database failures
2935
+ * content:
2936
+ * text/plain:
2937
+ * schema:
2938
+ * type: string
2939
+ * "401":
2940
+ * description: Unauthorized
2941
+ * content: {}
2942
+ */
2943
+ function GET(_x, _x2, _x3) {
2944
+ return _GET.apply(this, arguments);
2945
+ }
2946
+ function _GET() {
2947
+ _GET = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2948
+ var url;
2949
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2950
+ while (1) switch (_context.prev = _context.next) {
2951
+ case 0:
2952
+ url = "" + apiRoutes.USER_TENANTS(session.id);
2953
+ log('[GET]', url);
2954
+ _context.next = 4;
2955
+ return request(url, init);
2956
+ case 4:
2957
+ return _context.abrupt("return", _context.sent);
2958
+ case 5:
2959
+ case "end":
2960
+ return _context.stop();
2961
+ }
2962
+ }, _callee);
2963
+ }));
2964
+ return _GET.apply(this, arguments);
2965
+ }
2966
+
2967
+ /**
2968
+ * @swagger
2969
+ * /api/tenants/{tenantId}:
2970
+ * delete:
2971
+ * tags:
2972
+ * - tenants
2973
+ * summary: Deletes a tenant.
2974
+ * operationId: deleteTenant
2975
+ * parameters:
2976
+ * - name: tenantId
2977
+ * in: path
2978
+ * required: true
2979
+ * schema:
2980
+ * type: string
2981
+ * responses:
2982
+ * "204":
2983
+ * description: Tenant deleted
2984
+ * "401":
2985
+ * description: Unauthorized
2986
+ * content:
2987
+ * application/json:
2988
+ * schema:
2989
+ * $ref: '#/components/schemas/APIError'
2990
+ * "404":
2991
+ * description: Tenant not found
2992
+ * content:
2993
+ * application/json:
2994
+ * schema:
2995
+ * $ref: '#/components/schemas/APIError'
2996
+ */
2997
+ function DELETE(_x, _x2, _x3) {
2998
+ return _DELETE.apply(this, arguments);
2999
+ }
3000
+ function _DELETE() {
3001
+ _DELETE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
3002
+ var yurl, _yurl$pathname$split$, tenantId, url;
3003
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3004
+ while (1) switch (_context.prev = _context.next) {
3005
+ case 0:
3006
+ yurl = new URL(init.request.url);
3007
+ _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[0];
3008
+ if (tenantId) {
3009
+ _context.next = 4;
3010
+ break;
3011
+ }
3012
+ return _context.abrupt("return", new Response(null, {
3013
+ status: 404
3014
+ }));
3015
+ case 4:
3016
+ init.method = 'DELETE';
3017
+ url = "" + apiRoutes.TENANT(tenantId);
3018
+ log('[DELETE]', url);
3019
+ _context.next = 9;
3020
+ return request(url, init);
3021
+ case 9:
3022
+ return _context.abrupt("return", _context.sent);
3023
+ case 10:
3024
+ case "end":
3025
+ return _context.stop();
3026
+ }
3027
+ }, _callee);
3028
+ }));
3029
+ return _DELETE.apply(this, arguments);
3030
+ }
3031
+
3032
+ /**
3033
+ * @swagger
3034
+ * /api/tenants:
3035
+ * post:
3036
+ * tags:
3037
+ * - tenants
3038
+ * summary: Create a tenant
3039
+ * description: Creates a new tenant in a database.
3040
+ * operationId: createTenant
3041
+ * requestBody:
3042
+ * description: A wrapper for the tenant name.
3043
+ * content:
3044
+ * application/json:
3045
+ * schema:
3046
+ * $ref: '#/components/schemas/CreateTenantRequest'
3047
+ * examples:
3048
+ * Create Tenant Request:
3049
+ * summary: Creates a named tenant
3050
+ * description: Create Tenant Request
3051
+ * value:
3052
+ * name: My Sandbox
3053
+ * responses:
3054
+ * "201":
3055
+ * description: Tenant created
3056
+ * content:
3057
+ * application/json:
3058
+ * schema:
3059
+ * $ref: '#/components/schemas/Tenant'
3060
+ * "401":
3061
+ * description: Unauthorized
3062
+ * content:
3063
+ * application/json:
3064
+ * schema:
3065
+ * $ref: '#/components/schemas/APIError'
3066
+ * "404":
3067
+ * description: Database not found
3068
+ * content:
3069
+ * application/json:
3070
+ * schema:
3071
+ * $ref: '#/components/schemas/APIError'
3072
+ */
3073
+ function POST(_x, _x2, _x3) {
3074
+ return _POST.apply(this, arguments);
3075
+ }
3076
+ function _POST() {
3077
+ _POST = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
3078
+ var url;
3079
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3080
+ while (1) switch (_context.prev = _context.next) {
3081
+ case 0:
3082
+ init.body = init.request.body;
3083
+ init.method = 'POST';
3084
+ url = "" + apiRoutes.TENANTS;
3085
+ log('[POST]', url);
3086
+ _context.next = 6;
3087
+ return request(url, init);
3088
+ case 6:
3089
+ return _context.abrupt("return", _context.sent);
3090
+ case 7:
3091
+ case "end":
3092
+ return _context.stop();
3093
+ }
3094
+ }, _callee);
3095
+ }));
3096
+ return _POST.apply(this, arguments);
3097
+ }
3098
+
3099
+ var key$3 = 'TENANTS';
3100
+ function route$7(_x, _x2) {
3101
+ return _route$7.apply(this, arguments);
3102
+ }
3103
+ function _route$7() {
3104
+ _route$7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request, config) {
3105
+ var _Logger, info, session;
3106
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3107
+ while (1) switch (_context.prev = _context.next) {
3108
+ case 0:
3109
+ _Logger = Logger(_extends({}, config, {
3110
+ debug: config.debug
3111
+ }), '[ROUTES]', "[" + key$3 + "]"), info = _Logger.info;
3112
+ _context.next = 3;
3113
+ return auth(request, config);
3114
+ case 3:
3115
+ session = _context.sent;
3116
+ if (session) {
3117
+ _context.next = 7;
3118
+ break;
3119
+ }
3120
+ info('401');
3121
+ return _context.abrupt("return", new Response(null, {
3122
+ status: 401
3123
+ }));
3124
+ case 7:
3125
+ _context.t0 = request.method;
3126
+ _context.next = _context.t0 === 'GET' ? 10 : _context.t0 === 'POST' ? 13 : _context.t0 === 'DELETE' ? 16 : 19;
3127
+ break;
3128
+ case 10:
3129
+ _context.next = 12;
3130
+ return GET(session, {
3131
+ request: request
3132
+ }, info);
3133
+ case 12:
3134
+ return _context.abrupt("return", _context.sent);
3135
+ case 13:
3136
+ _context.next = 15;
3137
+ return POST(session, {
3138
+ request: request
3139
+ }, info);
3140
+ case 15:
3141
+ return _context.abrupt("return", _context.sent);
3142
+ case 16:
3143
+ _context.next = 18;
3144
+ return DELETE(session, {
3145
+ request: request
3146
+ }, info);
3147
+ case 18:
3148
+ return _context.abrupt("return", _context.sent);
3149
+ case 19:
3150
+ return _context.abrupt("return", new Response('method not allowed', {
3151
+ status: 405
3152
+ }));
3153
+ case 20:
3154
+ case "end":
3155
+ return _context.stop();
3156
+ }
3157
+ }, _callee);
3158
+ }));
3159
+ return _route$7.apply(this, arguments);
3160
+ }
3161
+ function matches$7(configRoutes, request) {
3162
+ return urlMatches(request.url, configRoutes[key$3]);
3163
+ }
3164
+
3165
+ var proxyRoutes = {
3166
+ SIGNIN: /*#__PURE__*/makeRestUrl('/auth/signin'),
3167
+ PROVIDERS: /*#__PURE__*/makeRestUrl('/auth/providers'),
3168
+ SESSION: /*#__PURE__*/makeRestUrl('/auth/session'),
3169
+ CSRF: /*#__PURE__*/makeRestUrl('/auth/csrf'),
3170
+ CALLBACK: /*#__PURE__*/makeRestUrl('/auth/callback'),
3171
+ SIGNOUT: /*#__PURE__*/makeRestUrl('/auth/signout'),
3172
+ ERROR: /*#__PURE__*/makeRestUrl('/auth/error')
3173
+ };
3174
+
3175
+ var key$2 = 'SIGNIN';
3176
+ function route$6(_x) {
3177
+ return _route$6.apply(this, arguments);
3178
+ }
3179
+ function _route$6() {
3180
+ _route$6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request$1) {
3181
+ var url, init, _URL$pathname$split$r, provider, passThroughUrl, params, res;
3182
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3183
+ while (1) switch (_context.prev = _context.next) {
3184
+ case 0:
3185
+ url = proxyRoutes[key$2];
3186
+ init = {
3187
+ method: request$1.method
3188
+ };
3189
+ if (request$1.method === 'POST') {
3190
+ init.body = request$1.body;
3191
+ _URL$pathname$split$r = new URL(request$1.url).pathname.split('/').reverse(), provider = _URL$pathname$split$r[0];
3192
+ url = proxyRoutes[key$2] + "/" + provider;
3193
+ }
3194
+ passThroughUrl = new URL(request$1.url);
3195
+ params = new URLSearchParams(passThroughUrl.search);
3196
+ url = "" + url + (params.toString() !== '' ? "?" + params.toString() : '');
3197
+ _context.next = 8;
3198
+ return request(url, _extends({}, init, {
3199
+ request: request$1
3200
+ }));
3201
+ case 8:
3202
+ res = _context.sent;
3203
+ return _context.abrupt("return", res);
3204
+ case 10:
3205
+ case "end":
3206
+ return _context.stop();
3207
+ }
3208
+ }, _callee);
3209
+ }));
3210
+ return _route$6.apply(this, arguments);
3211
+ }
3212
+ function matches$6(configRoutes, request) {
3213
+ return urlMatches(request.url, configRoutes[key$2]);
3214
+ }
3215
+
3216
+ function route$5(_x) {
3217
+ return _route$5.apply(this, arguments);
3218
+ }
3219
+ function _route$5() {
3220
+ _route$5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3221
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3222
+ while (1) switch (_context.prev = _context.next) {
3223
+ case 0:
3224
+ return _context.abrupt("return", request(proxyRoutes.SESSION, {
3225
+ method: req.method,
3226
+ request: req
3227
+ }));
3228
+ case 1:
3229
+ case "end":
3230
+ return _context.stop();
3231
+ }
3232
+ }, _callee);
3233
+ }));
3234
+ return _route$5.apply(this, arguments);
3235
+ }
3236
+ function matches$5(configRoutes, request) {
3237
+ return urlMatches(request.url, configRoutes.SESSION);
3238
+ }
3239
+
3240
+ function route$4(_x) {
3241
+ return _route$4.apply(this, arguments);
3242
+ }
3243
+ function _route$4() {
3244
+ _route$4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3245
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3246
+ while (1) switch (_context.prev = _context.next) {
3247
+ case 0:
3248
+ return _context.abrupt("return", request(proxyRoutes.PROVIDERS, {
3249
+ method: req.method,
3250
+ request: req
3251
+ }));
3252
+ case 1:
3253
+ case "end":
3254
+ return _context.stop();
3255
+ }
3256
+ }, _callee);
3257
+ }));
3258
+ return _route$4.apply(this, arguments);
3259
+ }
3260
+ function matches$4(configRoutes, request) {
3261
+ return urlMatches(request.url, configRoutes.PROVIDERS);
3262
+ }
3263
+
3264
+ function route$3(_x) {
3265
+ return _route$3.apply(this, arguments);
3266
+ }
3267
+ function _route$3() {
3268
+ _route$3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3269
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3270
+ while (1) switch (_context.prev = _context.next) {
3271
+ case 0:
3272
+ return _context.abrupt("return", request(proxyRoutes.CSRF, {
3273
+ method: req.method,
3274
+ request: req
3275
+ }));
3276
+ case 1:
3277
+ case "end":
3278
+ return _context.stop();
3279
+ }
3280
+ }, _callee);
3281
+ }));
3282
+ return _route$3.apply(this, arguments);
3283
+ }
3284
+ function matches$3(configRoutes, request) {
3285
+ return urlMatches(request.url, configRoutes.CSRF);
3286
+ }
3287
+
3288
+ var _console = console,
3289
+ log = _console.log,
3290
+ error = _console.error;
3291
+ function route$2(_x) {
3292
+ return _route$2.apply(this, arguments);
3293
+ }
3294
+ function _route$2() {
3295
+ _route$2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request$1) {
3296
+ var _URL$pathname$split$r, provider, passThroughUrl, params, url, res, location;
3297
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3298
+ while (1) switch (_context.prev = _context.next) {
3299
+ case 0:
3300
+ _URL$pathname$split$r = new URL(request$1.url).pathname.split('/').reverse(), provider = _URL$pathname$split$r[0];
3301
+ passThroughUrl = new URL(request$1.url);
3302
+ params = new URLSearchParams(passThroughUrl.search);
3303
+ url = proxyRoutes.CALLBACK + "/" + provider + (params.toString() !== '' ? "?" + params.toString() : '');
3304
+ _context.next = 6;
3305
+ return request(url, {
3306
+ request: request$1,
3307
+ method: request$1.method
3308
+ })["catch"](function (e) {
3309
+ error('an error has occurred in callback');
3310
+ log(e);
3311
+ });
3312
+ case 6:
3313
+ res = _context.sent;
3314
+ location = res == null ? void 0 : res.headers.get('location');
3315
+ if (!location) {
3316
+ _context.next = 10;
3317
+ break;
3318
+ }
3319
+ return _context.abrupt("return", new Response(res == null ? void 0 : res.body, {
3320
+ status: 302,
3321
+ headers: res == null ? void 0 : res.headers
3322
+ }));
3323
+ case 10:
3324
+ return _context.abrupt("return", new Response(res == null ? void 0 : res.body, {
3325
+ status: res == null ? void 0 : res.status,
3326
+ headers: res == null ? void 0 : res.headers
3327
+ }));
3328
+ case 11:
3329
+ case "end":
3330
+ return _context.stop();
3331
+ }
3332
+ }, _callee);
3333
+ }));
3334
+ return _route$2.apply(this, arguments);
3335
+ }
3336
+ function matches$2(configRoutes, request) {
3337
+ return urlMatches(request.url, configRoutes.CALLBACK);
3338
+ }
3339
+
3340
+ var key$1 = 'SIGNOUT';
3341
+ function route$1(_x) {
3342
+ return _route$1.apply(this, arguments);
3343
+ }
3344
+ function _route$1() {
3345
+ _route$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request$1) {
3346
+ var url, init, _URL$pathname$split$r, provider, res;
3347
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3348
+ while (1) switch (_context.prev = _context.next) {
3349
+ case 0:
3350
+ url = proxyRoutes[key$1];
3351
+ init = {
3352
+ method: request$1.method
3353
+ };
3354
+ if (request$1.method === 'POST') {
3355
+ init.body = request$1.body;
3356
+ _URL$pathname$split$r = new URL(request$1.url).pathname.split('/').reverse(), provider = _URL$pathname$split$r[0];
3357
+ url = proxyRoutes[key$1] + "/" + provider;
3358
+ }
3359
+ _context.next = 5;
3360
+ return request(url, _extends({}, init, {
3361
+ request: request$1
3362
+ }));
3363
+ case 5:
3364
+ res = _context.sent;
3365
+ return _context.abrupt("return", res);
3366
+ case 7:
3367
+ case "end":
3368
+ return _context.stop();
3369
+ }
3370
+ }, _callee);
3371
+ }));
3372
+ return _route$1.apply(this, arguments);
3373
+ }
3374
+ function matches$1(configRoutes, request) {
3375
+ return urlMatches(request.url, configRoutes[key$1]);
3376
+ }
3377
+
3378
+ var key = 'ERROR';
3379
+ function route(_x) {
3380
+ return _route.apply(this, arguments);
3381
+ }
3382
+ function _route() {
3383
+ _route = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3384
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3385
+ while (1) switch (_context.prev = _context.next) {
3386
+ case 0:
3387
+ return _context.abrupt("return", request(proxyRoutes[key], {
3388
+ method: req.method,
3389
+ request: req
3390
+ }));
3391
+ case 1:
3392
+ case "end":
3393
+ return _context.stop();
3394
+ }
3395
+ }, _callee);
3396
+ }));
3397
+ return _route.apply(this, arguments);
3398
+ }
3399
+ function matches(configRoutes, request) {
3400
+ return urlMatches(request.url, configRoutes[key]);
3401
+ }
3402
+
3403
+ function GETTER(configRoutes, config) {
3404
+ return /*#__PURE__*/function () {
3405
+ var _GET = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3406
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3407
+ while (1) switch (_context.prev = _context.next) {
3408
+ case 0:
3409
+ if (!matches$a(configRoutes, req)) {
3410
+ _context.next = 2;
3411
+ break;
3412
+ }
3413
+ return _context.abrupt("return", route$a(req, config));
3414
+ case 2:
3415
+ if (!matches$9(configRoutes, req)) {
3416
+ _context.next = 4;
3417
+ break;
3418
+ }
3419
+ return _context.abrupt("return", route$9(req, config));
3420
+ case 4:
3421
+ if (!matches$8(configRoutes, req)) {
3422
+ _context.next = 6;
3423
+ break;
3424
+ }
3425
+ return _context.abrupt("return", route$8(req, config));
3426
+ case 6:
3427
+ if (!matches$7(configRoutes, req)) {
3428
+ _context.next = 8;
3429
+ break;
3430
+ }
3431
+ return _context.abrupt("return", route$7(req, config));
3432
+ case 8:
3433
+ if (!matches$5(configRoutes, req)) {
3434
+ _context.next = 10;
3435
+ break;
3436
+ }
3437
+ return _context.abrupt("return", route$5(req));
3438
+ case 10:
3439
+ if (!matches$6(configRoutes, req)) {
3440
+ _context.next = 12;
3441
+ break;
3442
+ }
3443
+ return _context.abrupt("return", route$6(req));
3444
+ case 12:
3445
+ if (!matches$4(configRoutes, req)) {
3446
+ _context.next = 14;
3447
+ break;
3448
+ }
3449
+ return _context.abrupt("return", route$4(req));
3450
+ case 14:
3451
+ if (!matches$3(configRoutes, req)) {
3452
+ _context.next = 16;
3453
+ break;
3454
+ }
3455
+ return _context.abrupt("return", route$3(req));
3456
+ case 16:
3457
+ if (!matches$2(configRoutes, req)) {
3458
+ _context.next = 18;
3459
+ break;
3460
+ }
3461
+ return _context.abrupt("return", route$2(req));
3462
+ case 18:
3463
+ if (!matches$1(configRoutes, req)) {
3464
+ _context.next = 20;
3465
+ break;
3466
+ }
3467
+ return _context.abrupt("return", route$1(req));
3468
+ case 20:
3469
+ if (!matches(configRoutes, req)) {
3470
+ _context.next = 22;
3471
+ break;
3472
+ }
3473
+ return _context.abrupt("return", route(req));
3474
+ case 22:
3475
+ return _context.abrupt("return", new Response(null, {
3476
+ status: 404
3477
+ }));
3478
+ case 23:
3479
+ case "end":
3480
+ return _context.stop();
3481
+ }
3482
+ }, _callee);
3483
+ }));
3484
+ function GET(_x) {
3485
+ return _GET.apply(this, arguments);
3486
+ }
3487
+ return GET;
3488
+ }();
3489
+ }
3490
+
3491
+ function POSTER(configRoutes, config) {
3492
+ return /*#__PURE__*/function () {
3493
+ var _POST = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3494
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3495
+ while (1) switch (_context.prev = _context.next) {
3496
+ case 0:
3497
+ if (!matches$8(configRoutes, req)) {
3498
+ _context.next = 2;
3499
+ break;
3500
+ }
3501
+ return _context.abrupt("return", route$8(req, config));
3502
+ case 2:
3503
+ if (!matches$9(configRoutes, req)) {
3504
+ _context.next = 4;
3505
+ break;
3506
+ }
3507
+ return _context.abrupt("return", route$9(req, config));
3508
+ case 4:
3509
+ if (!matches$7(configRoutes, req)) {
3510
+ _context.next = 6;
3511
+ break;
3512
+ }
3513
+ return _context.abrupt("return", route$7(req, config));
3514
+ case 6:
3515
+ if (!matches$5(configRoutes, req)) {
3516
+ _context.next = 8;
3517
+ break;
3518
+ }
3519
+ return _context.abrupt("return", route$5(req));
3520
+ case 8:
3521
+ if (!matches$6(configRoutes, req)) {
3522
+ _context.next = 10;
3523
+ break;
3524
+ }
3525
+ return _context.abrupt("return", route$6(req));
3526
+ case 10:
3527
+ if (!matches$4(configRoutes, req)) {
3528
+ _context.next = 12;
3529
+ break;
3530
+ }
3531
+ return _context.abrupt("return", route$4(req));
3532
+ case 12:
3533
+ if (!matches$3(configRoutes, req)) {
3534
+ _context.next = 14;
3535
+ break;
3536
+ }
3537
+ return _context.abrupt("return", route$3(req));
3538
+ case 14:
3539
+ if (!matches$2(configRoutes, req)) {
3540
+ _context.next = 16;
3541
+ break;
3542
+ }
3543
+ return _context.abrupt("return", route$2(req));
3544
+ case 16:
3545
+ if (!matches$1(configRoutes, req)) {
3546
+ _context.next = 18;
3547
+ break;
3548
+ }
3549
+ return _context.abrupt("return", route$1(req));
3550
+ case 18:
3551
+ return _context.abrupt("return", new Response(null, {
3552
+ status: 404
3553
+ }));
3554
+ case 19:
3555
+ case "end":
3556
+ return _context.stop();
3557
+ }
3558
+ }, _callee);
3559
+ }));
3560
+ function POST(_x) {
3561
+ return _POST.apply(this, arguments);
3562
+ }
3563
+ return POST;
3564
+ }();
3565
+ }
3566
+
3567
+ function DELETER(configRoutes, config) {
3568
+ return /*#__PURE__*/function () {
3569
+ var _DELETE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3570
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3571
+ while (1) switch (_context.prev = _context.next) {
3572
+ case 0:
3573
+ if (!matches$8(configRoutes, req)) {
3574
+ _context.next = 2;
3575
+ break;
3576
+ }
3577
+ return _context.abrupt("return", route$8(req, config));
3578
+ case 2:
3579
+ if (!matches$7(configRoutes, req)) {
3580
+ _context.next = 4;
3581
+ break;
3582
+ }
3583
+ return _context.abrupt("return", route$7(req, config));
3584
+ case 4:
3585
+ return _context.abrupt("return", new Response(null, {
3586
+ status: 404
3587
+ }));
3588
+ case 5:
3589
+ case "end":
3590
+ return _context.stop();
3591
+ }
3592
+ }, _callee);
3593
+ }));
3594
+ function DELETE(_x) {
3595
+ return _DELETE.apply(this, arguments);
3596
+ }
3597
+ return DELETE;
3598
+ }();
3599
+ }
3600
+
3601
+ function PUTER(configRoutes, config) {
3602
+ return /*#__PURE__*/function () {
3603
+ var _PUT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3604
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3605
+ while (1) switch (_context.prev = _context.next) {
3606
+ case 0:
3607
+ if (!matches$8(configRoutes, req)) {
3608
+ _context.next = 2;
3609
+ break;
3610
+ }
3611
+ return _context.abrupt("return", route$8(req, config));
3612
+ case 2:
3613
+ if (!matches$9(configRoutes, req)) {
3614
+ _context.next = 4;
3615
+ break;
3616
+ }
3617
+ return _context.abrupt("return", route$9(req, config));
3618
+ case 4:
3619
+ if (!matches$7(configRoutes, req)) {
3620
+ _context.next = 6;
3621
+ break;
3622
+ }
3623
+ return _context.abrupt("return", route$7(req, config));
3624
+ case 6:
3625
+ return _context.abrupt("return", new Response(null, {
3626
+ status: 404
3627
+ }));
3628
+ case 7:
3629
+ case "end":
3630
+ return _context.stop();
3631
+ }
3632
+ }, _callee);
3633
+ }));
3634
+ function PUT(_x) {
3635
+ return _PUT.apply(this, arguments);
3636
+ }
3637
+ return PUT;
3638
+ }();
3639
+ }
3640
+
3641
+ function Handlers(configRoutes, config) {
3642
+ var GET = GETTER(configRoutes, config);
3643
+ var POST = POSTER(configRoutes, config);
3644
+ var DELETE = DELETER(configRoutes, config);
3645
+ var PUT = PUTER(configRoutes, config);
3646
+ return {
3647
+ GET: GET,
3648
+ POST: POST,
3649
+ DELETE: DELETE,
3650
+ PUT: PUT
3651
+ };
3652
+ }
3653
+
3654
+ var Api = /*#__PURE__*/function () {
3655
+ function Api(config) {
3656
+ this.config = void 0;
3657
+ this.users = void 0;
3658
+ this.tenants = void 0;
3659
+ this.routes = void 0;
3660
+ this.handlers = void 0;
3661
+ this.config = config;
3662
+ this.users = new Users(config);
3663
+ this.tenants = new Tenants(config);
3664
+ this.routes = _extends({}, appRoutes(config == null ? void 0 : config.routePrefix), config == null ? void 0 : config.routes);
3665
+ this.handlers = Handlers(this.routes, config);
3666
+ }
3667
+ var _proto = Api.prototype;
3668
+ _proto.login = /*#__PURE__*/function () {
3669
+ var _login = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(payload) {
3670
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3671
+ while (1) switch (_context.prev = _context.next) {
3672
+ case 0:
3673
+ _context.next = 2;
3674
+ return serverAuth(this.config, this.handlers)(payload);
3675
+ case 2:
3676
+ this.headers = _context.sent;
3677
+ case 3:
3678
+ case "end":
3679
+ return _context.stop();
3680
+ }
3681
+ }, _callee, this);
3682
+ }));
3683
+ function login(_x) {
3684
+ return _login.apply(this, arguments);
3685
+ }
3686
+ return login;
3687
+ }();
3688
+ return _createClass(Api, [{
3689
+ key: "headers",
3690
+ set: function set(headers) {
3691
+ this.users = new Users(this.config, headers);
3692
+ this.tenants = new Tenants(this.config, headers);
3693
+ }
3694
+ }]);
3695
+ }();
3696
+ var Server = /*#__PURE__*/function () {
3697
+ function Server(config) {
3698
+ var _this = this;
3699
+ this.config = void 0;
3700
+ this.api = void 0;
3701
+ this.manager = void 0;
3702
+ this.servers = void 0;
3703
+ this.config = new Config(config, '[initial config]');
3704
+ this.servers = new Map();
3705
+ this.api = new Api(this.config);
3706
+ this.manager = new DBManager(this.config);
3707
+ watchTenantId(function (tenantId) {
3708
+ _this.tenantId = tenantId;
3709
+ });
3710
+ watchUserId(function (userId) {
3711
+ _this.userId = userId;
3712
+ });
3713
+ watchToken(function (token) {
3714
+ _this.token = token;
3715
+ });
3716
+ }
3717
+ var _proto2 = Server.prototype;
3718
+ _proto2.setConfig = function setConfig(cfg) {
3719
+ this.config = new Config(cfg);
3720
+ };
3721
+ _proto2.init = /*#__PURE__*/function () {
3722
+ var _init = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(cfg) {
3723
+ var updatedConfig;
3724
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3725
+ while (1) switch (_context2.prev = _context2.next) {
3726
+ case 0:
3727
+ _context2.next = 2;
3728
+ return this.config.configure(_extends({}, this.config, cfg));
3729
+ case 2:
3730
+ updatedConfig = _context2.sent;
3731
+ this.setConfig(updatedConfig);
3732
+ this.manager.clear(this.config);
3733
+ this.manager = new DBManager(this.config);
3734
+ this.api = new Api(this.config);
3735
+ return _context2.abrupt("return", this);
3736
+ case 8:
3737
+ case "end":
3738
+ return _context2.stop();
3739
+ }
3740
+ }, _callee2, this);
3741
+ }));
3742
+ function init(_x2) {
3743
+ return _init.apply(this, arguments);
3744
+ }
3745
+ return init;
3746
+ }();
3747
+ /**
3748
+ * A utility function if you want to manage different NileDB instances yourself
3749
+ * returns the global Server object, an existing server that's already been configured,
3750
+ * or a new one if the config isn't in the cache
3751
+ */
3752
+ _proto2.getInstance = function getInstance(config) {
3753
+ var _config = _extends({}, this.config, config);
3754
+ var serverId = getServerId(_config);
3755
+ var currentServerId = makeServerId(this.config);
3756
+ if (serverId === currentServerId) {
3757
+ return this;
3758
+ }
3759
+ var existing = this.servers.get(serverId);
3760
+ if (existing) {
3761
+ // be sure the config is up to date
3762
+ var updatedConfig = new Config(_config);
3763
+ existing.setConfig(updatedConfig);
3764
+ // propagate special config items
3765
+ existing.tenantId = updatedConfig.tenantId;
3766
+ existing.userId = updatedConfig.userId;
3767
+ existing.token = updatedConfig.api.token;
3768
+ existing.databaseId = updatedConfig.databaseId;
3769
+ return existing;
3770
+ }
3771
+ this.servers.set(serverId, new Server(_config));
3772
+ return this.servers.get(serverId);
3773
+ };
3774
+ return _createClass(Server, [{
3775
+ key: "databaseId",
3776
+ set: function set(val) {
3777
+ if (val) {
3778
+ this.config.databaseId = val;
3779
+ this.api.users.databaseId = val;
3780
+ this.api.tenants.databaseId = val;
3781
+ }
3782
+ }
3783
+ }, {
3784
+ key: "userId",
3785
+ get: function get() {
3786
+ return this.config.userId;
3787
+ },
3788
+ set: function set(userId) {
3789
+ this.databaseId = this.config.databaseId;
3790
+ this.config.userId = userId;
3791
+ if (this.api) {
3792
+ this.api.users.userId = this.config.userId;
3793
+ this.api.tenants.userId = this.config.userId;
3794
+ }
3795
+ }
3796
+ }, {
3797
+ key: "tenantId",
3798
+ get: function get() {
3799
+ return this.config.tenantId;
3800
+ },
3801
+ set: function set(tenantId) {
3802
+ this.databaseId = this.config.databaseId;
3803
+ this.config.tenantId = tenantId;
3804
+ if (this.api) {
3805
+ this.api.users.tenantId = tenantId;
3806
+ this.api.tenants.tenantId = tenantId;
3807
+ }
3808
+ }
3809
+ }, {
3810
+ key: "token",
3811
+ get: function get() {
3812
+ var _this$config;
3813
+ return (_this$config = this.config) == null || (_this$config = _this$config.api) == null ? void 0 : _this$config.token;
3814
+ },
3815
+ set: function set(token) {
3816
+ if (token) {
3817
+ this.config.api.token = token;
3818
+ if (this.api) {
3819
+ this.api.users.api.token = token;
3820
+ this.api.tenants.api.token = token;
3821
+ }
3822
+ }
3823
+ }
3824
+ }, {
3825
+ key: "db",
3826
+ get: function get() {
3827
+ // only need to interact with the knex object
3828
+ return this.manager.getConnection(this.config);
3829
+ }
3830
+ }]);
3831
+ }();
3832
+ function create(_x3) {
3833
+ return _create.apply(this, arguments);
3834
+ }
3835
+ function _create() {
3836
+ _create = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(config) {
3837
+ var server;
3838
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3839
+ while (1) switch (_context3.prev = _context3.next) {
3840
+ case 0:
3841
+ server = new Server(config);
3842
+ _context3.next = 3;
3843
+ return server.init();
3844
+ case 3:
3845
+ return _context3.abrupt("return", _context3.sent);
3846
+ case 4:
3847
+ case "end":
3848
+ return _context3.stop();
3849
+ }
3850
+ }, _callee3);
3851
+ }));
2255
3852
  return _create.apply(this, arguments);
2256
3853
  }
2257
3854