@niledatabase/server 3.0.0-alpha.8 → 3.0.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 (75) hide show
  1. package/dist/express.d.mts +24 -0
  2. package/dist/express.d.ts +24 -0
  3. package/dist/express.js +147 -0
  4. package/dist/express.js.map +1 -0
  5. package/dist/express.mjs +144 -0
  6. package/dist/express.mjs.map +1 -0
  7. package/dist/index.d.mts +323 -0
  8. package/dist/index.d.ts +323 -5
  9. package/dist/index.js +2382 -5
  10. package/dist/index.js.map +1 -0
  11. package/dist/index.mjs +2377 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/package.json +17 -4
  14. package/dist/Api.d.ts +0 -22
  15. package/dist/Server.d.ts +0 -29
  16. package/dist/api/handlers/DELETE.d.ts +0 -3
  17. package/dist/api/handlers/GET.d.ts +0 -3
  18. package/dist/api/handlers/POST.d.ts +0 -3
  19. package/dist/api/handlers/PUT.d.ts +0 -3
  20. package/dist/api/handlers/index.d.ts +0 -8
  21. package/dist/api/routes/auth/callback.d.ts +0 -3
  22. package/dist/api/routes/auth/csrf.d.ts +0 -3
  23. package/dist/api/routes/auth/error.d.ts +0 -3
  24. package/dist/api/routes/auth/index.d.ts +0 -7
  25. package/dist/api/routes/auth/providers.d.ts +0 -3
  26. package/dist/api/routes/auth/session.d.ts +0 -4
  27. package/dist/api/routes/auth/signin.d.ts +0 -33
  28. package/dist/api/routes/auth/signout.d.ts +0 -3
  29. package/dist/api/routes/me/index.d.ts +0 -4
  30. package/dist/api/routes/tenants/GET.d.ts +0 -32
  31. package/dist/api/routes/tenants/POST.d.ts +0 -45
  32. package/dist/api/routes/tenants/[tenantId]/DELETE.d.ts +0 -34
  33. package/dist/api/routes/tenants/[tenantId]/users/GET.d.ts +0 -35
  34. package/dist/api/routes/tenants/[tenantId]/users/POST.d.ts +0 -44
  35. package/dist/api/routes/tenants/[tenantId]/users/PUT.d.ts +0 -29
  36. package/dist/api/routes/tenants/[tenantId]/users/[userId]/DELETE.d.ts +0 -30
  37. package/dist/api/routes/tenants/[tenantId]/users/index.d.ts +0 -4
  38. package/dist/api/routes/tenants/index.d.ts +0 -4
  39. package/dist/api/routes/users/GET.d.ts +0 -34
  40. package/dist/api/routes/users/POST.d.ts +0 -66
  41. package/dist/api/routes/users/[userId]/PUT.d.ts +0 -40
  42. package/dist/api/routes/users/index.d.ts +0 -4
  43. package/dist/api/swagger.d.ts +0 -152
  44. package/dist/api/types.d.ts +0 -18
  45. package/dist/api/utils/auth.d.ts +0 -14
  46. package/dist/api/utils/request.d.ts +0 -4
  47. package/dist/api/utils/routes/apiRoutes.d.ts +0 -14
  48. package/dist/api/utils/routes/defaultRoutes.d.ts +0 -2
  49. package/dist/api/utils/routes/makeRestUrl.d.ts +0 -1
  50. package/dist/api/utils/routes/proxyRoutes.d.ts +0 -12
  51. package/dist/api/utils/routes/urlMatches.d.ts +0 -1
  52. package/dist/auth/index.d.ts +0 -13
  53. package/dist/db/DBManager.d.ts +0 -12
  54. package/dist/db/NileInstance.d.ts +0 -14
  55. package/dist/db/PoolProxy.d.ts +0 -3
  56. package/dist/db/index.d.ts +0 -1
  57. package/dist/db/isUUID.d.ts +0 -1
  58. package/dist/server.cjs.development.js +0 -3968
  59. package/dist/server.cjs.development.js.map +0 -1
  60. package/dist/server.cjs.production.min.js +0 -2
  61. package/dist/server.cjs.production.min.js.map +0 -1
  62. package/dist/server.esm.js +0 -3966
  63. package/dist/server.esm.js.map +0 -1
  64. package/dist/tenants/index.d.ts +0 -21
  65. package/dist/types.d.ts +0 -36
  66. package/dist/users/index.d.ts +0 -52
  67. package/dist/utils/Config/envVars.d.ts +0 -22
  68. package/dist/utils/Config/index.d.ts +0 -47
  69. package/dist/utils/Event/index.d.ts +0 -12
  70. package/dist/utils/Logger.d.ts +0 -7
  71. package/dist/utils/Requester/index.d.ts +0 -23
  72. package/dist/utils/Requester/types.d.ts +0 -88
  73. package/dist/utils/ResponseError.d.ts +0 -4
  74. package/dist/utils/Server/index.d.ts +0 -4
  75. package/dist/utils/fetch.d.ts +0 -9
@@ -1,3966 +0,0 @@
1
- import 'dotenv/config';
2
- import { Pool } from 'pg';
3
- import { decodeJwt } from 'jose';
4
-
5
- function _regeneratorRuntime() {
6
- _regeneratorRuntime = function () {
7
- return e;
8
- };
9
- var t,
10
- e = {},
11
- r = Object.prototype,
12
- n = r.hasOwnProperty,
13
- o = Object.defineProperty || function (t, e, r) {
14
- t[e] = r.value;
15
- },
16
- i = "function" == typeof Symbol ? Symbol : {},
17
- a = i.iterator || "@@iterator",
18
- c = i.asyncIterator || "@@asyncIterator",
19
- u = i.toStringTag || "@@toStringTag";
20
- function define(t, e, r) {
21
- return Object.defineProperty(t, e, {
22
- value: r,
23
- enumerable: !0,
24
- configurable: !0,
25
- writable: !0
26
- }), t[e];
27
- }
28
- try {
29
- define({}, "");
30
- } catch (t) {
31
- define = function (t, e, r) {
32
- return t[e] = r;
33
- };
34
- }
35
- function wrap(t, e, r, n) {
36
- var i = e && e.prototype instanceof Generator ? e : Generator,
37
- a = Object.create(i.prototype),
38
- c = new Context(n || []);
39
- return o(a, "_invoke", {
40
- value: makeInvokeMethod(t, r, c)
41
- }), a;
42
- }
43
- function tryCatch(t, e, r) {
44
- try {
45
- return {
46
- type: "normal",
47
- arg: t.call(e, r)
48
- };
49
- } catch (t) {
50
- return {
51
- type: "throw",
52
- arg: t
53
- };
54
- }
55
- }
56
- e.wrap = wrap;
57
- var h = "suspendedStart",
58
- l = "suspendedYield",
59
- f = "executing",
60
- s = "completed",
61
- y = {};
62
- function Generator() {}
63
- function GeneratorFunction() {}
64
- function GeneratorFunctionPrototype() {}
65
- var p = {};
66
- define(p, a, function () {
67
- return this;
68
- });
69
- var d = Object.getPrototypeOf,
70
- v = d && d(d(values([])));
71
- v && v !== r && n.call(v, a) && (p = v);
72
- var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
73
- function defineIteratorMethods(t) {
74
- ["next", "throw", "return"].forEach(function (e) {
75
- define(t, e, function (t) {
76
- return this._invoke(e, t);
77
- });
78
- });
79
- }
80
- function AsyncIterator(t, e) {
81
- function invoke(r, o, i, a) {
82
- var c = tryCatch(t[r], t, o);
83
- if ("throw" !== c.type) {
84
- var u = c.arg,
85
- h = u.value;
86
- return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
87
- invoke("next", t, i, a);
88
- }, function (t) {
89
- invoke("throw", t, i, a);
90
- }) : e.resolve(h).then(function (t) {
91
- u.value = t, i(u);
92
- }, function (t) {
93
- return invoke("throw", t, i, a);
94
- });
95
- }
96
- a(c.arg);
97
- }
98
- var r;
99
- o(this, "_invoke", {
100
- value: function (t, n) {
101
- function callInvokeWithMethodAndArg() {
102
- return new e(function (e, r) {
103
- invoke(t, n, e, r);
104
- });
105
- }
106
- return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
107
- }
108
- });
109
- }
110
- function makeInvokeMethod(e, r, n) {
111
- var o = h;
112
- return function (i, a) {
113
- if (o === f) throw Error("Generator is already running");
114
- if (o === s) {
115
- if ("throw" === i) throw a;
116
- return {
117
- value: t,
118
- done: !0
119
- };
120
- }
121
- for (n.method = i, n.arg = a;;) {
122
- var c = n.delegate;
123
- if (c) {
124
- var u = maybeInvokeDelegate(c, n);
125
- if (u) {
126
- if (u === y) continue;
127
- return u;
128
- }
129
- }
130
- if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
131
- if (o === h) throw o = s, n.arg;
132
- n.dispatchException(n.arg);
133
- } else "return" === n.method && n.abrupt("return", n.arg);
134
- o = f;
135
- var p = tryCatch(e, r, n);
136
- if ("normal" === p.type) {
137
- if (o = n.done ? s : l, p.arg === y) continue;
138
- return {
139
- value: p.arg,
140
- done: n.done
141
- };
142
- }
143
- "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
144
- }
145
- };
146
- }
147
- function maybeInvokeDelegate(e, r) {
148
- var n = r.method,
149
- o = e.iterator[n];
150
- if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
151
- var i = tryCatch(o, e.iterator, r.arg);
152
- if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
153
- var a = i.arg;
154
- return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
155
- }
156
- function pushTryEntry(t) {
157
- var e = {
158
- tryLoc: t[0]
159
- };
160
- 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
161
- }
162
- function resetTryEntry(t) {
163
- var e = t.completion || {};
164
- e.type = "normal", delete e.arg, t.completion = e;
165
- }
166
- function Context(t) {
167
- this.tryEntries = [{
168
- tryLoc: "root"
169
- }], t.forEach(pushTryEntry, this), this.reset(!0);
170
- }
171
- function values(e) {
172
- if (e || "" === e) {
173
- var r = e[a];
174
- if (r) return r.call(e);
175
- if ("function" == typeof e.next) return e;
176
- if (!isNaN(e.length)) {
177
- var o = -1,
178
- i = function next() {
179
- for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
180
- return next.value = t, next.done = !0, next;
181
- };
182
- return i.next = i;
183
- }
184
- }
185
- throw new TypeError(typeof e + " is not iterable");
186
- }
187
- return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
188
- value: GeneratorFunctionPrototype,
189
- configurable: !0
190
- }), o(GeneratorFunctionPrototype, "constructor", {
191
- value: GeneratorFunction,
192
- configurable: !0
193
- }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
194
- var e = "function" == typeof t && t.constructor;
195
- return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
196
- }, e.mark = function (t) {
197
- return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
198
- }, e.awrap = function (t) {
199
- return {
200
- __await: t
201
- };
202
- }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
203
- return this;
204
- }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
205
- void 0 === i && (i = Promise);
206
- var a = new AsyncIterator(wrap(t, r, n, o), i);
207
- return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
208
- return t.done ? t.value : a.next();
209
- });
210
- }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
211
- return this;
212
- }), define(g, "toString", function () {
213
- return "[object Generator]";
214
- }), e.keys = function (t) {
215
- var e = Object(t),
216
- r = [];
217
- for (var n in e) r.push(n);
218
- return r.reverse(), function next() {
219
- for (; r.length;) {
220
- var t = r.pop();
221
- if (t in e) return next.value = t, next.done = !1, next;
222
- }
223
- return next.done = !0, next;
224
- };
225
- }, e.values = values, Context.prototype = {
226
- constructor: Context,
227
- reset: function (e) {
228
- if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
229
- },
230
- stop: function () {
231
- this.done = !0;
232
- var t = this.tryEntries[0].completion;
233
- if ("throw" === t.type) throw t.arg;
234
- return this.rval;
235
- },
236
- dispatchException: function (e) {
237
- if (this.done) throw e;
238
- var r = this;
239
- function handle(n, o) {
240
- return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
241
- }
242
- for (var o = this.tryEntries.length - 1; o >= 0; --o) {
243
- var i = this.tryEntries[o],
244
- a = i.completion;
245
- if ("root" === i.tryLoc) return handle("end");
246
- if (i.tryLoc <= this.prev) {
247
- var c = n.call(i, "catchLoc"),
248
- u = n.call(i, "finallyLoc");
249
- if (c && u) {
250
- if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
251
- if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
252
- } else if (c) {
253
- if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
254
- } else {
255
- if (!u) throw Error("try statement without catch or finally");
256
- if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
257
- }
258
- }
259
- }
260
- },
261
- abrupt: function (t, e) {
262
- for (var r = this.tryEntries.length - 1; r >= 0; --r) {
263
- var o = this.tryEntries[r];
264
- if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
265
- var i = o;
266
- break;
267
- }
268
- }
269
- i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
270
- var a = i ? i.completion : {};
271
- return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
272
- },
273
- complete: function (t, e) {
274
- if ("throw" === t.type) throw t.arg;
275
- return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
276
- },
277
- finish: function (t) {
278
- for (var e = this.tryEntries.length - 1; e >= 0; --e) {
279
- var r = this.tryEntries[e];
280
- if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
281
- }
282
- },
283
- catch: function (t) {
284
- for (var e = this.tryEntries.length - 1; e >= 0; --e) {
285
- var r = this.tryEntries[e];
286
- if (r.tryLoc === t) {
287
- var n = r.completion;
288
- if ("throw" === n.type) {
289
- var o = n.arg;
290
- resetTryEntry(r);
291
- }
292
- return o;
293
- }
294
- }
295
- throw Error("illegal catch attempt");
296
- },
297
- delegateYield: function (e, r, n) {
298
- return this.delegate = {
299
- iterator: values(e),
300
- resultName: r,
301
- nextLoc: n
302
- }, "next" === this.method && (this.arg = t), y;
303
- }
304
- }, e;
305
- }
306
- function _toPrimitive(t, r) {
307
- if ("object" != typeof t || !t) return t;
308
- var e = t[Symbol.toPrimitive];
309
- if (void 0 !== e) {
310
- var i = e.call(t, r || "default");
311
- if ("object" != typeof i) return i;
312
- throw new TypeError("@@toPrimitive must return a primitive value.");
313
- }
314
- return ("string" === r ? String : Number)(t);
315
- }
316
- function _toPropertyKey(t) {
317
- var i = _toPrimitive(t, "string");
318
- return "symbol" == typeof i ? i : i + "";
319
- }
320
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
321
- try {
322
- var info = gen[key](arg);
323
- var value = info.value;
324
- } catch (error) {
325
- reject(error);
326
- return;
327
- }
328
- if (info.done) {
329
- resolve(value);
330
- } else {
331
- Promise.resolve(value).then(_next, _throw);
332
- }
333
- }
334
- function _asyncToGenerator(fn) {
335
- return function () {
336
- var self = this,
337
- args = arguments;
338
- return new Promise(function (resolve, reject) {
339
- var gen = fn.apply(self, args);
340
- function _next(value) {
341
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
342
- }
343
- function _throw(err) {
344
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
345
- }
346
- _next(undefined);
347
- });
348
- };
349
- }
350
- function _defineProperties(target, props) {
351
- for (var i = 0; i < props.length; i++) {
352
- var descriptor = props[i];
353
- descriptor.enumerable = descriptor.enumerable || false;
354
- descriptor.configurable = true;
355
- if ("value" in descriptor) descriptor.writable = true;
356
- Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
357
- }
358
- }
359
- function _createClass(Constructor, protoProps, staticProps) {
360
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
361
- if (staticProps) _defineProperties(Constructor, staticProps);
362
- Object.defineProperty(Constructor, "prototype", {
363
- writable: false
364
- });
365
- return Constructor;
366
- }
367
- function _extends() {
368
- _extends = Object.assign ? Object.assign.bind() : function (target) {
369
- for (var i = 1; i < arguments.length; i++) {
370
- var source = arguments[i];
371
- for (var key in source) {
372
- if (Object.prototype.hasOwnProperty.call(source, key)) {
373
- target[key] = source[key];
374
- }
375
- }
376
- }
377
- return target;
378
- };
379
- return _extends.apply(this, arguments);
380
- }
381
- function _inheritsLoose(subClass, superClass) {
382
- subClass.prototype = Object.create(superClass.prototype);
383
- subClass.prototype.constructor = subClass;
384
- _setPrototypeOf(subClass, superClass);
385
- }
386
- function _setPrototypeOf(o, p) {
387
- _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
388
- o.__proto__ = p;
389
- return o;
390
- };
391
- return _setPrototypeOf(o, p);
392
- }
393
- function _objectWithoutPropertiesLoose(source, excluded) {
394
- if (source == null) return {};
395
- var target = {};
396
- var sourceKeys = Object.keys(source);
397
- var key, i;
398
- for (i = 0; i < sourceKeys.length; i++) {
399
- key = sourceKeys[i];
400
- if (excluded.indexOf(key) >= 0) continue;
401
- target[key] = source[key];
402
- }
403
- return target;
404
- }
405
- function _unsupportedIterableToArray(o, minLen) {
406
- if (!o) return;
407
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
408
- var n = Object.prototype.toString.call(o).slice(8, -1);
409
- if (n === "Object" && o.constructor) n = o.constructor.name;
410
- if (n === "Map" || n === "Set") return Array.from(o);
411
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
412
- }
413
- function _arrayLikeToArray(arr, len) {
414
- if (len == null || len > arr.length) len = arr.length;
415
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
416
- return arr2;
417
- }
418
- function _createForOfIteratorHelperLoose(o, allowArrayLike) {
419
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
420
- if (it) return (it = it.call(o)).next.bind(it);
421
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
422
- if (it) o = it;
423
- var i = 0;
424
- return function () {
425
- if (i >= o.length) return {
426
- done: true
427
- };
428
- return {
429
- done: false,
430
- value: o[i++]
431
- };
432
- };
433
- }
434
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
435
- }
436
-
437
- function Logger(config) {
438
- for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
439
- params[_key - 1] = arguments[_key];
440
- }
441
- return {
442
- info: function info() {
443
- if (config != null && config.debug) {
444
- var _console;
445
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
446
- args[_key2] = arguments[_key2];
447
- }
448
- // eslint-disable-next-line no-console
449
- (_console = console).info.apply(_console, ['[niledb]'].concat(params, args));
450
- }
451
- },
452
- warn: function warn() {
453
- if (config != null && config.debug) {
454
- var _console2;
455
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
456
- args[_key3] = arguments[_key3];
457
- }
458
- // eslint-disable-next-line no-console
459
- (_console2 = console).warn.apply(_console2, ['[niledb]'].concat(params, args));
460
- }
461
- },
462
- error: function error() {
463
- var _console3;
464
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
465
- args[_key4] = arguments[_key4];
466
- }
467
- // eslint-disable-next-line no-console
468
- (_console3 = console).error.apply(_console3, ['[niledb]', '[ERROR]'].concat(params, args));
469
- }
470
- };
471
- }
472
-
473
- var getDatabaseId = function getDatabaseId(cfg) {
474
- var config = cfg.config,
475
- logger = cfg.logger;
476
- var _Logger = Logger(config, '[databaseId]'),
477
- info = _Logger.info;
478
- if (config != null && config.databaseId) {
479
- logger && info(logger, 'config', config.databaseId);
480
- return String(config == null ? void 0 : config.databaseId);
481
- }
482
- if (process.env.NILEDB_POSTGRES_URL) {
483
- var pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
484
- return pgUrl.pathname.substring(1);
485
- }
486
- logger && info(logger, 'env', process.env.NILEDB_ID);
487
- return process.env.NILEDB_ID;
488
- };
489
- var getUsername = function getUsername(cfg) {
490
- var config = cfg.config,
491
- logger = cfg.logger;
492
- var _Logger2 = Logger(config, '[username]'),
493
- info = _Logger2.info;
494
- if (config != null && config.user) {
495
- logger && info(logger, 'config', config.user);
496
- return String(config == null ? void 0 : config.user);
497
- }
498
- logger && info(logger, 'NILEDB_USER', process.env.NILEDB_USER);
499
- return process.env.NILEDB_USER;
500
- };
501
- var getPassword = function getPassword(cfg) {
502
- var config = cfg.config,
503
- logger = cfg.logger;
504
- var log = logProtector(logger);
505
- var _Logger3 = Logger(config, '[password]'),
506
- info = _Logger3.info;
507
- if (config != null && config.password) {
508
- log && info(logger, 'config', config.password);
509
- return String(config.password);
510
- }
511
- log && info(logger, 'NILEDB_PASSWORD', process.env.NILEDB_PASSWORD);
512
- return process.env.NILEDB_PASSWORD;
513
- };
514
- var getInfoBearer = function getInfoBearer(cfg) {
515
- return getUsername(cfg) + ":" + getPassword(cfg);
516
- };
517
- var getToken = function getToken(cfg) {
518
- var _config$api;
519
- var config = cfg.config,
520
- logger = cfg.logger;
521
- var _Logger4 = Logger(config, '[token]'),
522
- info = _Logger4.info;
523
- if (config != null && (_config$api = config.api) != null && _config$api.token) {
524
- var _config$api2, _config$api3;
525
- logger && info(logger, 'config', (_config$api2 = config.api) == null ? void 0 : _config$api2.token);
526
- return String((_config$api3 = config.api) == null ? void 0 : _config$api3.token);
527
- }
528
- if (process.env.NILEDB_TOKEN) {
529
- logger && info(logger, 'NILEDB_TOKEN', process.env.NILEDB_TOKEN);
530
- return process.env.NILEDB_TOKEN;
531
- }
532
- return undefined;
533
- };
534
- var getDatabaseName = function getDatabaseName(cfg) {
535
- var config = cfg.config,
536
- logger = cfg.logger;
537
- var _Logger5 = Logger(config, '[databaseName]'),
538
- info = _Logger5.info;
539
- if (config != null && config.databaseName) {
540
- logger && info(logger, 'config', config.databaseName);
541
- return String(config.databaseName);
542
- }
543
- if (process.env.NILEDB_NAME) {
544
- logger && info(logger, 'NILEDB_NAME', process.env.NILEDB_NAME);
545
- return process.env.NILEDB_NAME;
546
- }
547
- return null;
548
- };
549
- var getTenantId = function getTenantId(cfg) {
550
- var config = cfg.config,
551
- logger = cfg.logger;
552
- var _Logger6 = Logger(config, '[tenantId]'),
553
- info = _Logger6.info;
554
- if (config != null && config.tenantId) {
555
- logger && info(logger, 'config', config.tenantId);
556
- return config.tenantId;
557
- }
558
- if (process.env.NILEDB_TENANT) {
559
- logger && info(logger, 'NILEDB_TENANT', process.env.NILEDB_TENANT);
560
- return process.env.NILEDB_TENANT;
561
- }
562
- return null;
563
- };
564
- var getLocal = function getLocal(cfg) {
565
- var config = cfg.config,
566
- logger = cfg.logger;
567
- if (process.env.NILEDB_LOCAL) {
568
- var _Logger7 = Logger(config, '[local]'),
569
- info = _Logger7.info;
570
- logger && info(logger, 'NILEDB_LOCAL', process.env.NILEDB_LOCAL);
571
- var apiUrl = new URL(process.env.NILEDB_LOCAL);
572
- return apiUrl.href;
573
- }
574
- return 'http://localhost:3000';
575
- };
576
- /**
577
- * @param cfg various overrides
578
- * @returns the url for REST to use
579
- */
580
- var getBasePath = function getBasePath(cfg) {
581
- var _config$api4;
582
- var config = cfg.config,
583
- logger = cfg.logger;
584
- var _Logger8 = Logger(config, '[basePath]'),
585
- info = _Logger8.info;
586
- var basePath = config == null || (_config$api4 = config.api) == null ? void 0 : _config$api4.basePath;
587
- var version = '';
588
- if (!/\/v\d\//.test(String(basePath))) {
589
- var _config$api5, _config$api$version, _config$api6;
590
- 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);
591
- }
592
- if (basePath) {
593
- logger && info(logger, 'config', basePath);
594
- return "" + basePath + version;
595
- }
596
- if (process.env.NILEDB_API_URL) {
597
- logger && info(logger, 'NILEDB_API_URL', process.env.NILEDB_API_URL);
598
- var apiUrl = new URL(process.env.NILEDB_API_URL);
599
- return apiUrl.href;
600
- }
601
- throw new Error('NILEDB_API_URL is missing.');
602
- };
603
- var getControlPlane = function getControlPlane(cfg) {
604
- var config = cfg.config,
605
- logger = cfg.logger;
606
- var _Logger9 = Logger(config, '[basePath]'),
607
- info = _Logger9.info;
608
- if (process.env.NILEDB_CONFIGURE) {
609
- logger && info(logger, 'NILEDB_CONFIGURE', process.env.NILEDB_CONFIGURE);
610
- return process.env.NILEDB_CONFIGURE;
611
- }
612
- logger && info(logger, 'default', process.env.NILEDB_CONFIGURE);
613
- return 'https://global.thenile.dev';
614
- };
615
- function getDbHost(cfg) {
616
- var config = cfg.config,
617
- logger = cfg.logger;
618
- var _Logger10 = Logger(config, '[db.host]'),
619
- info = _Logger10.info;
620
- if (config != null && config.db && config.db.host) {
621
- logger && info(logger, 'config', config == null ? void 0 : config.db.host);
622
- return config.db.host;
623
- }
624
- if (process.env.NILEDB_POSTGRES_URL) {
625
- var pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
626
- logger && info(logger, 'NILEDB_POSTGRES_URL', pgUrl.host);
627
- return pgUrl.host;
628
- }
629
- if (process.env.NILEDB_HOST) {
630
- logger && info(logger, 'NILEDB_HOST', process.env.NILEDB_HOST);
631
- return process.env.NILEDB_HOST;
632
- }
633
- logger && info(logger, 'default', 'db.thenile.dev');
634
- return 'db.thenile.dev';
635
- }
636
- function getDbPort(cfg) {
637
- var _config$db;
638
- var config = cfg.config,
639
- logger = cfg.logger;
640
- var _Logger11 = Logger(config, '[db.port]'),
641
- info = _Logger11.info;
642
- if (config != null && (_config$db = config.db) != null && _config$db.port && config.db.port != null) {
643
- var _config$db2;
644
- logger && info(logger, 'config', config == null ? void 0 : config.db.port);
645
- return Number((_config$db2 = config.db) == null ? void 0 : _config$db2.port);
646
- }
647
- if (process.env.NILEDB_PORT) {
648
- logger && info(logger, 'config', process.env.NILEDB_PORT);
649
- return Number(process.env.NILEDB_PORT);
650
- }
651
- logger && info(logger, 'default', 5432);
652
- return 5432;
653
- }
654
- // don't let people accidentally log secrets to production
655
- var logProtector = function logProtector(logger) {
656
- return process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test' ? logger : null;
657
- };
658
-
659
- var _excluded$2 = ["host", "port"],
660
- _excluded2 = ["host", "port"];
661
- var ApiConfig = /*#__PURE__*/function () {
662
- function ApiConfig(_ref) {
663
- var basePath = _ref.basePath,
664
- cookieKey = _ref.cookieKey,
665
- token = _ref.token,
666
- version = _ref.version,
667
- localPath = _ref.localPath;
668
- this.cookieKey = void 0;
669
- this.basePath = void 0;
670
- this.version = void 0;
671
- this.localPath = void 0;
672
- this._token = void 0;
673
- this.basePath = basePath;
674
- this.cookieKey = cookieKey;
675
- this.version = version;
676
- this._token = token;
677
- this.localPath = localPath != null ? localPath : 'http://localhost:3000';
678
- }
679
- return _createClass(ApiConfig, [{
680
- key: "token",
681
- get: function get() {
682
- return this._token;
683
- },
684
- set: function set(value) {
685
- this._token = value;
686
- }
687
- }]);
688
- }();
689
- var Config = /*#__PURE__*/function () {
690
- function Config(_config, logger) {
691
- var _this = this,
692
- _config$db2,
693
- _config$api$cookieKey2,
694
- _config$api3,
695
- _config$api$version2,
696
- _config$api4;
697
- this.user = void 0;
698
- this.password = void 0;
699
- this.databaseId = void 0;
700
- this.databaseName = void 0;
701
- this.routePrefix = void 0;
702
- this.routes = void 0;
703
- this.debug = void 0;
704
- this.db = void 0;
705
- this.api = void 0;
706
- this._tenantId = void 0;
707
- this._userId = void 0;
708
- this.configure = /*#__PURE__*/function () {
709
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config) {
710
- var _config$db, _envVarConfig$config, _config$api$cookieKey, _config$api, _config$api$version, _config$api2;
711
- 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;
712
- return _regeneratorRuntime().wrap(function _callee$(_context) {
713
- while (1) switch (_context.prev = _context.next) {
714
- case 0:
715
- _Logger = Logger(config, '[init]'), info = _Logger.info, error = _Logger.error;
716
- envVarConfig = {
717
- config: config
718
- };
719
- _ref3 = (_config$db = config.db) != null ? _config$db : {}, host = _ref3.host, port = _ref3.port, dbConfig = _objectWithoutPropertiesLoose(_ref3, _excluded$2);
720
- configuredHost = host != null ? host : getDbHost(envVarConfig);
721
- configuredPort = port != null ? port : getDbPort(envVarConfig);
722
- if (!(configuredHost && _this.databaseName && _this.databaseId)) {
723
- _context.next = 8;
724
- break;
725
- }
726
- info('Already configured, aborting fetch');
727
- return _context.abrupt("return", _this);
728
- case 8:
729
- basePath = getBasePath(envVarConfig);
730
- cp = getControlPlane(envVarConfig);
731
- databaseName = getDatabaseName({
732
- config: config,
733
- logger: 'getInfo'
734
- });
735
- url = new URL(cp + "/databases/configure");
736
- if (databaseName) {
737
- url.searchParams.set('databaseName', databaseName);
738
- }
739
- info('configuring from', url.href);
740
- _context.next = 16;
741
- return fetch(url, {
742
- headers: {
743
- Authorization: "Bearer " + getInfoBearer({
744
- config: config
745
- })
746
- }
747
- });
748
- case 16:
749
- res = _context.sent;
750
- possibleError = res.clone();
751
- _context.prev = 18;
752
- _context.next = 21;
753
- return res.json();
754
- case 21:
755
- json = _context.sent;
756
- if (res.status === 404) {
757
- info('is the configured databaseName correct?');
758
- }
759
- if (json.status && json.status !== 'READY') {
760
- database = {
761
- message: 'Database is not ready yet'
762
- };
763
- } else {
764
- database = json;
765
- }
766
- _context.next = 33;
767
- break;
768
- case 26:
769
- _context.prev = 26;
770
- _context.t0 = _context["catch"](18);
771
- _context.next = 30;
772
- return possibleError.text();
773
- case 30:
774
- message = _context.sent;
775
- error(message);
776
- database = {
777
- message: message
778
- };
779
- case 33:
780
- info('[fetched database]', database);
781
- if (!(process.env.NODE_ENV !== 'TEST')) {
782
- _context.next = 43;
783
- break;
784
- }
785
- if (!('message' in database)) {
786
- _context.next = 42;
787
- break;
788
- }
789
- if (!('statusCode' in database)) {
790
- _context.next = 41;
791
- break;
792
- }
793
- error(database);
794
- throw new Error('HTTP error has occurred');
795
- case 41:
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.');
797
- case 42:
798
- if (typeof database === 'object') {
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
801
- _this.databaseId = id;
802
- _this.databaseName = name;
803
- dburl = new URL(dbHost);
804
- configuredHost = dburl.host;
805
- basePath = duckApiHost;
806
- }
807
- case 43:
808
- (_envVarConfig$config = envVarConfig.config) == null || (_envVarConfig$config = _envVarConfig$config.api) == null || delete _envVarConfig$config.basePath;
809
- basePath = getBasePath(envVarConfig);
810
- _this.api = new ApiConfig({
811
- basePath: basePath,
812
- cookieKey: (_config$api$cookieKey = config == null || (_config$api = config.api) == null ? void 0 : _config$api.cookieKey) != null ? _config$api$cookieKey : 'token',
813
- token: getToken({
814
- config: config
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)
818
- });
819
- _this.db = _extends({
820
- user: _this.user,
821
- password: _this.password,
822
- host: configuredHost,
823
- port: configuredPort,
824
- database: _this.databaseName
825
- }, dbConfig);
826
- info('[config set]', _this);
827
- return _context.abrupt("return", _this);
828
- case 49:
829
- case "end":
830
- return _context.stop();
831
- }
832
- }, _callee, null, [[18, 26]]);
833
- }));
834
- return function (_x) {
835
- return _ref2.apply(this, arguments);
836
- };
837
- }();
838
- var _envVarConfig = {
839
- config: _config,
840
- logger: logger
841
- };
842
- this.user = getUsername(_envVarConfig);
843
- this.password = getPassword(_envVarConfig);
844
- if (process.env.NODE_ENV !== 'TEST') {
845
- if (!this.user) {
846
- throw new Error('User is required. Set NILEDB_USER as an environment variable or set `user` in the config options.');
847
- }
848
- if (!this.password) {
849
- throw new Error('Password is required. Set NILEDB_PASSWORD as an environment variable or set `password` in the config options.');
850
- }
851
- }
852
- this.databaseId = getDatabaseId(_envVarConfig);
853
- this.databaseName = getDatabaseName(_envVarConfig);
854
- this._tenantId = getTenantId(_envVarConfig);
855
- this.debug = Boolean(_config == null ? void 0 : _config.debug);
856
- this._userId = _config == null ? void 0 : _config.userId;
857
- var _basePath = getBasePath(_envVarConfig);
858
- var _ref4 = (_config$db2 = _config == null ? void 0 : _config.db) != null ? _config$db2 : {},
859
- _host = _ref4.host,
860
- _port = _ref4.port,
861
- _dbConfig = _objectWithoutPropertiesLoose(_ref4, _excluded2);
862
- var _configuredHost = _host != null ? _host : getDbHost(_envVarConfig);
863
- var _configuredPort = _port != null ? _port : getDbPort(_envVarConfig);
864
- this.api = new ApiConfig({
865
- basePath: _basePath,
866
- cookieKey: (_config$api$cookieKey2 = _config == null || (_config$api3 = _config.api) == null ? void 0 : _config$api3.cookieKey) != null ? _config$api$cookieKey2 : 'token',
867
- token: getToken({
868
- config: _config
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)
872
- });
873
- this.db = _extends({
874
- user: this.user,
875
- password: this.password,
876
- host: _configuredHost,
877
- port: _configuredPort
878
- }, _dbConfig);
879
- if (this.databaseName) {
880
- this.db.database = this.databaseName;
881
- }
882
- }
883
- return _createClass(Config, [{
884
- key: "tenantId",
885
- get: function get() {
886
- return this._tenantId;
887
- },
888
- set: function set(value) {
889
- this._tenantId = value;
890
- }
891
- }, {
892
- key: "userId",
893
- get: function get() {
894
- return this._userId;
895
- },
896
- set: function set(value) {
897
- this._userId = value;
898
- }
899
- }]);
900
- }();
901
-
902
- var Events;
903
- (function (Events) {
904
- Events["User"] = "userId";
905
- Events["Tenant"] = "tenantId";
906
- Events["Token"] = "token";
907
- Events["EvictPool"] = "EvictPool";
908
- })(Events || (Events = {}));
909
- var Eventer = /*#__PURE__*/function () {
910
- function Eventer() {
911
- this.events = void 0;
912
- this.events = {};
913
- }
914
- var _proto = Eventer.prototype;
915
- _proto.publish = function publish(eventName, value) {
916
- // Get all the callback functions of the current event
917
- var callbackList = this.events[eventName];
918
- // execute each callback function
919
- if (callbackList) {
920
- for (var _iterator = _createForOfIteratorHelperLoose(callbackList), _step; !(_step = _iterator()).done;) {
921
- var callback = _step.value;
922
- callback(value);
923
- }
924
- }
925
- }
926
- // Subscribe to events
927
- ;
928
- _proto.subscribe = function subscribe(eventName, callback) {
929
- // initialize this event
930
- if (!this.events[eventName]) {
931
- this.events[eventName] = [];
932
- }
933
- // store the callback function of the subscriber
934
- this.events[eventName].push(callback);
935
- };
936
- _proto.unsubscribe = function unsubscribe(eventName, callback) {
937
- var toRemove = this.events[eventName].findIndex(function (cb) {
938
- return cb === callback;
939
- });
940
- if (toRemove !== -1) {
941
- this.events[eventName].splice(toRemove, 1);
942
- }
943
- };
944
- return Eventer;
945
- }(); // tenantId manager
946
- var eventer = /*#__PURE__*/new Eventer();
947
- var updateTenantId = function updateTenantId(tenantId) {
948
- eventer.publish(Events.Tenant, tenantId);
949
- };
950
- var watchTenantId = function watchTenantId(cb) {
951
- return eventer.subscribe(Events.Tenant, cb);
952
- };
953
- var updateUserId = function updateUserId(userId) {
954
- eventer.publish(Events.User, userId);
955
- };
956
- var watchUserId = function watchUserId(cb) {
957
- return eventer.subscribe(Events.User, cb);
958
- };
959
- var watchToken = function watchToken(cb) {
960
- return eventer.subscribe(Events.Token, cb);
961
- };
962
- var watchEvictPool = function watchEvictPool(cb) {
963
- return eventer.subscribe(Events.EvictPool, cb);
964
- };
965
- var closeEvictPool = function closeEvictPool(cb) {
966
- return eventer.unsubscribe(Events.EvictPool, cb);
967
- };
968
- var evictPool = function evictPool(val) {
969
- eventer.publish(Events.EvictPool, val);
970
- };
971
-
972
- function createProxyForPool(pool, config) {
973
- var _Logger = Logger(config, '[pool]'),
974
- info = _Logger.info,
975
- error = _Logger.error;
976
- return new Proxy(pool, {
977
- get: function get(target, property) {
978
- if (property === 'query') {
979
- // give connection string a pass for these problems
980
- if (!config.db.connectionString) {
981
- if (!config.user || !config.password) {
982
- error('Cannot connect to the database. User and/or password are missing. Generate them at https://console.thenile.dev');
983
- } else if (!config.db.database) {
984
- error('Database name is missing from the config. Call `nile.init()` or set NILEDB_ID in your .env');
985
- }
986
- }
987
- var caller = target[property];
988
- return function query() {
989
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
990
- args[_key] = arguments[_key];
991
- }
992
- info.apply(void 0, args);
993
- // @ts-expect-error - not mine
994
- var called = caller.apply(this, args);
995
- return called;
996
- };
997
- }
998
- return target[property];
999
- }
1000
- });
1001
- }
1002
-
1003
- function isUUID(value) {
1004
- if (!value) {
1005
- return false;
1006
- }
1007
- var regex = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1008
- return regex.test(value);
1009
- }
1010
-
1011
- var _excluded$1 = ["afterCreate"];
1012
- var NileDatabase = /*#__PURE__*/function () {
1013
- function NileDatabase(config, id) {
1014
- var _this = this;
1015
- this.pool = void 0;
1016
- this.tenantId = void 0;
1017
- this.userId = void 0;
1018
- this.id = void 0;
1019
- this.config = void 0;
1020
- this.timer = void 0;
1021
- var _Logger = Logger(config, '[NileInstance]'),
1022
- warn = _Logger.warn,
1023
- info = _Logger.info;
1024
- this.id = id;
1025
- var poolConfig = _extends({
1026
- min: 0,
1027
- max: 10,
1028
- idleTimeoutMillis: 30000
1029
- }, config.db);
1030
- var afterCreate = poolConfig.afterCreate,
1031
- remaining = _objectWithoutPropertiesLoose(poolConfig, _excluded$1);
1032
- config.db = poolConfig;
1033
- this.config = config;
1034
- info(this.config.db);
1035
- this.pool = createProxyForPool(new Pool(remaining), this.config);
1036
- if (typeof afterCreate === 'function') {
1037
- warn('Providing an pool configuration will stop automatic tenant context setting.');
1038
- }
1039
- // start the timer for cleanup
1040
- this.startTimeout();
1041
- this.pool.on('connect', /*#__PURE__*/function () {
1042
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(client) {
1043
- var afterCreate;
1044
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1045
- while (1) switch (_context.prev = _context.next) {
1046
- case 0:
1047
- info('pool connected');
1048
- afterCreate = makeAfterCreate(config);
1049
- afterCreate(client, function (err) {
1050
- var _Logger2 = Logger(config, '[after create callback]'),
1051
- error = _Logger2.error;
1052
- if (err) {
1053
- error('after create failed', err);
1054
- evictPool(_this.id);
1055
- }
1056
- });
1057
- _this.startTimeout();
1058
- case 4:
1059
- case "end":
1060
- return _context.stop();
1061
- }
1062
- }, _callee);
1063
- }));
1064
- return function (_x) {
1065
- return _ref.apply(this, arguments);
1066
- };
1067
- }());
1068
- this.pool.on('error', /*#__PURE__*/function () {
1069
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(e) {
1070
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1071
- while (1) switch (_context2.prev = _context2.next) {
1072
- case 0:
1073
- info('pool failed', e);
1074
- if (_this.timer) {
1075
- clearTimeout(_this.timer);
1076
- }
1077
- evictPool(_this.id);
1078
- case 3:
1079
- case "end":
1080
- return _context2.stop();
1081
- }
1082
- }, _callee2);
1083
- }));
1084
- return function (_x2) {
1085
- return _ref2.apply(this, arguments);
1086
- };
1087
- }());
1088
- }
1089
- var _proto = NileDatabase.prototype;
1090
- _proto.startTimeout = function startTimeout() {
1091
- var _this2 = this;
1092
- var _Logger3 = Logger(this.config, '[NileInstance]'),
1093
- info = _Logger3.info;
1094
- if (this.timer) {
1095
- clearTimeout(this.timer);
1096
- }
1097
- this.timer = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
1098
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1099
- while (1) switch (_context3.prev = _context3.next) {
1100
- case 0:
1101
- info('Pool reached idleTimeoutMillis.', _this2.id, 'evicted after', _this2.config.db.idleTimeoutMillis, 'ms');
1102
- _context3.next = 3;
1103
- return _this2.pool.end(function () {
1104
- info('Pool end called');
1105
- // something odd going on here. Without the callback, pool.end() is flakey
1106
- });
1107
- case 3:
1108
- evictPool(_this2.id);
1109
- case 4:
1110
- case "end":
1111
- return _context3.stop();
1112
- }
1113
- }, _callee3);
1114
- })), this.config.db.idleTimeoutMillis);
1115
- };
1116
- return NileDatabase;
1117
- }();
1118
- function makeAfterCreate(config) {
1119
- var _Logger4 = Logger(config, '[afterCreate]'),
1120
- warn = _Logger4.warn,
1121
- info = _Logger4.info;
1122
- return function (conn, done) {
1123
- conn.on('error', function errorHandler(error) {
1124
- warn('Connection was terminated by server', error);
1125
- done(error, conn);
1126
- });
1127
- if (isUUID(config.tenantId)) {
1128
- var query = ["SET nile.tenant_id = '" + config.tenantId + "'"];
1129
- if (isUUID(config.userId)) {
1130
- if (!config.tenantId) {
1131
- warn('A user id cannot be set in context without a tenant id');
1132
- }
1133
- query.push("SET nile.user_id = '" + config.userId + "'");
1134
- }
1135
- // in this example we use pg driver's connection API
1136
- conn.query(query.join(';'), function (err) {
1137
- if (query.length === 1) {
1138
- info('[tenant id]', config.tenantId);
1139
- }
1140
- if (query.length === 2) {
1141
- info('[user id]', config.userId);
1142
- }
1143
- done(err, conn);
1144
- });
1145
- }
1146
- done(null, conn);
1147
- };
1148
- }
1149
-
1150
- var DBManager = /*#__PURE__*/function () {
1151
- function DBManager(_config) {
1152
- var _this = this;
1153
- this.connections = void 0;
1154
- this.cleared = void 0;
1155
- this.poolWatcher = function (config) {
1156
- return function (id) {
1157
- var _Logger = Logger(config, '[DBManager]'),
1158
- info = _Logger.info;
1159
- if (id && _this.connections.has(id)) {
1160
- info('Removing', id, 'from db connection pool.');
1161
- _this.connections["delete"](id);
1162
- }
1163
- };
1164
- };
1165
- this.getConnection = function (config) {
1166
- var _Logger2 = Logger(config, '[DBManager]'),
1167
- info = _Logger2.info;
1168
- var id = _this.makeId(config.tenantId, config.userId);
1169
- var existing = _this.connections.get(id);
1170
- info('# of instances:', _this.connections.size);
1171
- if (existing) {
1172
- info('returning existing', id);
1173
- existing.startTimeout();
1174
- return existing.pool;
1175
- }
1176
- var newOne = new NileDatabase(new Config(config), id);
1177
- _this.connections.set(id, newOne);
1178
- info('created new', id);
1179
- info('# of instances:', _this.connections.size);
1180
- // resume listening to the evict pool if a connection is requested.
1181
- if (_this.cleared) {
1182
- _this.cleared = false;
1183
- watchEvictPool(_this.poolWatcher(config));
1184
- }
1185
- return newOne.pool;
1186
- };
1187
- this.clear = function (config) {
1188
- var _Logger3 = Logger(config, '[DBManager]'),
1189
- info = _Logger3.info;
1190
- info('Clearing all connections', _this.connections.size);
1191
- closeEvictPool(_this.poolWatcher(config));
1192
- _this.cleared = true;
1193
- _this.connections.clear();
1194
- };
1195
- var _Logger4 = Logger(_config, '[DBManager]'),
1196
- _info = _Logger4.info;
1197
- this.cleared = false;
1198
- this.connections = new Map();
1199
- // add the base one, so you can at least query
1200
- var _id = this.makeId();
1201
- _info('constructor', _id);
1202
- this.connections.set(_id, new NileDatabase(new Config(_config), _id));
1203
- watchEvictPool(this.poolWatcher(_config));
1204
- }
1205
- var _proto = DBManager.prototype;
1206
- _proto.makeId = function makeId(tenantId, userId) {
1207
- if (isUUID(tenantId) && isUUID(userId)) {
1208
- return tenantId + ":" + userId;
1209
- }
1210
- if (isUUID(tenantId)) {
1211
- return "" + tenantId;
1212
- }
1213
- return 'base';
1214
- };
1215
- return DBManager;
1216
- }();
1217
-
1218
- var getServerId = function getServerId(config) {
1219
- var cfg = new Config(config);
1220
- return makeServerId(cfg);
1221
- };
1222
- var makeServerId = function makeServerId(config) {
1223
- return Buffer.from(JSON.stringify(config), 'utf8').toString('base64');
1224
- };
1225
-
1226
- var NILEDB_API_URL = process.env.NILEDB_API_URL;
1227
- function makeRestUrl(path, qp) {
1228
- if (!NILEDB_API_URL) {
1229
- throw new Error('An API url is required. Set it via NILEDB_API_URL.');
1230
- }
1231
- var params = new URLSearchParams(qp);
1232
- return "" + [NILEDB_API_URL, path.substring(1, path.length)].join('/') + (qp ? "?" + params.toString() : '');
1233
- }
1234
-
1235
- var apiRoutes = {
1236
- ME: /*#__PURE__*/makeRestUrl('/me'),
1237
- USERS: function USERS(tenantId) {
1238
- return makeRestUrl('/users', tenantId ? {
1239
- tenantId: tenantId
1240
- } : undefined);
1241
- },
1242
- USER: function USER(userId) {
1243
- return makeRestUrl("/users/" + userId);
1244
- },
1245
- TENANTS: /*#__PURE__*/makeRestUrl('/tenants'),
1246
- TENANT: function TENANT(tenantId) {
1247
- return makeRestUrl("/tenants/" + tenantId);
1248
- },
1249
- SIGNUP: /*#__PURE__*/makeRestUrl('/signup'),
1250
- TENANT_USERS: function TENANT_USERS(tenantId) {
1251
- return makeRestUrl("/tenants/" + tenantId + "/users");
1252
- },
1253
- TENANT_USER: function TENANT_USER(tenantId, userId) {
1254
- return makeRestUrl("/tenants/" + tenantId + "/users/" + userId);
1255
- },
1256
- USER_TENANTS: function USER_TENANTS(userId) {
1257
- return makeRestUrl("/users/" + userId + "/tenants");
1258
- }
1259
- };
1260
-
1261
- function urlMatches(requestUrl, route) {
1262
- var url = new URL(requestUrl);
1263
- return url.pathname.startsWith(route);
1264
- }
1265
-
1266
- var _excluded = ["request"];
1267
- var _console$1 = console,
1268
- log$1 = _console$1.log;
1269
- function request(_x, _x2, _x3) {
1270
- return _request.apply(this, arguments);
1271
- }
1272
- function _request() {
1273
- _request = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(url, _init, config) {
1274
- var _params$method;
1275
- var _Logger, info, error, request, init, requestUrl, updatedHeaders, params, _init$body, res, loggingRes;
1276
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1277
- while (1) switch (_context.prev = _context.next) {
1278
- case 0:
1279
- _Logger = Logger(_extends({}, config, {
1280
- debug: config == null ? void 0 : config.debug
1281
- }), '[REQUEST]', "[" + url + "]"), info = _Logger.info, error = _Logger.error;
1282
- request = _init.request, init = _objectWithoutPropertiesLoose(_init, _excluded);
1283
- requestUrl = new URL(request.url);
1284
- updatedHeaders = new Headers(request.headers);
1285
- updatedHeaders.set('host', requestUrl.host);
1286
- updatedHeaders.set('niledb-origin', requestUrl.origin);
1287
- updatedHeaders.set('niledb-creds', Buffer.from(process.env.NILEDB_USER + ":" + process.env.NILEDB_PASSWORD).toString('base64'));
1288
- params = _extends({}, init, {
1289
- headers: updatedHeaders
1290
- });
1291
- if (params.method === 'POST' || params.method === 'PUT') {
1292
- params.body = (_init$body = init.body) != null ? _init$body : request.body;
1293
- // @ts-expect-error - its there
1294
- params.duplex = 'half';
1295
- }
1296
- log$1("[" + ((_params$method = params.method) != null ? _params$method : 'GET') + "]", url);
1297
- _context.next = 12;
1298
- return fetch(url, _extends({}, params))["catch"](function (e) {
1299
- error('An error has occurred in the fetch', e);
1300
- return new Response('An unexpected (most likely configuration) problem has occurred', {
1301
- status: 500
1302
- });
1303
- });
1304
- case 12:
1305
- res = _context.sent;
1306
- loggingRes = typeof (res == null ? void 0 : res.clone) === 'function' ? res == null ? void 0 : res.clone() : null;
1307
- _context.t0 = info;
1308
- _context.t1 = res == null ? void 0 : res.status;
1309
- _context.t2 = res == null ? void 0 : res.statusText;
1310
- _context.next = 19;
1311
- return loggingRes == null ? void 0 : loggingRes.text();
1312
- case 19:
1313
- _context.t3 = _context.sent;
1314
- (0, _context.t0)('[Response]', _context.t1, _context.t2, _context.t3);
1315
- return _context.abrupt("return", res);
1316
- case 22:
1317
- case "end":
1318
- return _context.stop();
1319
- }
1320
- }, _callee);
1321
- }));
1322
- return _request.apply(this, arguments);
1323
- }
1324
-
1325
- var key$6 = 'ME';
1326
- var url = apiRoutes[key$6];
1327
- /**
1328
- * @swagger
1329
- * /api/me:
1330
- * get:
1331
- * summary: Identify the principal
1332
- * description: Returns information about the principal associated with the session
1333
- * provided
1334
- * operationId: me
1335
- * responses:
1336
- * "200":
1337
- * description: Identified user
1338
- * content:
1339
- * application/json:
1340
- * schema:
1341
- * $ref: '#/components/schemas/User'
1342
- * "400":
1343
- * description: API/Database failures
1344
- * content:
1345
- * text/plain:
1346
- * schema:
1347
- * type: string
1348
- * "404":
1349
- * description: Not found
1350
- * content: {}
1351
- * "401":
1352
- * description: Unauthorized
1353
- * content: {}
1354
- */
1355
- function GET$3(_x, _x2) {
1356
- return _GET$3.apply(this, arguments);
1357
- }
1358
- function _GET$3() {
1359
- _GET$3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(init, log) {
1360
- var res;
1361
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1362
- while (1) switch (_context.prev = _context.next) {
1363
- case 0:
1364
- log('[GET]', url);
1365
- _context.next = 3;
1366
- return request(url, init);
1367
- case 3:
1368
- res = _context.sent;
1369
- return _context.abrupt("return", res);
1370
- case 5:
1371
- case "end":
1372
- return _context.stop();
1373
- }
1374
- }, _callee);
1375
- }));
1376
- return _GET$3.apply(this, arguments);
1377
- }
1378
- function route$a(_x3, _x4) {
1379
- return _route$a.apply(this, arguments);
1380
- }
1381
- function _route$a() {
1382
- _route$a = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(request, config) {
1383
- var _Logger, info;
1384
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1385
- while (1) switch (_context2.prev = _context2.next) {
1386
- case 0:
1387
- _Logger = Logger(_extends({}, config, {
1388
- debug: config.debug
1389
- }), '[ROUTES]', "[" + key$6 + "]"), info = _Logger.info;
1390
- _context2.t0 = request.method;
1391
- _context2.next = _context2.t0 === 'GET' ? 4 : 7;
1392
- break;
1393
- case 4:
1394
- _context2.next = 6;
1395
- return GET$3({
1396
- request: request
1397
- }, info);
1398
- case 6:
1399
- return _context2.abrupt("return", _context2.sent);
1400
- case 7:
1401
- return _context2.abrupt("return", new Response('method not allowed', {
1402
- status: 405
1403
- }));
1404
- case 8:
1405
- case "end":
1406
- return _context2.stop();
1407
- }
1408
- }, _callee2);
1409
- }));
1410
- return _route$a.apply(this, arguments);
1411
- }
1412
- function matches$a(configRoutes, request) {
1413
- return urlMatches(request.url, configRoutes[key$6]);
1414
- }
1415
-
1416
- function auth(_x, _x2) {
1417
- return _auth.apply(this, arguments);
1418
- }
1419
- function _auth() {
1420
- _auth = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, config) {
1421
- var _Logger, info, sessionUrl, res;
1422
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1423
- while (1) switch (_context.prev = _context.next) {
1424
- case 0:
1425
- _Logger = Logger(_extends({}, config, {
1426
- debug: config.debug
1427
- }), '[nileauth]'), info = _Logger.info;
1428
- info('checking auth');
1429
- sessionUrl = config.api.basePath + "/auth/session";
1430
- info('using session', sessionUrl);
1431
- // handle the pass through with posts
1432
- req.headers["delete"]('content-length');
1433
- _context.next = 7;
1434
- return request(sessionUrl, {
1435
- request: req
1436
- });
1437
- case 7:
1438
- res = _context.sent;
1439
- if (res) {
1440
- _context.next = 11;
1441
- break;
1442
- }
1443
- info('no session found');
1444
- return _context.abrupt("return", undefined);
1445
- case 11:
1446
- info('session active');
1447
- _context.next = 14;
1448
- return new Response(res.body).json();
1449
- case 14:
1450
- return _context.abrupt("return", _context.sent);
1451
- case 15:
1452
- case "end":
1453
- return _context.stop();
1454
- }
1455
- }, _callee);
1456
- }));
1457
- return _auth.apply(this, arguments);
1458
- }
1459
-
1460
- var ResponseError = function ResponseError(body, init) {
1461
- this.response = void 0;
1462
- this.response = new Response(body, init);
1463
- };
1464
-
1465
- var X_NILE_TENANT = 'niledb-tenant-id';
1466
- var X_NILE_USER_ID = 'niledb-user-id';
1467
- function getTokenFromCookie(headers, cookieKey) {
1468
- var _headers$get;
1469
- var cookie = (_headers$get = headers.get('cookie')) == null ? void 0 : _headers$get.split('; ');
1470
- var _cookies = {};
1471
- if (cookie) {
1472
- for (var _iterator = _createForOfIteratorHelperLoose(cookie), _step; !(_step = _iterator()).done;) {
1473
- var parts = _step.value;
1474
- var cookieParts = parts.split('=');
1475
- var _cookie = cookieParts.slice(1).join('=');
1476
- var name = cookieParts[0];
1477
- _cookies[name] = _cookie;
1478
- }
1479
- }
1480
- if (cookie) {
1481
- for (var _iterator2 = _createForOfIteratorHelperLoose(cookie), _step2; !(_step2 = _iterator2()).done;) {
1482
- var _parts = _step2.value;
1483
- var _cookieParts = _parts.split('=');
1484
- var _cookie2 = _cookieParts.slice(1).join('=');
1485
- var _name = _cookieParts[0];
1486
- _cookies[_name] = _cookie2;
1487
- }
1488
- }
1489
- if (cookieKey) {
1490
- return _cookies[cookieKey];
1491
- }
1492
- return null;
1493
- }
1494
- function getTenantFromHttp(headers, config) {
1495
- var _ref;
1496
- var cookieTenant = getTokenFromCookie(headers, X_NILE_TENANT);
1497
- return (_ref = cookieTenant != null ? cookieTenant : headers == null ? void 0 : headers.get(X_NILE_TENANT)) != null ? _ref : config == null ? void 0 : config.tenantId;
1498
- }
1499
- function getUserFromHttp(headers, config) {
1500
- var _headers$get2;
1501
- var token = getTokenFromCookie(headers, config.api.cookieKey);
1502
- if (token) {
1503
- var jwt = decodeJwt(token);
1504
- return jwt.sub;
1505
- }
1506
- return (_headers$get2 = headers == null ? void 0 : headers.get(X_NILE_USER_ID)) != null ? _headers$get2 : config.userId;
1507
- }
1508
- function _fetch(_x, _x2, _x3) {
1509
- return _fetch2.apply(this, arguments);
1510
- }
1511
- function _fetch2() {
1512
- _fetch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config, path, opts) {
1513
- var _config$api, _config$api2, _response$status;
1514
- var _Logger, info, error, url, cookieKey, headers, basicHeaders, creds, authHeader, token, tenantId, userId, useableUrl, response, res, errorHandler, msg, _res, message, _res2, _res2$errors, _message;
1515
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1516
- while (1) switch (_context.prev = _context.next) {
1517
- case 0:
1518
- _Logger = Logger(config, '[server]'), info = _Logger.info, error = _Logger.error;
1519
- url = "" + ((_config$api = config.api) == null ? void 0 : _config$api.basePath) + path;
1520
- cookieKey = (_config$api2 = config.api) == null ? void 0 : _config$api2.cookieKey;
1521
- headers = new Headers(opts == null ? void 0 : opts.headers);
1522
- basicHeaders = new Headers(opts == null ? void 0 : opts.headers);
1523
- basicHeaders.set('content-type', 'application/json; charset=utf-8');
1524
- creds = Buffer.from(process.env.NILEDB_USER + ":" + process.env.NILEDB_PASSWORD, 'utf8').toString('base64');
1525
- basicHeaders.set('niledb-creds', creds);
1526
- authHeader = headers.get('Authorization');
1527
- if (!authHeader) {
1528
- token = getTokenFromCookie(headers, cookieKey);
1529
- if (token) {
1530
- basicHeaders.set('Authorization', "Bearer " + token);
1531
- } else if (getToken({
1532
- config: config
1533
- })) {
1534
- basicHeaders.set('Authorization', "Bearer " + getToken({
1535
- config: config
1536
- }));
1537
- }
1538
- }
1539
- tenantId = getTenantFromHttp(headers, config);
1540
- updateTenantId(tenantId);
1541
- userId = getUserFromHttp(headers, config);
1542
- updateUserId(userId);
1543
- if (!(url.includes('{tenantId}') && !tenantId)) {
1544
- _context.next = 16;
1545
- break;
1546
- }
1547
- return _context.abrupt("return", new ResponseError('tenantId is not set for request', {
1548
- status: 400
1549
- }));
1550
- case 16:
1551
- useableUrl = url.replace('{tenantId}', encodeURIComponent(String(tenantId))).replace('{userId}', encodeURIComponent(String(userId)));
1552
- info('[fetch]', useableUrl);
1553
- _context.next = 20;
1554
- return fetch(useableUrl, _extends({}, opts, {
1555
- headers: basicHeaders
1556
- }))["catch"](function (e) {
1557
- error('[fetch]', '[response]', e);
1558
- });
1559
- case 20:
1560
- response = _context.sent;
1561
- if (!(response && response.status >= 200 && response.status < 300)) {
1562
- _context.next = 39;
1563
- break;
1564
- }
1565
- if (!(typeof response.clone === 'function')) {
1566
- _context.next = 38;
1567
- break;
1568
- }
1569
- _context.prev = 23;
1570
- _context.t0 = info;
1571
- _context.next = 27;
1572
- return response.clone().json();
1573
- case 27:
1574
- _context.t1 = _context.sent;
1575
- (0, _context.t0)('[fetch]', '[response]', _context.t1);
1576
- _context.next = 38;
1577
- break;
1578
- case 31:
1579
- _context.prev = 31;
1580
- _context.t2 = _context["catch"](23);
1581
- _context.t3 = info;
1582
- _context.next = 36;
1583
- return response.clone().text();
1584
- case 36:
1585
- _context.t4 = _context.sent;
1586
- (0, _context.t3)('[fetch]', '[response]', _context.t4);
1587
- case 38:
1588
- return _context.abrupt("return", response);
1589
- case 39:
1590
- if (!((response == null ? void 0 : response.status) === 401)) {
1591
- _context.next = 41;
1592
- break;
1593
- }
1594
- return _context.abrupt("return", new ResponseError('Unauthorized', {
1595
- status: 401
1596
- }));
1597
- case 41:
1598
- if (!((response == null ? void 0 : response.status) === 405)) {
1599
- _context.next = 43;
1600
- break;
1601
- }
1602
- return _context.abrupt("return", new ResponseError('Method not allowed', {
1603
- status: 405
1604
- }));
1605
- case 43:
1606
- errorHandler = typeof (response == null ? void 0 : response.clone) === 'function' ? response.clone() : null;
1607
- msg = '';
1608
- _context.prev = 45;
1609
- _context.next = 48;
1610
- return response == null ? void 0 : response.json();
1611
- case 48:
1612
- res = _context.sent;
1613
- _context.next = 59;
1614
- break;
1615
- case 51:
1616
- _context.prev = 51;
1617
- _context.t5 = _context["catch"](45);
1618
- if (!errorHandler) {
1619
- _context.next = 58;
1620
- break;
1621
- }
1622
- _context.next = 56;
1623
- return errorHandler.text();
1624
- case 56:
1625
- msg = _context.sent;
1626
- if (msg) {
1627
- error('[fetch]', '[response]', "[status: " + errorHandler.status + "]", msg);
1628
- }
1629
- case 58:
1630
- if (!msg) {
1631
- error('[fetch]', '[response]', _context.t5);
1632
- }
1633
- case 59:
1634
- if (!msg) {
1635
- _context.next = 61;
1636
- break;
1637
- }
1638
- return _context.abrupt("return", new ResponseError(msg, {
1639
- status: errorHandler == null ? void 0 : errorHandler.status
1640
- }));
1641
- case 61:
1642
- if (!(res && 'message' in res)) {
1643
- _context.next = 65;
1644
- break;
1645
- }
1646
- _res = res, message = _res.message;
1647
- error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", message);
1648
- return _context.abrupt("return", new ResponseError(message, {
1649
- status: 400
1650
- }));
1651
- case 65:
1652
- if (!(res && 'errors' in res)) {
1653
- _context.next = 69;
1654
- break;
1655
- }
1656
- _res2 = res, _res2$errors = _res2.errors, _message = _res2$errors[0];
1657
- error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", _message);
1658
- return _context.abrupt("return", new ResponseError(_message, {
1659
- status: 400
1660
- }));
1661
- case 69:
1662
- error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", 'UNHANDLED ERROR');
1663
- return _context.abrupt("return", new ResponseError(null, {
1664
- status: (_response$status = response == null ? void 0 : response.status) != null ? _response$status : 500
1665
- }));
1666
- case 71:
1667
- case "end":
1668
- return _context.stop();
1669
- }
1670
- }, _callee, null, [[23, 31], [45, 51]]);
1671
- }));
1672
- return _fetch2.apply(this, arguments);
1673
- }
1674
-
1675
- /**
1676
- * @swagger
1677
- * /api/users:
1678
- * post:
1679
- * tags:
1680
- * - users
1681
- * summary: Creates a user
1682
- * description: Creates a user in the database
1683
- * operationId: createUser
1684
- * parameters:
1685
- * - name: tenantId
1686
- * description: A tenant id to add the user to when they are created
1687
- * in: query
1688
- * schema:
1689
- * type: string
1690
- * - name: newTenantName
1691
- * description: A tenant name to create, then the user to when they are created
1692
- * in: query
1693
- * schema:
1694
- * type: string
1695
- * requestBody:
1696
- * description: |-
1697
- * The email and password combination the user will use to authenticate.
1698
- * The `name` is optional; if provided it will be recorded in the `users` table.
1699
- * The `newTenant` is optional; if provided, it is used as the name of a new tenant record associated with the newly created user.
1700
- * content:
1701
- * application/json:
1702
- * schema:
1703
- * $ref: '#/components/schemas/CreateBasicUserRequest'
1704
- * examples:
1705
- * Create User Request:
1706
- * summary: Creates a user with basic credentials
1707
- * description: Create User Request
1708
- * value:
1709
- * email: a.user@somedomain.com
1710
- * password: somepassword
1711
- * name: A. User
1712
- * Create User Request with Tenant:
1713
- * summary: Creates a user and a new tenant for that user
1714
- * description: Create User Request with Tenant
1715
- * value:
1716
- * email: a.user@somedomain.com
1717
- * password: somepassword
1718
- * name: A. User
1719
- * newTenant: My Sandbox
1720
- * responses:
1721
- * "201":
1722
- * description: User created
1723
- * content:
1724
- * application/json:
1725
- * schema:
1726
- * $ref: "#/components/schemas/User"
1727
- * "400":
1728
- * description: API/Database failures
1729
- * content:
1730
- * text/plain:
1731
- * schema:
1732
- * type: string
1733
- * "401":
1734
- * description: Unauthorized
1735
- * content: {}
1736
- */
1737
- function POST$2(_x, _x2, _x3) {
1738
- return _POST$2.apply(this, arguments);
1739
- }
1740
- function _POST$2() {
1741
- _POST$2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
1742
- var yurl, tenantId, tenant, url;
1743
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1744
- while (1) switch (_context.prev = _context.next) {
1745
- case 0:
1746
- if (session) {
1747
- _context.next = 2;
1748
- break;
1749
- }
1750
- return _context.abrupt("return", new Response(null, {
1751
- status: 401
1752
- }));
1753
- case 2:
1754
- init.body = init.request.body;
1755
- init.method = 'POST';
1756
- yurl = new URL(init.request.url);
1757
- tenantId = yurl.searchParams.get('tenantId');
1758
- tenant = tenantId != null ? tenantId : getTenantFromHttp(init.request.headers);
1759
- url = apiRoutes.USERS(tenant ? tenant : undefined);
1760
- log && log('[POST]', url);
1761
- _context.next = 11;
1762
- return request(url, init);
1763
- case 11:
1764
- return _context.abrupt("return", _context.sent);
1765
- case 12:
1766
- case "end":
1767
- return _context.stop();
1768
- }
1769
- }, _callee);
1770
- }));
1771
- return _POST$2.apply(this, arguments);
1772
- }
1773
-
1774
- /**
1775
- * @swagger
1776
- * /api/users:
1777
- * get:
1778
- * tags:
1779
- * - users
1780
- * summary: lists users in the tenant
1781
- * description: Returns information about the users within the tenant
1782
- * provided. You can also pass the a `niledb-tenant-id` in the header or in a cookie.
1783
- * operationId: listUsers
1784
- * parameters:
1785
- * - name: tenantId
1786
- * in: query
1787
- * schema:
1788
- * type: string
1789
- * responses:
1790
- * "200":
1791
- * description: A list of users
1792
- * content:
1793
- * application/json:
1794
- * schema:
1795
- * type: array
1796
- * items:
1797
- * $ref: '#/components/schemas/TenantUser'
1798
- * "404":
1799
- * description: Not found
1800
- * content: {}
1801
- * "401":
1802
- * description: Unauthorized
1803
- * content: {}
1804
- */
1805
- function GET$2(_x, _x2) {
1806
- return _GET$2.apply(this, arguments);
1807
- }
1808
- function _GET$2() {
1809
- _GET$2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(init, log) {
1810
- var yurl, tenantId, tenant, url;
1811
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1812
- while (1) switch (_context.prev = _context.next) {
1813
- case 0:
1814
- yurl = new URL(init.request.url);
1815
- tenantId = yurl.searchParams.get('tenantId');
1816
- tenant = tenantId != null ? tenantId : getTenantFromHttp(init.request.headers);
1817
- if (tenant) {
1818
- _context.next = 6;
1819
- break;
1820
- }
1821
- log('[GET]', '[ERROR]', 'No tenant id provided.');
1822
- return _context.abrupt("return", new Response(null, {
1823
- status: 404
1824
- }));
1825
- case 6:
1826
- url = apiRoutes.TENANT_USERS(tenant);
1827
- log('[GET]', url);
1828
- init.method = 'GET';
1829
- _context.next = 11;
1830
- return request(url, init);
1831
- case 11:
1832
- return _context.abrupt("return", _context.sent);
1833
- case 12:
1834
- case "end":
1835
- return _context.stop();
1836
- }
1837
- }, _callee);
1838
- }));
1839
- return _GET$2.apply(this, arguments);
1840
- }
1841
-
1842
- /**
1843
- * @swagger
1844
- * /api/users/{userid}:
1845
- * put:
1846
- * tags:
1847
- * - users
1848
- * summary: update a user
1849
- * description: updates a user within the tenant
1850
- * operationId: updateUser
1851
- * parameters:
1852
- * - name: userid
1853
- * in: path
1854
- * required: true
1855
- * schema:
1856
- * type: string
1857
- * requestBody:
1858
- * description: |-
1859
- * Update a user
1860
- * content:
1861
- * application/json:
1862
- * schema:
1863
- * $ref: '#/components/schemas/UpdateUserRequest'
1864
- * responses:
1865
- * "200":
1866
- * description: An updated user
1867
- * content:
1868
- * application/json:
1869
- * schema:
1870
- * $ref: '#/components/schemas/User'
1871
- * "404":
1872
- * description: Not found
1873
- * content: {}
1874
- * "401":
1875
- * description: Unauthorized
1876
- * content: {}
1877
- */
1878
- function PUT$1(_x, _x2, _x3) {
1879
- return _PUT$1.apply(this, arguments);
1880
- }
1881
- function _PUT$1() {
1882
- _PUT$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
1883
- var _URL$pathname$split$r, userId, url;
1884
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1885
- while (1) switch (_context.prev = _context.next) {
1886
- case 0:
1887
- if (session) {
1888
- _context.next = 2;
1889
- break;
1890
- }
1891
- return _context.abrupt("return", new Response(null, {
1892
- status: 401
1893
- }));
1894
- case 2:
1895
- init.body = init.request.body;
1896
- init.method = 'PUT';
1897
- // update the user
1898
- _URL$pathname$split$r = new URL(init.request.url).pathname.split('/').reverse(), userId = _URL$pathname$split$r[0];
1899
- url = apiRoutes.USER(userId);
1900
- log('[PUT]', url);
1901
- _context.next = 9;
1902
- return request(url, init);
1903
- case 9:
1904
- return _context.abrupt("return", _context.sent);
1905
- case 10:
1906
- case "end":
1907
- return _context.stop();
1908
- }
1909
- }, _callee);
1910
- }));
1911
- return _PUT$1.apply(this, arguments);
1912
- }
1913
-
1914
- var key$5 = 'USERS';
1915
- function route$9(_x, _x2) {
1916
- return _route$9.apply(this, arguments);
1917
- }
1918
- function _route$9() {
1919
- _route$9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request, config) {
1920
- var _Logger, info, session;
1921
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1922
- while (1) switch (_context.prev = _context.next) {
1923
- case 0:
1924
- _Logger = Logger(_extends({}, config, {
1925
- debug: config.debug
1926
- }), '[ROUTES]', "[" + key$5 + "]"), info = _Logger.info;
1927
- _context.next = 3;
1928
- return auth(request, config);
1929
- case 3:
1930
- session = _context.sent;
1931
- _context.t0 = request.method;
1932
- _context.next = _context.t0 === 'GET' ? 7 : _context.t0 === 'POST' ? 10 : _context.t0 === 'PUT' ? 13 : 16;
1933
- break;
1934
- case 7:
1935
- _context.next = 9;
1936
- return GET$2({
1937
- request: request
1938
- }, info);
1939
- case 9:
1940
- return _context.abrupt("return", _context.sent);
1941
- case 10:
1942
- _context.next = 12;
1943
- return POST$2(session, {
1944
- request: request
1945
- }, info);
1946
- case 12:
1947
- return _context.abrupt("return", _context.sent);
1948
- case 13:
1949
- _context.next = 15;
1950
- return PUT$1(session, {
1951
- request: request
1952
- }, info);
1953
- case 15:
1954
- return _context.abrupt("return", _context.sent);
1955
- case 16:
1956
- return _context.abrupt("return", new Response('method not allowed', {
1957
- status: 405
1958
- }));
1959
- case 17:
1960
- case "end":
1961
- return _context.stop();
1962
- }
1963
- }, _callee);
1964
- }));
1965
- return _route$9.apply(this, arguments);
1966
- }
1967
- function matches$9(configRoutes, request) {
1968
- return urlMatches(request.url, configRoutes[key$5]);
1969
- }
1970
-
1971
- /**
1972
- * @swagger
1973
- * /api/tenants/{tenantId}/users:
1974
- * get:
1975
- * tags:
1976
- * - users
1977
- * summary: List tenant users
1978
- * description: Lists users that are associated with the specified tenant.
1979
- * operationId: listTenantUsers
1980
- * parameters:
1981
- * - name: tenantId
1982
- * in: path
1983
- * required: true
1984
- * schema:
1985
- * type: string
1986
- * responses:
1987
- * "200":
1988
- * description: Users found
1989
- * content:
1990
- * application/json:
1991
- * schema:
1992
- * type: array
1993
- * items:
1994
- * $ref: '#/components/schemas/User'
1995
- * "401":
1996
- * description: Unauthorized
1997
- * content:
1998
- * application/json:
1999
- * schema:
2000
- * $ref: '#/components/schemas/APIError'
2001
- */
2002
- function GET$1(_x, _x2, _x3) {
2003
- return _GET$1.apply(this, arguments);
2004
- }
2005
- function _GET$1() {
2006
- _GET$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2007
- var yurl, _yurl$pathname$split$, tenantId, url;
2008
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2009
- while (1) switch (_context.prev = _context.next) {
2010
- case 0:
2011
- yurl = new URL(init.request.url);
2012
- _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[1];
2013
- if (tenantId) {
2014
- _context.next = 4;
2015
- break;
2016
- }
2017
- return _context.abrupt("return", new Response(null, {
2018
- status: 404
2019
- }));
2020
- case 4:
2021
- url = "" + apiRoutes.TENANT_USERS(tenantId);
2022
- log('[GET]', '[TENANT_USERS]', url);
2023
- _context.next = 8;
2024
- return request(url, init);
2025
- case 8:
2026
- return _context.abrupt("return", _context.sent);
2027
- case 9:
2028
- case "end":
2029
- return _context.stop();
2030
- }
2031
- }, _callee);
2032
- }));
2033
- return _GET$1.apply(this, arguments);
2034
- }
2035
-
2036
- /**
2037
- * @swagger
2038
- * /api/tenants/{tenantId}/users:
2039
- * post:
2040
- * tags:
2041
- * - users
2042
- * summary: Create a user in a tenant
2043
- * description: Creates a new user and associates that user with the specified
2044
- * tenant.
2045
- * operationId: createTenantUser
2046
- * parameters:
2047
- * - name: tenantId
2048
- * in: path
2049
- * required: true
2050
- * schema:
2051
- * type: string
2052
- * requestBody:
2053
- * description: |
2054
- * The email and password combination the user will use to authenticate.
2055
- * The `name` is optional; if provided it will be recorded in the `users` table.
2056
- * content:
2057
- * application/json:
2058
- * schema:
2059
- * $ref: '#/components/schemas/CreateBasicUserRequest'
2060
- * examples:
2061
- * Create User Request:
2062
- * summary: Creates a user with basic credentials
2063
- * description: Create User Request
2064
- * value:
2065
- * email: a.user@somedomain.com
2066
- * password: somepassword
2067
- * name: A. User
2068
- * responses:
2069
- * "201":
2070
- * description: User created
2071
- * content:
2072
- * application/json:
2073
- * schema:
2074
- * $ref: '#/components/schemas/User'
2075
- */
2076
- function POST$1(_x, _x2, _x3) {
2077
- return _POST$1.apply(this, arguments);
2078
- }
2079
- function _POST$1() {
2080
- _POST$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2081
- var yurl, _yurl$pathname$split$, tenantId, url;
2082
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2083
- while (1) switch (_context.prev = _context.next) {
2084
- case 0:
2085
- yurl = new URL(init.request.url);
2086
- _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[1]; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2087
- // @ts-ignore
2088
- init.body = JSON.stringify({
2089
- email: session.email
2090
- });
2091
- init.method = 'PUT';
2092
- url = apiRoutes.TENANT_USERS(tenantId);
2093
- log('[PUT]', url);
2094
- _context.next = 8;
2095
- return request(url, init);
2096
- case 8:
2097
- return _context.abrupt("return", _context.sent);
2098
- case 9:
2099
- case "end":
2100
- return _context.stop();
2101
- }
2102
- }, _callee);
2103
- }));
2104
- return _POST$1.apply(this, arguments);
2105
- }
2106
-
2107
- /**
2108
- * @swagger
2109
- * /api/tenants/{tenantId}/users/{email}:
2110
- * delete:
2111
- * tags:
2112
- * - tenants
2113
- * summary: removes a user from a tenant
2114
- * description: removes an associated user from a specified
2115
- * tenant.
2116
- * operationId: unlinkUser
2117
- * parameters:
2118
- * - name: tenantId
2119
- * in: path
2120
- * required: true
2121
- * schema:
2122
- * type: string
2123
- * - name: email
2124
- * in: path
2125
- * required: true
2126
- * schema:
2127
- * type: string
2128
-
2129
- * responses:
2130
- * "204":
2131
- * description: User removed
2132
- */
2133
- function DELETE$1(_x, _x2, _x3) {
2134
- return _DELETE$1.apply(this, arguments);
2135
- }
2136
- function _DELETE$1() {
2137
- _DELETE$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2138
- var yurl, _yurl$pathname$split$, userId, tenantId, url;
2139
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2140
- while (1) switch (_context.prev = _context.next) {
2141
- case 0:
2142
- yurl = new URL(init.request.url); // eslint-disable-next-line @typescript-eslint/no-unused-vars
2143
- _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), userId = _yurl$pathname$split$[0], tenantId = _yurl$pathname$split$[2];
2144
- if (tenantId) {
2145
- _context.next = 4;
2146
- break;
2147
- }
2148
- return _context.abrupt("return", new Response(null, {
2149
- status: 404
2150
- }));
2151
- case 4:
2152
- init.method = 'DELETE';
2153
- init.body = JSON.stringify({
2154
- email: userId
2155
- });
2156
- url = "" + apiRoutes.TENANT_USER(tenantId, userId);
2157
- log('[DELETE]', url);
2158
- _context.next = 10;
2159
- return request(url, init);
2160
- case 10:
2161
- return _context.abrupt("return", _context.sent);
2162
- case 11:
2163
- case "end":
2164
- return _context.stop();
2165
- }
2166
- }, _callee);
2167
- }));
2168
- return _DELETE$1.apply(this, arguments);
2169
- }
2170
-
2171
- /**
2172
- * @swagger
2173
- * /api/tenants/{tenantId}/users:
2174
- * put:
2175
- * tags:
2176
- * - tenants
2177
- * summary: associates an existing user with the tenant
2178
- * operationId: linkUser
2179
- * parameters:
2180
- * - name: tenantId
2181
- * in: path
2182
- * required: true
2183
- * schema:
2184
- * type: string
2185
- * requestBody:
2186
- * description: |
2187
- * The email of the user you want to add to a tenant.
2188
- * content:
2189
- * application/json:
2190
- * schema:
2191
- * $ref: '#/components/schemas/AssociateUserRequest'
2192
- * responses:
2193
- * "201":
2194
- * description: add user to tenant
2195
- */
2196
- function PUT(_x, _x2, _x3) {
2197
- return _PUT.apply(this, arguments);
2198
- }
2199
- function _PUT() {
2200
- _PUT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2201
- var yurl, _yurl$pathname$split$, tenantId, url;
2202
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2203
- while (1) switch (_context.prev = _context.next) {
2204
- case 0:
2205
- yurl = new URL(init.request.url);
2206
- _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[1];
2207
- if (tenantId) {
2208
- _context.next = 4;
2209
- break;
2210
- }
2211
- return _context.abrupt("return", new Response(null, {
2212
- status: 404
2213
- }));
2214
- case 4:
2215
- init.method = 'PUT';
2216
- url = "" + apiRoutes.TENANT_USERS(tenantId);
2217
- log('[PUT]', url);
2218
- _context.next = 9;
2219
- return request(url, init);
2220
- case 9:
2221
- return _context.abrupt("return", _context.sent);
2222
- case 10:
2223
- case "end":
2224
- return _context.stop();
2225
- }
2226
- }, _callee);
2227
- }));
2228
- return _PUT.apply(this, arguments);
2229
- }
2230
-
2231
- var key$4 = 'TENANT_USERS';
2232
- function route$8(_x, _x2) {
2233
- return _route$8.apply(this, arguments);
2234
- }
2235
- function _route$8() {
2236
- _route$8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request, config) {
2237
- var _Logger, info, session;
2238
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2239
- while (1) switch (_context.prev = _context.next) {
2240
- case 0:
2241
- _Logger = Logger(_extends({}, config, {
2242
- debug: config.debug
2243
- }), '[ROUTES]', "[" + key$4 + "]"), info = _Logger.info;
2244
- _context.next = 3;
2245
- return auth(request, config);
2246
- case 3:
2247
- session = _context.sent;
2248
- if (session) {
2249
- _context.next = 7;
2250
- break;
2251
- }
2252
- info('401');
2253
- return _context.abrupt("return", new Response(null, {
2254
- status: 401
2255
- }));
2256
- case 7:
2257
- _context.t0 = request.method;
2258
- _context.next = _context.t0 === 'GET' ? 10 : _context.t0 === 'POST' ? 13 : _context.t0 === 'PUT' ? 16 : _context.t0 === 'DELETE' ? 19 : 22;
2259
- break;
2260
- case 10:
2261
- _context.next = 12;
2262
- return GET$1(session, {
2263
- request: request
2264
- }, info);
2265
- case 12:
2266
- return _context.abrupt("return", _context.sent);
2267
- case 13:
2268
- _context.next = 15;
2269
- return POST$1(session, {
2270
- request: request
2271
- }, info);
2272
- case 15:
2273
- return _context.abrupt("return", _context.sent);
2274
- case 16:
2275
- _context.next = 18;
2276
- return PUT(session, {
2277
- request: request
2278
- }, info);
2279
- case 18:
2280
- return _context.abrupt("return", _context.sent);
2281
- case 19:
2282
- _context.next = 21;
2283
- return DELETE$1(session, {
2284
- request: request
2285
- }, info);
2286
- case 21:
2287
- return _context.abrupt("return", _context.sent);
2288
- case 22:
2289
- return _context.abrupt("return", new Response('method not allowed', {
2290
- status: 405
2291
- }));
2292
- case 23:
2293
- case "end":
2294
- return _context.stop();
2295
- }
2296
- }, _callee);
2297
- }));
2298
- return _route$8.apply(this, arguments);
2299
- }
2300
- function matches$8(configRoutes, request) {
2301
- var url = new URL(request.url);
2302
- var _url$pathname$split$r = url.pathname.split('/').reverse(),
2303
- userId = _url$pathname$split$r[0],
2304
- possibleTenantId = _url$pathname$split$r[1],
2305
- tenantId = _url$pathname$split$r[2];
2306
- var route = configRoutes[key$4].replace('{tenantId}', tenantId).replace('{userId}', userId);
2307
- if (userId === 'users') {
2308
- route = configRoutes[key$4].replace('{tenantId}', possibleTenantId);
2309
- }
2310
- return urlMatches(request.url, route);
2311
- }
2312
-
2313
- /**
2314
- * @swagger
2315
- * /api/tenants:
2316
- * get:
2317
- * tags:
2318
- * - tenants
2319
- * summary: list tenants by user
2320
- * description: Creates a user in the database
2321
- * operationId: listTenants
2322
- * responses:
2323
- * "200":
2324
- * description: a list of tenants
2325
- * content:
2326
- * application/json:
2327
- * schema:
2328
- * type: array
2329
- * items:
2330
- * $ref: "#/components/schemas/Tenant"
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 GET(_x, _x2, _x3) {
2342
- return _GET.apply(this, arguments);
2343
- }
2344
- function _GET() {
2345
- _GET = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2346
- var url, res;
2347
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2348
- while (1) switch (_context.prev = _context.next) {
2349
- case 0:
2350
- url = "" + apiRoutes.USER_TENANTS(session.id);
2351
- if (typeof session === 'object' && 'user' in session && session.user) {
2352
- url = "" + apiRoutes.USER_TENANTS(session.user.id);
2353
- }
2354
- log('[GET]', url);
2355
- _context.next = 5;
2356
- return request(url, init);
2357
- case 5:
2358
- res = _context.sent;
2359
- return _context.abrupt("return", res);
2360
- case 7:
2361
- case "end":
2362
- return _context.stop();
2363
- }
2364
- }, _callee);
2365
- }));
2366
- return _GET.apply(this, arguments);
2367
- }
2368
-
2369
- /**
2370
- * @swagger
2371
- * /api/tenants/{tenantId}:
2372
- * delete:
2373
- * tags:
2374
- * - tenants
2375
- * summary: Deletes a tenant.
2376
- * operationId: deleteTenant
2377
- * parameters:
2378
- * - name: tenantId
2379
- * in: path
2380
- * required: true
2381
- * schema:
2382
- * type: string
2383
- * responses:
2384
- * "204":
2385
- * description: Tenant deleted
2386
- * "401":
2387
- * description: Unauthorized
2388
- * content:
2389
- * application/json:
2390
- * schema:
2391
- * $ref: '#/components/schemas/APIError'
2392
- * "404":
2393
- * description: Tenant not found
2394
- * content:
2395
- * application/json:
2396
- * schema:
2397
- * $ref: '#/components/schemas/APIError'
2398
- */
2399
- function DELETE(_x, _x2, _x3) {
2400
- return _DELETE.apply(this, arguments);
2401
- }
2402
- function _DELETE() {
2403
- _DELETE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2404
- var yurl, _yurl$pathname$split$, tenantId, url;
2405
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2406
- while (1) switch (_context.prev = _context.next) {
2407
- case 0:
2408
- yurl = new URL(init.request.url);
2409
- _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[0];
2410
- if (tenantId) {
2411
- _context.next = 4;
2412
- break;
2413
- }
2414
- return _context.abrupt("return", new Response(null, {
2415
- status: 404
2416
- }));
2417
- case 4:
2418
- init.method = 'DELETE';
2419
- url = "" + apiRoutes.TENANT(tenantId);
2420
- log('[DELETE]', url);
2421
- _context.next = 9;
2422
- return request(url, init);
2423
- case 9:
2424
- return _context.abrupt("return", _context.sent);
2425
- case 10:
2426
- case "end":
2427
- return _context.stop();
2428
- }
2429
- }, _callee);
2430
- }));
2431
- return _DELETE.apply(this, arguments);
2432
- }
2433
-
2434
- /**
2435
- * @swagger
2436
- * /api/tenants:
2437
- * post:
2438
- * tags:
2439
- * - tenants
2440
- * summary: Create a tenant
2441
- * description: Creates a new tenant in a database.
2442
- * operationId: createTenant
2443
- * requestBody:
2444
- * description: A wrapper for the tenant name.
2445
- * content:
2446
- * application/json:
2447
- * schema:
2448
- * $ref: '#/components/schemas/CreateTenantRequest'
2449
- * examples:
2450
- * Create Tenant Request:
2451
- * summary: Creates a named tenant
2452
- * description: Create Tenant Request
2453
- * value:
2454
- * name: My Sandbox
2455
- * responses:
2456
- * "201":
2457
- * description: Tenant created
2458
- * content:
2459
- * application/json:
2460
- * schema:
2461
- * $ref: '#/components/schemas/Tenant'
2462
- * "401":
2463
- * description: Unauthorized
2464
- * content:
2465
- * application/json:
2466
- * schema:
2467
- * $ref: '#/components/schemas/APIError'
2468
- * "404":
2469
- * description: Database not found
2470
- * content:
2471
- * application/json:
2472
- * schema:
2473
- * $ref: '#/components/schemas/APIError'
2474
- */
2475
- function POST(_x, _x2, _x3) {
2476
- return _POST.apply(this, arguments);
2477
- }
2478
- function _POST() {
2479
- _POST = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2480
- var url;
2481
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2482
- while (1) switch (_context.prev = _context.next) {
2483
- case 0:
2484
- init.body = init.request.body;
2485
- init.method = 'POST';
2486
- url = "" + apiRoutes.TENANTS;
2487
- log('[POST]', url);
2488
- _context.next = 6;
2489
- return request(url, init);
2490
- case 6:
2491
- return _context.abrupt("return", _context.sent);
2492
- case 7:
2493
- case "end":
2494
- return _context.stop();
2495
- }
2496
- }, _callee);
2497
- }));
2498
- return _POST.apply(this, arguments);
2499
- }
2500
-
2501
- var key$3 = 'TENANTS';
2502
- function route$7(_x, _x2) {
2503
- return _route$7.apply(this, arguments);
2504
- }
2505
- function _route$7() {
2506
- _route$7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request, config) {
2507
- var _Logger, info, session;
2508
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2509
- while (1) switch (_context.prev = _context.next) {
2510
- case 0:
2511
- _Logger = Logger(_extends({}, config, {
2512
- debug: config.debug
2513
- }), '[ROUTES]', "[" + key$3 + "]"), info = _Logger.info;
2514
- _context.next = 3;
2515
- return auth(request, config);
2516
- case 3:
2517
- session = _context.sent;
2518
- if (session) {
2519
- _context.next = 7;
2520
- break;
2521
- }
2522
- info('401');
2523
- return _context.abrupt("return", new Response(null, {
2524
- status: 401
2525
- }));
2526
- case 7:
2527
- _context.t0 = request.method;
2528
- _context.next = _context.t0 === 'GET' ? 10 : _context.t0 === 'POST' ? 13 : _context.t0 === 'DELETE' ? 16 : 19;
2529
- break;
2530
- case 10:
2531
- _context.next = 12;
2532
- return GET(session, {
2533
- request: request
2534
- }, info);
2535
- case 12:
2536
- return _context.abrupt("return", _context.sent);
2537
- case 13:
2538
- _context.next = 15;
2539
- return POST(session, {
2540
- request: request
2541
- }, info);
2542
- case 15:
2543
- return _context.abrupt("return", _context.sent);
2544
- case 16:
2545
- _context.next = 18;
2546
- return DELETE(session, {
2547
- request: request
2548
- }, info);
2549
- case 18:
2550
- return _context.abrupt("return", _context.sent);
2551
- case 19:
2552
- return _context.abrupt("return", new Response('method not allowed', {
2553
- status: 405
2554
- }));
2555
- case 20:
2556
- case "end":
2557
- return _context.stop();
2558
- }
2559
- }, _callee);
2560
- }));
2561
- return _route$7.apply(this, arguments);
2562
- }
2563
- function matches$7(configRoutes, request) {
2564
- return urlMatches(request.url, configRoutes[key$3]);
2565
- }
2566
-
2567
- var proxyRoutes = {
2568
- SIGNIN: /*#__PURE__*/makeRestUrl('/auth/signin'),
2569
- PROVIDERS: /*#__PURE__*/makeRestUrl('/auth/providers'),
2570
- SESSION: /*#__PURE__*/makeRestUrl('/auth/session'),
2571
- CSRF: /*#__PURE__*/makeRestUrl('/auth/csrf'),
2572
- CALLBACK: /*#__PURE__*/makeRestUrl('/auth/callback'),
2573
- SIGNOUT: /*#__PURE__*/makeRestUrl('/auth/signout'),
2574
- ERROR: /*#__PURE__*/makeRestUrl('/auth/error')
2575
- };
2576
-
2577
- var key$2 = 'SIGNIN';
2578
- function route$6(_x) {
2579
- return _route$6.apply(this, arguments);
2580
- }
2581
- function _route$6() {
2582
- _route$6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2583
- var url, init, _URL$pathname$split$r, provider, passThroughUrl, params, res;
2584
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2585
- while (1) switch (_context.prev = _context.next) {
2586
- case 0:
2587
- url = proxyRoutes[key$2];
2588
- init = {
2589
- method: req.method,
2590
- headers: req.headers
2591
- };
2592
- if (req.method === 'POST') {
2593
- if (typeof req.clone === 'function') {
2594
- init.body = req.clone().body;
2595
- }
2596
- _URL$pathname$split$r = new URL(req.url).pathname.split('/').reverse(), provider = _URL$pathname$split$r[0];
2597
- url = proxyRoutes[key$2] + "/" + provider;
2598
- }
2599
- passThroughUrl = new URL(req.url);
2600
- params = new URLSearchParams(passThroughUrl.search);
2601
- url = "" + url + (params.toString() !== '' ? "?" + params.toString() : '');
2602
- _context.next = 8;
2603
- return request(url, _extends({}, init, {
2604
- request: req
2605
- }));
2606
- case 8:
2607
- res = _context.sent;
2608
- return _context.abrupt("return", res);
2609
- case 10:
2610
- case "end":
2611
- return _context.stop();
2612
- }
2613
- }, _callee);
2614
- }));
2615
- return _route$6.apply(this, arguments);
2616
- }
2617
- function matches$6(configRoutes, request) {
2618
- return urlMatches(request.url, configRoutes[key$2]);
2619
- }
2620
-
2621
- function route$5(_x, _x2) {
2622
- return _route$5.apply(this, arguments);
2623
- }
2624
- function _route$5() {
2625
- _route$5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, config) {
2626
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2627
- while (1) switch (_context.prev = _context.next) {
2628
- case 0:
2629
- return _context.abrupt("return", request(proxyRoutes.SESSION, {
2630
- method: req.method,
2631
- request: req
2632
- }, config));
2633
- case 1:
2634
- case "end":
2635
- return _context.stop();
2636
- }
2637
- }, _callee);
2638
- }));
2639
- return _route$5.apply(this, arguments);
2640
- }
2641
- function matches$5(configRoutes, request) {
2642
- return urlMatches(request.url, configRoutes.SESSION);
2643
- }
2644
-
2645
- function route$4(_x) {
2646
- return _route$4.apply(this, arguments);
2647
- }
2648
- function _route$4() {
2649
- _route$4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2650
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2651
- while (1) switch (_context.prev = _context.next) {
2652
- case 0:
2653
- return _context.abrupt("return", request(proxyRoutes.PROVIDERS, {
2654
- method: req.method,
2655
- request: req
2656
- }));
2657
- case 1:
2658
- case "end":
2659
- return _context.stop();
2660
- }
2661
- }, _callee);
2662
- }));
2663
- return _route$4.apply(this, arguments);
2664
- }
2665
- function matches$4(configRoutes, request) {
2666
- return urlMatches(request.url, configRoutes.PROVIDERS);
2667
- }
2668
-
2669
- function route$3(_x) {
2670
- return _route$3.apply(this, arguments);
2671
- }
2672
- function _route$3() {
2673
- _route$3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2674
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2675
- while (1) switch (_context.prev = _context.next) {
2676
- case 0:
2677
- return _context.abrupt("return", request(proxyRoutes.CSRF, {
2678
- method: req.method,
2679
- request: req
2680
- }));
2681
- case 1:
2682
- case "end":
2683
- return _context.stop();
2684
- }
2685
- }, _callee);
2686
- }));
2687
- return _route$3.apply(this, arguments);
2688
- }
2689
- function matches$3(configRoutes, request) {
2690
- return urlMatches(request.url, configRoutes.CSRF);
2691
- }
2692
-
2693
- var _console = console,
2694
- log = _console.log,
2695
- error = _console.error;
2696
- function route$2(_x) {
2697
- return _route$2.apply(this, arguments);
2698
- }
2699
- function _route$2() {
2700
- _route$2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request$1) {
2701
- var _URL$pathname$split$r, provider, passThroughUrl, params, url, res, location;
2702
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2703
- while (1) switch (_context.prev = _context.next) {
2704
- case 0:
2705
- _URL$pathname$split$r = new URL(request$1.url).pathname.split('/').reverse(), provider = _URL$pathname$split$r[0];
2706
- passThroughUrl = new URL(request$1.url);
2707
- params = new URLSearchParams(passThroughUrl.search);
2708
- url = proxyRoutes.CALLBACK + "/" + provider + (params.toString() !== '' ? "?" + params.toString() : '');
2709
- _context.next = 6;
2710
- return request(url, {
2711
- request: request$1,
2712
- method: request$1.method
2713
- })["catch"](function (e) {
2714
- error('an error has occurred in callback');
2715
- log(e);
2716
- });
2717
- case 6:
2718
- res = _context.sent;
2719
- location = res == null ? void 0 : res.headers.get('location');
2720
- if (!location) {
2721
- _context.next = 10;
2722
- break;
2723
- }
2724
- return _context.abrupt("return", new Response(res == null ? void 0 : res.body, {
2725
- status: 302,
2726
- headers: res == null ? void 0 : res.headers
2727
- }));
2728
- case 10:
2729
- return _context.abrupt("return", new Response(res == null ? void 0 : res.body, {
2730
- status: res == null ? void 0 : res.status,
2731
- headers: res == null ? void 0 : res.headers
2732
- }));
2733
- case 11:
2734
- case "end":
2735
- return _context.stop();
2736
- }
2737
- }, _callee);
2738
- }));
2739
- return _route$2.apply(this, arguments);
2740
- }
2741
- function matches$2(configRoutes, request) {
2742
- return urlMatches(request.url, configRoutes.CALLBACK);
2743
- }
2744
-
2745
- var key$1 = 'SIGNOUT';
2746
- function route$1(_x) {
2747
- return _route$1.apply(this, arguments);
2748
- }
2749
- function _route$1() {
2750
- _route$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request$1) {
2751
- var url, init, _URL$pathname$split$r, provider, res;
2752
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2753
- while (1) switch (_context.prev = _context.next) {
2754
- case 0:
2755
- url = proxyRoutes[key$1];
2756
- init = {
2757
- method: request$1.method
2758
- };
2759
- if (request$1.method === 'POST') {
2760
- init.body = request$1.body;
2761
- _URL$pathname$split$r = new URL(request$1.url).pathname.split('/').reverse(), provider = _URL$pathname$split$r[0];
2762
- url = proxyRoutes[key$1] + "/" + provider;
2763
- }
2764
- _context.next = 5;
2765
- return request(url, _extends({}, init, {
2766
- request: request$1
2767
- }));
2768
- case 5:
2769
- res = _context.sent;
2770
- return _context.abrupt("return", res);
2771
- case 7:
2772
- case "end":
2773
- return _context.stop();
2774
- }
2775
- }, _callee);
2776
- }));
2777
- return _route$1.apply(this, arguments);
2778
- }
2779
- function matches$1(configRoutes, request) {
2780
- return urlMatches(request.url, configRoutes[key$1]);
2781
- }
2782
-
2783
- var key = 'ERROR';
2784
- function route(_x) {
2785
- return _route.apply(this, arguments);
2786
- }
2787
- function _route() {
2788
- _route = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2789
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2790
- while (1) switch (_context.prev = _context.next) {
2791
- case 0:
2792
- return _context.abrupt("return", request(proxyRoutes[key], {
2793
- method: req.method,
2794
- request: req
2795
- }));
2796
- case 1:
2797
- case "end":
2798
- return _context.stop();
2799
- }
2800
- }, _callee);
2801
- }));
2802
- return _route.apply(this, arguments);
2803
- }
2804
- function matches(configRoutes, request) {
2805
- return urlMatches(request.url, configRoutes[key]);
2806
- }
2807
-
2808
- function GETTER(configRoutes, config) {
2809
- return /*#__PURE__*/function () {
2810
- var _GET = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2811
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2812
- while (1) switch (_context.prev = _context.next) {
2813
- case 0:
2814
- if (!matches$a(configRoutes, req)) {
2815
- _context.next = 2;
2816
- break;
2817
- }
2818
- return _context.abrupt("return", route$a(req, config));
2819
- case 2:
2820
- if (!matches$9(configRoutes, req)) {
2821
- _context.next = 4;
2822
- break;
2823
- }
2824
- return _context.abrupt("return", route$9(req, config));
2825
- case 4:
2826
- if (!matches$8(configRoutes, req)) {
2827
- _context.next = 6;
2828
- break;
2829
- }
2830
- return _context.abrupt("return", route$8(req, config));
2831
- case 6:
2832
- if (!matches$7(configRoutes, req)) {
2833
- _context.next = 8;
2834
- break;
2835
- }
2836
- return _context.abrupt("return", route$7(req, config));
2837
- case 8:
2838
- if (!matches$5(configRoutes, req)) {
2839
- _context.next = 10;
2840
- break;
2841
- }
2842
- return _context.abrupt("return", route$5(req, config));
2843
- case 10:
2844
- if (!matches$6(configRoutes, req)) {
2845
- _context.next = 12;
2846
- break;
2847
- }
2848
- return _context.abrupt("return", route$6(req));
2849
- case 12:
2850
- if (!matches$4(configRoutes, req)) {
2851
- _context.next = 14;
2852
- break;
2853
- }
2854
- return _context.abrupt("return", route$4(req));
2855
- case 14:
2856
- if (!matches$3(configRoutes, req)) {
2857
- _context.next = 16;
2858
- break;
2859
- }
2860
- return _context.abrupt("return", route$3(req));
2861
- case 16:
2862
- if (!matches$2(configRoutes, req)) {
2863
- _context.next = 18;
2864
- break;
2865
- }
2866
- return _context.abrupt("return", route$2(req));
2867
- case 18:
2868
- if (!matches$1(configRoutes, req)) {
2869
- _context.next = 20;
2870
- break;
2871
- }
2872
- return _context.abrupt("return", route$1(req));
2873
- case 20:
2874
- if (!matches(configRoutes, req)) {
2875
- _context.next = 22;
2876
- break;
2877
- }
2878
- return _context.abrupt("return", route(req));
2879
- case 22:
2880
- return _context.abrupt("return", new Response(null, {
2881
- status: 404
2882
- }));
2883
- case 23:
2884
- case "end":
2885
- return _context.stop();
2886
- }
2887
- }, _callee);
2888
- }));
2889
- function GET(_x) {
2890
- return _GET.apply(this, arguments);
2891
- }
2892
- return GET;
2893
- }();
2894
- }
2895
-
2896
- function POSTER(configRoutes, config) {
2897
- return /*#__PURE__*/function () {
2898
- var _POST = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2899
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2900
- while (1) switch (_context.prev = _context.next) {
2901
- case 0:
2902
- if (!matches$8(configRoutes, req)) {
2903
- _context.next = 2;
2904
- break;
2905
- }
2906
- return _context.abrupt("return", route$8(req, config));
2907
- case 2:
2908
- if (!matches$9(configRoutes, req)) {
2909
- _context.next = 4;
2910
- break;
2911
- }
2912
- return _context.abrupt("return", route$9(req, config));
2913
- case 4:
2914
- if (!matches$7(configRoutes, req)) {
2915
- _context.next = 6;
2916
- break;
2917
- }
2918
- return _context.abrupt("return", route$7(req, config));
2919
- case 6:
2920
- if (!matches$5(configRoutes, req)) {
2921
- _context.next = 8;
2922
- break;
2923
- }
2924
- return _context.abrupt("return", route$5(req, config));
2925
- case 8:
2926
- if (!matches$6(configRoutes, req)) {
2927
- _context.next = 10;
2928
- break;
2929
- }
2930
- return _context.abrupt("return", route$6(req));
2931
- case 10:
2932
- if (!matches$4(configRoutes, req)) {
2933
- _context.next = 12;
2934
- break;
2935
- }
2936
- return _context.abrupt("return", route$4(req));
2937
- case 12:
2938
- if (!matches$3(configRoutes, req)) {
2939
- _context.next = 14;
2940
- break;
2941
- }
2942
- return _context.abrupt("return", route$3(req));
2943
- case 14:
2944
- if (!matches$2(configRoutes, req)) {
2945
- _context.next = 16;
2946
- break;
2947
- }
2948
- return _context.abrupt("return", route$2(req));
2949
- case 16:
2950
- if (!matches$1(configRoutes, req)) {
2951
- _context.next = 18;
2952
- break;
2953
- }
2954
- return _context.abrupt("return", route$1(req));
2955
- case 18:
2956
- return _context.abrupt("return", new Response(null, {
2957
- status: 404
2958
- }));
2959
- case 19:
2960
- case "end":
2961
- return _context.stop();
2962
- }
2963
- }, _callee);
2964
- }));
2965
- function POST(_x) {
2966
- return _POST.apply(this, arguments);
2967
- }
2968
- return POST;
2969
- }();
2970
- }
2971
-
2972
- function DELETER(configRoutes, config) {
2973
- return /*#__PURE__*/function () {
2974
- var _DELETE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2975
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2976
- while (1) switch (_context.prev = _context.next) {
2977
- case 0:
2978
- if (!matches$8(configRoutes, req)) {
2979
- _context.next = 2;
2980
- break;
2981
- }
2982
- return _context.abrupt("return", route$8(req, config));
2983
- case 2:
2984
- if (!matches$7(configRoutes, req)) {
2985
- _context.next = 4;
2986
- break;
2987
- }
2988
- return _context.abrupt("return", route$7(req, config));
2989
- case 4:
2990
- return _context.abrupt("return", new Response(null, {
2991
- status: 404
2992
- }));
2993
- case 5:
2994
- case "end":
2995
- return _context.stop();
2996
- }
2997
- }, _callee);
2998
- }));
2999
- function DELETE(_x) {
3000
- return _DELETE.apply(this, arguments);
3001
- }
3002
- return DELETE;
3003
- }();
3004
- }
3005
-
3006
- function PUTER(configRoutes, config) {
3007
- return /*#__PURE__*/function () {
3008
- var _PUT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3009
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3010
- while (1) switch (_context.prev = _context.next) {
3011
- case 0:
3012
- if (!matches$8(configRoutes, req)) {
3013
- _context.next = 2;
3014
- break;
3015
- }
3016
- return _context.abrupt("return", route$8(req, config));
3017
- case 2:
3018
- if (!matches$9(configRoutes, req)) {
3019
- _context.next = 4;
3020
- break;
3021
- }
3022
- return _context.abrupt("return", route$9(req, config));
3023
- case 4:
3024
- if (!matches$7(configRoutes, req)) {
3025
- _context.next = 6;
3026
- break;
3027
- }
3028
- return _context.abrupt("return", route$7(req, config));
3029
- case 6:
3030
- return _context.abrupt("return", new Response(null, {
3031
- status: 404
3032
- }));
3033
- case 7:
3034
- case "end":
3035
- return _context.stop();
3036
- }
3037
- }, _callee);
3038
- }));
3039
- function PUT(_x) {
3040
- return _PUT.apply(this, arguments);
3041
- }
3042
- return PUT;
3043
- }();
3044
- }
3045
-
3046
- function Handlers(configRoutes, config) {
3047
- var GET = GETTER(configRoutes, config);
3048
- var POST = POSTER(configRoutes, config);
3049
- var DELETE = DELETER(configRoutes, config);
3050
- var PUT = PUTER(configRoutes, config);
3051
- return {
3052
- GET: GET,
3053
- POST: POST,
3054
- DELETE: DELETE,
3055
- PUT: PUT
3056
- };
3057
- }
3058
-
3059
- var appRoutes = function appRoutes(prefix) {
3060
- if (prefix === void 0) {
3061
- prefix = '/api';
3062
- }
3063
- return {
3064
- SIGNIN: prefix + "/auth/signin",
3065
- PROVIDERS: prefix + "/auth/providers",
3066
- SESSION: prefix + "/auth/session",
3067
- CSRF: prefix + "/auth/csrf",
3068
- CALLBACK: prefix + "/auth/callback",
3069
- SIGNOUT: prefix + "/auth/signout",
3070
- ERROR: prefix + "/auth/error",
3071
- ME: prefix + "/me",
3072
- USERS: prefix + "/users",
3073
- TENANTS: prefix + "/tenants",
3074
- TENANT_USER: prefix + "/tenants/{tenantId}/users/{userId}",
3075
- TENANT_USERS: prefix + "/tenants/{tenantId}/users",
3076
- SIGNUP: prefix + "/signup"
3077
- };
3078
- };
3079
-
3080
- /**
3081
- * a helper function to log in server side.
3082
- */
3083
- function serverAuth(config, handlers) {
3084
- return /*#__PURE__*/function () {
3085
- var _login = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
3086
- var _yield$csrfRes$json, _exec;
3087
- var email, password, sessionUrl, sessionReq, sessionRes, providers, csrf, csrfReq, csrfRes, _ref2, csrfToken, credentials, csrfCookie, signInUrl, postReq, loginRes, authCookie, _ref3, token;
3088
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3089
- while (1) switch (_context.prev = _context.next) {
3090
- case 0:
3091
- email = _ref.email, password = _ref.password;
3092
- sessionUrl = new URL(config.api.localPath + "/api/auth/providers");
3093
- sessionReq = new Request(sessionUrl, {
3094
- method: 'GET',
3095
- headers: new Headers({
3096
- host: sessionUrl.host
3097
- })
3098
- });
3099
- _context.next = 5;
3100
- return handlers.POST(sessionReq);
3101
- case 5:
3102
- sessionRes = _context.sent;
3103
- _context.next = 8;
3104
- return sessionRes == null ? void 0 : sessionRes.json();
3105
- case 8:
3106
- providers = _context.sent;
3107
- csrf = new URL(config.api.localPath + "/api/auth/csrf");
3108
- csrfReq = new Request(csrf, {
3109
- method: 'GET',
3110
- headers: new Headers({
3111
- host: sessionUrl.host
3112
- })
3113
- });
3114
- _context.next = 13;
3115
- return handlers.POST(csrfReq);
3116
- case 13:
3117
- csrfRes = _context.sent;
3118
- _context.next = 16;
3119
- return csrfRes == null ? void 0 : csrfRes.json();
3120
- case 16:
3121
- _context.t0 = _yield$csrfRes$json = _context.sent;
3122
- if (!(_context.t0 != null)) {
3123
- _context.next = 21;
3124
- break;
3125
- }
3126
- _context.t1 = _yield$csrfRes$json;
3127
- _context.next = 22;
3128
- break;
3129
- case 21:
3130
- _context.t1 = {};
3131
- case 22:
3132
- _ref2 = _context.t1;
3133
- csrfToken = _ref2.csrfToken;
3134
- credentials = providers.credentials;
3135
- csrfCookie = csrfRes == null ? void 0 : csrfRes.headers.get('set-cookie');
3136
- expect(csrfCookie).toContain('nile.csrf-token=');
3137
- signInUrl = new URL(credentials.callbackUrl);
3138
- if (csrfCookie) {
3139
- _context.next = 30;
3140
- break;
3141
- }
3142
- throw new Error('unable to authenticate REST');
3143
- case 30:
3144
- postReq = new Request(signInUrl, {
3145
- method: 'POST',
3146
- headers: new Headers({
3147
- 'content-type': 'application/json',
3148
- cookie: csrfCookie
3149
- }),
3150
- body: JSON.stringify({
3151
- email: email,
3152
- password: password,
3153
- csrfToken: csrfToken,
3154
- callbackUrl: credentials.callbackUrl
3155
- })
3156
- });
3157
- _context.next = 33;
3158
- return handlers.POST(postReq);
3159
- case 33:
3160
- loginRes = _context.sent;
3161
- authCookie = loginRes == null ? void 0 : loginRes.headers.get('set-cookie');
3162
- if (authCookie) {
3163
- _context.next = 37;
3164
- break;
3165
- }
3166
- throw new Error('authentication failed');
3167
- case 37:
3168
- expect(authCookie).toContain('nile.session-token=');
3169
- _ref3 = (_exec = /(nile\.session-token=.+?);/.exec(authCookie)) != null ? _exec : [], token = _ref3[1];
3170
- return _context.abrupt("return", new Headers({
3171
- cookie: [token, csrfCookie].join('; ')
3172
- }));
3173
- case 40:
3174
- case "end":
3175
- return _context.stop();
3176
- }
3177
- }, _callee);
3178
- }));
3179
- function login(_x) {
3180
- return _login.apply(this, arguments);
3181
- }
3182
- return login;
3183
- }();
3184
- }
3185
-
3186
- var Requester = /*#__PURE__*/function (_Config) {
3187
- function Requester(config) {
3188
- return _Config.call(this, config) || this;
3189
- }
3190
- _inheritsLoose(Requester, _Config);
3191
- var _proto = Requester.prototype;
3192
- _proto.rawRequest = /*#__PURE__*/function () {
3193
- var _rawRequest = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(method, url, init, body) {
3194
- var _init, res;
3195
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3196
- while (1) switch (_context.prev = _context.next) {
3197
- case 0:
3198
- _init = _extends({}, init, {
3199
- body: body,
3200
- method: method
3201
- });
3202
- _context.next = 3;
3203
- return _fetch(this, url, _init);
3204
- case 3:
3205
- res = _context.sent;
3206
- if (!(res instanceof ResponseError)) {
3207
- _context.next = 6;
3208
- break;
3209
- }
3210
- return _context.abrupt("return", res.response);
3211
- case 6:
3212
- return _context.abrupt("return", res);
3213
- case 7:
3214
- case "end":
3215
- return _context.stop();
3216
- }
3217
- }, _callee, this);
3218
- }));
3219
- function rawRequest(_x, _x2, _x3, _x4) {
3220
- return _rawRequest.apply(this, arguments);
3221
- }
3222
- return rawRequest;
3223
- }()
3224
- /**
3225
- * three options here
3226
- * 1) pass in headers for a server side request
3227
- * 2) pass in the payload that matches the api
3228
- * 3) pass in the request object sent by a browser
3229
- * @param method
3230
- * @param url
3231
- * @param req
3232
- * @param init
3233
- * @returns
3234
- */
3235
- ;
3236
- _proto.request =
3237
- /*#__PURE__*/
3238
- function () {
3239
- var _request = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(method, url, req, init) {
3240
- var headers, tenantId, cookie, _headers, _tenantId, _cookie, body, _init;
3241
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3242
- while (1) switch (_context2.prev = _context2.next) {
3243
- case 0:
3244
- // set the headers
3245
- headers = new Headers(init ? init == null ? void 0 : init.headers : {});
3246
- if (req instanceof Headers) {
3247
- tenantId = req.get(X_NILE_TENANT);
3248
- cookie = req.get('cookie');
3249
- if (tenantId) {
3250
- headers.set(X_NILE_TENANT, tenantId);
3251
- }
3252
- if (cookie) {
3253
- headers.set('cookie', cookie);
3254
- }
3255
- } else if (req instanceof Request) {
3256
- // pass back the X_NILE_TENANT
3257
- _headers = new Headers(req == null ? void 0 : req.headers);
3258
- _tenantId = _headers.get(X_NILE_TENANT);
3259
- _cookie = _headers.get('cookie');
3260
- if (_tenantId) {
3261
- headers.set(X_NILE_TENANT, _tenantId);
3262
- }
3263
- if (_cookie) {
3264
- headers.set('cookie', _cookie);
3265
- }
3266
- }
3267
- // default the body - may be the actual payload for the API
3268
- body = JSON.stringify(req); // comes from next/some server
3269
- if (!(method === 'GET')) {
3270
- _context2.next = 7;
3271
- break;
3272
- }
3273
- body = undefined;
3274
- _context2.next = 14;
3275
- break;
3276
- case 7:
3277
- if (!(req instanceof Request)) {
3278
- _context2.next = 13;
3279
- break;
3280
- }
3281
- _context2.next = 10;
3282
- return new Response(req.body).text();
3283
- case 10:
3284
- body = _context2.sent;
3285
- _context2.next = 14;
3286
- break;
3287
- case 13:
3288
- if (
3289
- // is just headers for a GET request
3290
- req instanceof Headers || JSON.stringify(req) === '{}' || req && typeof req === 'object' && Object.values(req).length === 0) {
3291
- body = undefined;
3292
- }
3293
- case 14:
3294
- _init = _extends({}, init, {
3295
- headers: headers
3296
- });
3297
- _context2.next = 17;
3298
- return this.rawRequest(method, url, _init, body);
3299
- case 17:
3300
- return _context2.abrupt("return", _context2.sent);
3301
- case 18:
3302
- case "end":
3303
- return _context2.stop();
3304
- }
3305
- }, _callee2, this);
3306
- }));
3307
- function request(_x5, _x6, _x7, _x8) {
3308
- return _request.apply(this, arguments);
3309
- }
3310
- return request;
3311
- }();
3312
- _proto.post = /*#__PURE__*/function () {
3313
- var _post = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, url, init) {
3314
- var response;
3315
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3316
- while (1) switch (_context3.prev = _context3.next) {
3317
- case 0:
3318
- _context3.next = 2;
3319
- return this.request('POST', url, req, init);
3320
- case 2:
3321
- response = _context3.sent;
3322
- if (!(response && response.status >= 200 && response.status < 300)) {
3323
- _context3.next = 5;
3324
- break;
3325
- }
3326
- return _context3.abrupt("return", response.json());
3327
- case 5:
3328
- return _context3.abrupt("return", response);
3329
- case 6:
3330
- case "end":
3331
- return _context3.stop();
3332
- }
3333
- }, _callee3, this);
3334
- }));
3335
- function post(_x9, _x10, _x11) {
3336
- return _post.apply(this, arguments);
3337
- }
3338
- return post;
3339
- }();
3340
- _proto.get = /*#__PURE__*/function () {
3341
- var _get = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, url, init) {
3342
- var response;
3343
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
3344
- while (1) switch (_context4.prev = _context4.next) {
3345
- case 0:
3346
- _context4.next = 2;
3347
- return this.request('GET', url, req, init);
3348
- case 2:
3349
- response = _context4.sent;
3350
- if (!(response && response.status >= 200 && response.status < 300)) {
3351
- _context4.next = 5;
3352
- break;
3353
- }
3354
- return _context4.abrupt("return", response.json());
3355
- case 5:
3356
- return _context4.abrupt("return", response);
3357
- case 6:
3358
- case "end":
3359
- return _context4.stop();
3360
- }
3361
- }, _callee4, this);
3362
- }));
3363
- function get(_x12, _x13, _x14) {
3364
- return _get.apply(this, arguments);
3365
- }
3366
- return get;
3367
- }();
3368
- _proto.put = /*#__PURE__*/function () {
3369
- var _put = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req, url, init) {
3370
- var response;
3371
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
3372
- while (1) switch (_context5.prev = _context5.next) {
3373
- case 0:
3374
- _context5.next = 2;
3375
- return this.request('PUT', url, req, init);
3376
- case 2:
3377
- response = _context5.sent;
3378
- if (!(response && response.status >= 200 && response.status < 300)) {
3379
- _context5.next = 5;
3380
- break;
3381
- }
3382
- return _context5.abrupt("return", response.json());
3383
- case 5:
3384
- return _context5.abrupt("return", response);
3385
- case 6:
3386
- case "end":
3387
- return _context5.stop();
3388
- }
3389
- }, _callee5, this);
3390
- }));
3391
- function put(_x15, _x16, _x17) {
3392
- return _put.apply(this, arguments);
3393
- }
3394
- return put;
3395
- }();
3396
- _proto["delete"] = /*#__PURE__*/function () {
3397
- var _delete2 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(req, url, init) {
3398
- var response;
3399
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
3400
- while (1) switch (_context6.prev = _context6.next) {
3401
- case 0:
3402
- _context6.next = 2;
3403
- return this.request('DELETE', url, req, init);
3404
- case 2:
3405
- response = _context6.sent;
3406
- if (!(response && response.status >= 200 && response.status < 300)) {
3407
- _context6.next = 5;
3408
- break;
3409
- }
3410
- return _context6.abrupt("return", response.json());
3411
- case 5:
3412
- return _context6.abrupt("return", response);
3413
- case 6:
3414
- case "end":
3415
- return _context6.stop();
3416
- }
3417
- }, _callee6, this);
3418
- }));
3419
- function _delete(_x18, _x19, _x20) {
3420
- return _delete2.apply(this, arguments);
3421
- }
3422
- return _delete;
3423
- }();
3424
- return Requester;
3425
- }(Config);
3426
-
3427
- var Tenants = /*#__PURE__*/function (_Config) {
3428
- function Tenants(config, headers) {
3429
- var _this;
3430
- _this = _Config.call(this, config) || this;
3431
- _this.headers = void 0;
3432
- _this.createTenant = /*#__PURE__*/function () {
3433
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
3434
- var _req, _requester, _init;
3435
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3436
- while (1) switch (_context.prev = _context.next) {
3437
- case 0:
3438
- if (typeof req === 'string') {
3439
- _req = new Request("" + _this.api.basePath + _this.tenantsUrl, {
3440
- body: JSON.stringify({
3441
- name: req
3442
- }),
3443
- method: 'POST'
3444
- });
3445
- } else {
3446
- _req = req;
3447
- }
3448
- _requester = new Requester(_this);
3449
- _init = _this.handleHeaders(init);
3450
- return _context.abrupt("return", _requester.post(_req, _this.tenantsUrl, _init));
3451
- case 4:
3452
- case "end":
3453
- return _context.stop();
3454
- }
3455
- }, _callee);
3456
- }));
3457
- return function (_x, _x2) {
3458
- return _ref.apply(this, arguments);
3459
- };
3460
- }();
3461
- _this.getTenant = /*#__PURE__*/function () {
3462
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req, init) {
3463
- var _requester, _init;
3464
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3465
- while (1) switch (_context2.prev = _context2.next) {
3466
- case 0:
3467
- if (typeof req === 'string') {
3468
- _this.tenantId = req;
3469
- }
3470
- _requester = new Requester(_this);
3471
- _init = _this.handleHeaders(init);
3472
- return _context2.abrupt("return", _requester.get(req, _this.tenantUrl, _init));
3473
- case 4:
3474
- case "end":
3475
- return _context2.stop();
3476
- }
3477
- }, _callee2);
3478
- }));
3479
- return function (_x3, _x4) {
3480
- return _ref2.apply(this, arguments);
3481
- };
3482
- }();
3483
- _this.listTenants = /*#__PURE__*/function () {
3484
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
3485
- var _requester, _init;
3486
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3487
- while (1) switch (_context3.prev = _context3.next) {
3488
- case 0:
3489
- _requester = new Requester(_this);
3490
- _init = _this.handleHeaders(init);
3491
- return _context3.abrupt("return", _requester.get(req, _this.tenantListUrl, _init));
3492
- case 3:
3493
- case "end":
3494
- return _context3.stop();
3495
- }
3496
- }, _callee3);
3497
- }));
3498
- return function (_x5, _x6) {
3499
- return _ref3.apply(this, arguments);
3500
- };
3501
- }();
3502
- _this.headers = headers;
3503
- return _this;
3504
- }
3505
- _inheritsLoose(Tenants, _Config);
3506
- var _proto = Tenants.prototype;
3507
- _proto.handleHeaders = function handleHeaders(init) {
3508
- if (this.headers) {
3509
- if (init) {
3510
- var _init2;
3511
- init.headers = new Headers(_extends({}, this.headers, (_init2 = init) == null ? void 0 : _init2.headers));
3512
- return init;
3513
- } else {
3514
- init = {
3515
- headers: this.headers
3516
- };
3517
- return init;
3518
- }
3519
- }
3520
- return undefined;
3521
- };
3522
- return _createClass(Tenants, [{
3523
- key: "tenantsUrl",
3524
- get: function get() {
3525
- return '/tenants';
3526
- }
3527
- }, {
3528
- key: "tenantUrl",
3529
- get: function get() {
3530
- var _this$tenantId;
3531
- return "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}');
3532
- }
3533
- }, {
3534
- key: "tenantListUrl",
3535
- get: function get() {
3536
- var _this$userId;
3537
- return "/users/" + ((_this$userId = this.userId) != null ? _this$userId : '{userId}') + "/tenants";
3538
- }
3539
- }]);
3540
- }(Config);
3541
-
3542
- var Users = /*#__PURE__*/function (_Config) {
3543
- function Users(config, headers) {
3544
- var _this;
3545
- _this = _Config.call(this, config) || this;
3546
- _this.headers = void 0;
3547
- _this.createUser = /*#__PURE__*/function () {
3548
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
3549
- var _requester, _init;
3550
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3551
- while (1) switch (_context.prev = _context.next) {
3552
- case 0:
3553
- _requester = new Requester(_this);
3554
- _init = _this.handleHeaders(init);
3555
- _context.next = 4;
3556
- return _requester.post(req, _this.usersUrl, _init);
3557
- case 4:
3558
- return _context.abrupt("return", _context.sent);
3559
- case 5:
3560
- case "end":
3561
- return _context.stop();
3562
- }
3563
- }, _callee);
3564
- }));
3565
- return function (_x, _x2) {
3566
- return _ref.apply(this, arguments);
3567
- };
3568
- }();
3569
- _this.updateUser = /*#__PURE__*/function () {
3570
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(userId, req, init) {
3571
- var _requester, _init;
3572
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3573
- while (1) switch (_context2.prev = _context2.next) {
3574
- case 0:
3575
- _requester = new Requester(_this);
3576
- _init = _this.handleHeaders(init);
3577
- _context2.next = 4;
3578
- return _requester.put(req, _this.usersUrl + "/" + userId, _init);
3579
- case 4:
3580
- return _context2.abrupt("return", _context2.sent);
3581
- case 5:
3582
- case "end":
3583
- return _context2.stop();
3584
- }
3585
- }, _callee2);
3586
- }));
3587
- return function (_x3, _x4, _x5) {
3588
- return _ref2.apply(this, arguments);
3589
- };
3590
- }();
3591
- _this.listUsers = /*#__PURE__*/function () {
3592
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
3593
- var _requester, _init;
3594
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3595
- while (1) switch (_context3.prev = _context3.next) {
3596
- case 0:
3597
- _requester = new Requester(_this);
3598
- _init = _this.handleHeaders(init);
3599
- _context3.next = 4;
3600
- return _requester.get(req, _this.tenantUsersUrl, _init);
3601
- case 4:
3602
- return _context3.abrupt("return", _context3.sent);
3603
- case 5:
3604
- case "end":
3605
- return _context3.stop();
3606
- }
3607
- }, _callee3);
3608
- }));
3609
- return function (_x6, _x7) {
3610
- return _ref3.apply(this, arguments);
3611
- };
3612
- }();
3613
- _this.linkUser = /*#__PURE__*/function () {
3614
- var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, init) {
3615
- var _requester, _init;
3616
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
3617
- while (1) switch (_context4.prev = _context4.next) {
3618
- case 0:
3619
- _requester = new Requester(_this);
3620
- _init = _this.handleHeaders(init);
3621
- _context4.next = 4;
3622
- return _requester.put(req, _this.tenantUsersUrl, _init);
3623
- case 4:
3624
- return _context4.abrupt("return", _context4.sent);
3625
- case 5:
3626
- case "end":
3627
- return _context4.stop();
3628
- }
3629
- }, _callee4);
3630
- }));
3631
- return function (_x8, _x9) {
3632
- return _ref4.apply(this, arguments);
3633
- };
3634
- }();
3635
- _this.tenantUsersDeleteUrl = function (userId) {
3636
- var _this$tenantId;
3637
- return "/tenants/" + ((_this$tenantId = _this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/users/" + (userId != null ? userId : '{userId}');
3638
- };
3639
- _this.getUserId = /*#__PURE__*/function () {
3640
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req) {
3641
- var body;
3642
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
3643
- while (1) switch (_context5.prev = _context5.next) {
3644
- case 0:
3645
- if (!(req instanceof Request)) {
3646
- _context5.next = 6;
3647
- break;
3648
- }
3649
- _context5.next = 3;
3650
- return new Response(req == null ? void 0 : req.body).json();
3651
- case 3:
3652
- body = _context5.sent;
3653
- if (!body) {
3654
- _context5.next = 6;
3655
- break;
3656
- }
3657
- return _context5.abrupt("return", body.id);
3658
- case 6:
3659
- if (!('id' in req)) {
3660
- _context5.next = 8;
3661
- break;
3662
- }
3663
- return _context5.abrupt("return", req.id);
3664
- case 8:
3665
- return _context5.abrupt("return", null);
3666
- case 9:
3667
- case "end":
3668
- return _context5.stop();
3669
- }
3670
- }, _callee5);
3671
- }));
3672
- return function (_x10) {
3673
- return _ref5.apply(this, arguments);
3674
- };
3675
- }();
3676
- _this.unlinkUser = /*#__PURE__*/function () {
3677
- var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(req, init) {
3678
- var _requester, userId, _init;
3679
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
3680
- while (1) switch (_context6.prev = _context6.next) {
3681
- case 0:
3682
- _requester = new Requester(_this);
3683
- _context6.next = 3;
3684
- return _this.getUserId(req);
3685
- case 3:
3686
- userId = _context6.sent;
3687
- _init = _this.handleHeaders(init);
3688
- _context6.next = 7;
3689
- return _requester["delete"](req, _this.tenantUsersDeleteUrl(userId), _init);
3690
- case 7:
3691
- return _context6.abrupt("return", _context6.sent);
3692
- case 8:
3693
- case "end":
3694
- return _context6.stop();
3695
- }
3696
- }, _callee6);
3697
- }));
3698
- return function (_x11, _x12) {
3699
- return _ref6.apply(this, arguments);
3700
- };
3701
- }();
3702
- _this.me = /*#__PURE__*/function () {
3703
- var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(req, init) {
3704
- var _requester, _init;
3705
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
3706
- while (1) switch (_context7.prev = _context7.next) {
3707
- case 0:
3708
- _requester = new Requester(_this);
3709
- _init = _this.handleHeaders(init);
3710
- _context7.next = 4;
3711
- return _requester.get(req, _this.meUrl, _init);
3712
- case 4:
3713
- return _context7.abrupt("return", _context7.sent);
3714
- case 5:
3715
- case "end":
3716
- return _context7.stop();
3717
- }
3718
- }, _callee7);
3719
- }));
3720
- return function (_x13, _x14) {
3721
- return _ref7.apply(this, arguments);
3722
- };
3723
- }();
3724
- _this.headers = headers;
3725
- return _this;
3726
- }
3727
- _inheritsLoose(Users, _Config);
3728
- var _proto = Users.prototype;
3729
- _proto.handleHeaders = function handleHeaders(init) {
3730
- if (this.headers) {
3731
- if (init) {
3732
- var _init2;
3733
- init.headers = new Headers(_extends({}, this.headers, (_init2 = init) == null ? void 0 : _init2.headers));
3734
- return init;
3735
- } else {
3736
- init = {
3737
- headers: this.headers
3738
- };
3739
- return init;
3740
- }
3741
- }
3742
- return undefined;
3743
- };
3744
- return _createClass(Users, [{
3745
- key: "usersUrl",
3746
- get: function get() {
3747
- return '/users';
3748
- }
3749
- }, {
3750
- key: "tenantUsersUrl",
3751
- get: function get() {
3752
- var _this$tenantId2;
3753
- return "/tenants/" + ((_this$tenantId2 = this.tenantId) != null ? _this$tenantId2 : '{tenantId}') + "/users";
3754
- }
3755
- }, {
3756
- key: "meUrl",
3757
- get: function get() {
3758
- return '/me';
3759
- }
3760
- }]);
3761
- }(Config);
3762
-
3763
- var Api = /*#__PURE__*/function () {
3764
- function Api(config) {
3765
- this.config = void 0;
3766
- this.users = void 0;
3767
- this.tenants = void 0;
3768
- this.routes = void 0;
3769
- this.handlers = void 0;
3770
- this.config = config;
3771
- this.users = new Users(config);
3772
- this.tenants = new Tenants(config);
3773
- this.routes = _extends({}, appRoutes(config == null ? void 0 : config.routePrefix), config == null ? void 0 : config.routes);
3774
- this.handlers = Handlers(this.routes, config);
3775
- }
3776
- var _proto = Api.prototype;
3777
- _proto.login = /*#__PURE__*/function () {
3778
- var _login = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(payload) {
3779
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3780
- while (1) switch (_context.prev = _context.next) {
3781
- case 0:
3782
- _context.next = 2;
3783
- return serverAuth(this.config, this.handlers)(payload);
3784
- case 2:
3785
- this.headers = _context.sent;
3786
- case 3:
3787
- case "end":
3788
- return _context.stop();
3789
- }
3790
- }, _callee, this);
3791
- }));
3792
- function login(_x) {
3793
- return _login.apply(this, arguments);
3794
- }
3795
- return login;
3796
- }();
3797
- return _createClass(Api, [{
3798
- key: "headers",
3799
- set: function set(headers) {
3800
- this.users = new Users(this.config, headers);
3801
- this.tenants = new Tenants(this.config, headers);
3802
- }
3803
- }]);
3804
- }();
3805
-
3806
- var Server = /*#__PURE__*/function () {
3807
- function Server(config) {
3808
- var _this = this;
3809
- this.config = void 0;
3810
- this.api = void 0;
3811
- this.manager = void 0;
3812
- this.servers = void 0;
3813
- this.config = new Config(config, '[initial config]');
3814
- this.servers = new Map();
3815
- this.api = new Api(this.config);
3816
- this.manager = new DBManager(this.config);
3817
- watchTenantId(function (tenantId) {
3818
- _this.tenantId = tenantId;
3819
- });
3820
- watchUserId(function (userId) {
3821
- _this.userId = userId;
3822
- });
3823
- watchToken(function (token) {
3824
- _this.token = token;
3825
- });
3826
- }
3827
- var _proto = Server.prototype;
3828
- _proto.setConfig = function setConfig(cfg) {
3829
- this.config = new Config(cfg);
3830
- };
3831
- _proto.init = /*#__PURE__*/function () {
3832
- var _init = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(cfg) {
3833
- var updatedConfig;
3834
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3835
- while (1) switch (_context.prev = _context.next) {
3836
- case 0:
3837
- _context.next = 2;
3838
- return this.config.configure(_extends({}, this.config, cfg));
3839
- case 2:
3840
- updatedConfig = _context.sent;
3841
- this.setConfig(updatedConfig);
3842
- this.manager.clear(this.config);
3843
- this.manager = new DBManager(this.config);
3844
- this.api = new Api(this.config);
3845
- return _context.abrupt("return", this);
3846
- case 8:
3847
- case "end":
3848
- return _context.stop();
3849
- }
3850
- }, _callee, this);
3851
- }));
3852
- function init(_x) {
3853
- return _init.apply(this, arguments);
3854
- }
3855
- return init;
3856
- }();
3857
- /**
3858
- * A utility function if you want to manage different NileDB instances yourself
3859
- * returns the global Server object, an existing server that's already been configured,
3860
- * or a new one if the config isn't in the cache
3861
- */
3862
- _proto.getInstance = function getInstance(config) {
3863
- var _config = _extends({}, this.config, config);
3864
- var serverId = getServerId(_config);
3865
- var currentServerId = makeServerId(this.config);
3866
- if (serverId === currentServerId) {
3867
- return this;
3868
- }
3869
- var existing = this.servers.get(serverId);
3870
- if (existing) {
3871
- // be sure the config is up to date
3872
- var updatedConfig = new Config(_config);
3873
- existing.setConfig(updatedConfig);
3874
- // propagate special config items
3875
- existing.tenantId = updatedConfig.tenantId;
3876
- existing.userId = updatedConfig.userId;
3877
- existing.token = updatedConfig.api.token;
3878
- existing.databaseId = updatedConfig.databaseId;
3879
- return existing;
3880
- }
3881
- var newServer = new Server(_config);
3882
- this.servers.set(serverId, newServer);
3883
- return newServer;
3884
- };
3885
- return _createClass(Server, [{
3886
- key: "databaseId",
3887
- set: function set(val) {
3888
- if (val) {
3889
- this.config.databaseId = val;
3890
- this.api.users.databaseId = val;
3891
- this.api.tenants.databaseId = val;
3892
- }
3893
- }
3894
- }, {
3895
- key: "userId",
3896
- get: function get() {
3897
- return this.config.userId;
3898
- },
3899
- set: function set(userId) {
3900
- this.databaseId = this.config.databaseId;
3901
- this.config.userId = userId;
3902
- if (this.api) {
3903
- this.api.users.userId = this.config.userId;
3904
- this.api.tenants.userId = this.config.userId;
3905
- }
3906
- }
3907
- }, {
3908
- key: "tenantId",
3909
- get: function get() {
3910
- return this.config.tenantId;
3911
- },
3912
- set: function set(tenantId) {
3913
- this.databaseId = this.config.databaseId;
3914
- this.config.tenantId = tenantId;
3915
- if (this.api) {
3916
- this.api.users.tenantId = tenantId;
3917
- this.api.tenants.tenantId = tenantId;
3918
- }
3919
- }
3920
- }, {
3921
- key: "token",
3922
- get: function get() {
3923
- var _this$config;
3924
- return (_this$config = this.config) == null || (_this$config = _this$config.api) == null ? void 0 : _this$config.token;
3925
- },
3926
- set: function set(token) {
3927
- if (token) {
3928
- this.config.api.token = token;
3929
- if (this.api) {
3930
- this.api.users.api.token = token;
3931
- this.api.tenants.api.token = token;
3932
- }
3933
- }
3934
- }
3935
- }, {
3936
- key: "db",
3937
- get: function get() {
3938
- return this.manager.getConnection(this.config);
3939
- }
3940
- }]);
3941
- }();
3942
- function create(_x2) {
3943
- return _create.apply(this, arguments);
3944
- }
3945
- function _create() {
3946
- _create = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(config) {
3947
- var server;
3948
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3949
- while (1) switch (_context2.prev = _context2.next) {
3950
- case 0:
3951
- server = new Server(config);
3952
- _context2.next = 3;
3953
- return server.init();
3954
- case 3:
3955
- return _context2.abrupt("return", _context2.sent);
3956
- case 4:
3957
- case "end":
3958
- return _context2.stop();
3959
- }
3960
- }, _callee2);
3961
- }));
3962
- return _create.apply(this, arguments);
3963
- }
3964
-
3965
- export { create as Nile, Server, create as default };
3966
- //# sourceMappingURL=server.esm.js.map