@niledatabase/server 5.0.0-alpha.2 → 5.0.0-alpha.20

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.
package/dist/index.js CHANGED
@@ -8,6 +8,12 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
8
  var pg__default = /*#__PURE__*/_interopDefault(pg);
9
9
 
10
10
  // src/types.ts
11
+ var ExtensionState = /* @__PURE__ */ ((ExtensionState2) => {
12
+ ExtensionState2["onHandleRequest"] = "onHandleRequest";
13
+ ExtensionState2["onRequest"] = "onRequest";
14
+ ExtensionState2["onResponse"] = "onResponse";
15
+ return ExtensionState2;
16
+ })(ExtensionState || {});
11
17
  var APIErrorErrorCodeEnum = {
12
18
  InternalError: "internal_error",
13
19
  BadRequest: "bad_request",
@@ -31,6 +37,12 @@ var LoginUserResponseTokenTypeEnum = {
31
37
  IdToken: "ID_TOKEN"
32
38
  };
33
39
 
40
+ // src/utils/constants.ts
41
+ var TENANT_COOKIE = "nile.tenant-id";
42
+ var USER_COOKIE = "nile.user-id";
43
+ var HEADER_ORIGIN = "nile-origin";
44
+ var HEADER_SECURE_COOKIES = "nile-secure-cookies";
45
+
34
46
  // src/api/utils/routes/index.ts
35
47
  var NILEDB_API_URL = process.env.NILEDB_API_URL;
36
48
  var DEFAULT_PREFIX = "/api";
@@ -53,6 +65,8 @@ var appRoutes = (prefix = DEFAULT_PREFIX) => ({
53
65
  TENANT_USER: `${prefix}${"/tenants/{tenantId}/users/{userId}" /* TENANT_USER */}`,
54
66
  TENANT_USERS: `${prefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */}`,
55
67
  SIGNUP: `${prefix}${"/signup" /* SIGNUP */}`,
68
+ INVITES: `${prefix}${"/tenants/{tenantId}/invites" /* INVITES */}`,
69
+ INVITE: `${prefix}${"/tenants/{tenantId}/invite" /* INVITE */}`,
56
70
  LOG: `${prefix}/_log`
57
71
  });
58
72
  var apiRoutes = (config) => ({
@@ -63,6 +77,8 @@ var apiRoutes = (config) => ({
63
77
  TENANT: (tenantId) => makeRestUrl(config, `/tenants/${tenantId}`),
64
78
  SIGNUP: makeRestUrl(config, "/signup"),
65
79
  TENANT_USERS: (tenantId) => makeRestUrl(config, `/tenants/${tenantId}/users`),
80
+ INVITES: (tenantId) => makeRestUrl(config, `/tenants/${tenantId}/invites`),
81
+ INVITE: (tenantId) => makeRestUrl(config, `/tenants/${tenantId}/invite`),
66
82
  TENANT_USER: makeRestUrl(
67
83
  config,
68
84
  `/tenants/${config.tenantId}/users/${config.userId}`
@@ -104,9 +120,9 @@ function makeRestUrl(config, path, qp) {
104
120
  const strParams = params.toString();
105
121
  return `${[url, path.substring(1, path.length)].join("/")}${strParams ? `?${strParams}` : ""}`;
106
122
  }
107
- function urlMatches(requestUrl, route17) {
123
+ function urlMatches(requestUrl, route20) {
108
124
  const url = new URL(requestUrl);
109
- return url.pathname.startsWith(route17);
125
+ return url.pathname.startsWith(route20);
110
126
  }
111
127
  function isUUID(value) {
112
128
  if (!value) {
@@ -116,90 +132,26 @@ function isUUID(value) {
116
132
  return regex.test(value);
117
133
  }
118
134
 
119
- // src/utils/Logger.ts
120
- var red = "\x1B[31m";
121
- var yellow = "\x1B[38;2;255;255;0m";
122
- var purple = "\x1B[38;2;200;160;255m";
123
- var orange = "\x1B[38;2;255;165;0m";
124
- var reset = "\x1B[0m";
125
- var baseLogger = (config, ...params) => ({
126
- info(message, meta) {
127
- if (config?.debug) {
128
- console.info(
129
- `${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
130
- ""
131
- )}${reset} ${message}`,
132
- meta ? `${JSON.stringify(meta)}` : ""
133
- );
134
- }
135
- },
136
- debug(message, meta) {
137
- if (config?.debug) {
138
- console.debug(
139
- `${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
140
- ""
141
- )}${reset} ${message}`,
142
- meta ? `${JSON.stringify(meta)}` : ""
143
- );
144
- }
145
- },
146
- warn(message, meta) {
147
- if (config?.debug) {
148
- console.warn(
149
- `${orange}[niledb]${reset}${yellow}[WARN]${reset}${params.join(
150
- ""
151
- )}${reset} ${message}`,
152
- meta ? JSON.stringify(meta) : ""
153
- );
154
- }
155
- },
156
- error(message, meta) {
157
- console.error(
158
- `${orange}[niledb]${reset}${red}[ERROR]${reset}${params.join(
159
- ""
160
- )}${red} ${message}`,
161
- meta ? meta : "",
162
- `${reset}`
163
- );
164
- }
165
- });
166
- function Logger(config, ...params) {
167
- const base = baseLogger(config, params);
168
- const info = config?.logger?.info ?? base.info;
169
- const debug = config?.logger?.debug ?? base.debug;
170
- const warn = config?.logger?.warn ?? base.warn;
171
- const error = config?.logger?.error ?? base.error;
172
- return { info, warn, error, debug };
173
- }
174
- function matchesLog(configRoutes, request2) {
175
- return urlMatches(request2.url, configRoutes.LOG);
176
- }
177
-
178
- // src/utils/constants.ts
179
- var X_NILE_TENANT = "nile-tenant-id";
180
- var X_NILE_ORIGIN = "nile-origin";
181
- var X_NILE_SECURECOOKIES = "nile-secure-cookies";
182
-
183
135
  // src/api/utils/request.ts
184
136
  async function request(url, _init, config) {
185
- const { debug, info, error } = Logger(config, "[REQUEST]");
137
+ const { debug, info, error } = config.logger("[REQUEST]");
186
138
  const { request: request2, ...init } = _init;
187
139
  const requestUrl = new URL(request2.url);
188
140
  const updatedHeaders = new Headers({});
189
141
  if (request2.headers.get("cookie")) {
190
142
  updatedHeaders.set("cookie", String(request2.headers.get("cookie")));
191
143
  }
192
- if (request2.headers.get(X_NILE_TENANT)) {
144
+ if (request2.headers.get(TENANT_COOKIE)) {
193
145
  updatedHeaders.set(
194
- X_NILE_TENANT,
195
- String(request2.headers.get(X_NILE_TENANT))
146
+ TENANT_COOKIE,
147
+ String(request2.headers.get(TENANT_COOKIE))
196
148
  );
197
149
  }
198
150
  if (config.secureCookies != null) {
199
- updatedHeaders.set(X_NILE_SECURECOOKIES, String(config.secureCookies));
151
+ updatedHeaders.set(HEADER_SECURE_COOKIES, String(config.secureCookies));
200
152
  } else {
201
153
  updatedHeaders.set(
202
- X_NILE_SECURECOOKIES,
154
+ HEADER_SECURE_COOKIES,
203
155
  process.env.NODE_ENV === "production" ? "true" : "false"
204
156
  );
205
157
  }
@@ -207,17 +159,17 @@ async function request(url, _init, config) {
207
159
  if (config.callbackUrl) {
208
160
  const cbUrl = new URL(config.callbackUrl);
209
161
  debug(`Obtained origin from config.callbackUrl ${config.callbackUrl}`);
210
- updatedHeaders.set(X_NILE_ORIGIN, cbUrl.origin);
162
+ updatedHeaders.set(HEADER_ORIGIN, cbUrl.origin);
211
163
  } else if (config.origin) {
212
164
  debug(`Obtained origin from config.origin ${config.origin}`);
213
- updatedHeaders.set(X_NILE_ORIGIN, config.origin);
165
+ updatedHeaders.set(HEADER_ORIGIN, config.origin);
214
166
  } else {
215
- const passedOrigin = request2.headers.get(X_NILE_ORIGIN);
167
+ const passedOrigin = request2.headers.get(HEADER_ORIGIN);
216
168
  if (passedOrigin) {
217
- updatedHeaders.set(X_NILE_ORIGIN, passedOrigin);
169
+ updatedHeaders.set(HEADER_ORIGIN, passedOrigin);
218
170
  } else {
219
171
  const reqOrigin = config.routePrefix !== DEFAULT_PREFIX ? `${requestUrl.origin}${config.routePrefix}` : requestUrl.origin;
220
- updatedHeaders.set(X_NILE_ORIGIN, reqOrigin);
172
+ updatedHeaders.set(HEADER_ORIGIN, reqOrigin);
221
173
  debug(`Obtained origin from request ${reqOrigin}`);
222
174
  }
223
175
  }
@@ -225,14 +177,16 @@ async function request(url, _init, config) {
225
177
  if (params.method?.toLowerCase() === "post" || params.method?.toLowerCase() === "put") {
226
178
  try {
227
179
  updatedHeaders.set("content-type", "application/json");
228
- const initBody = await new Response(_init.request.clone().body).json();
229
- const requestBody = await new Response(request2.clone().body).json();
230
- params.body = JSON.stringify(initBody ?? requestBody);
180
+ const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
181
+ const bodyText = await new Response(bodyStream).text();
182
+ try {
183
+ params.body = JSON.stringify(JSON.parse(bodyText));
184
+ } catch {
185
+ updatedHeaders.set("content-type", "application/x-www-form-urlencoded");
186
+ params.body = bodyText;
187
+ }
231
188
  } catch (e) {
232
- updatedHeaders.set("content-type", "application/x-www-form-urlencoded");
233
- const initBody = await new Response(_init.request.clone().body).text();
234
- const requestBody = await new Response(request2.clone().body).text();
235
- params.body = initBody ?? requestBody;
189
+ error("Failed to parse request body");
236
190
  }
237
191
  }
238
192
  params.headers = updatedHeaders;
@@ -241,6 +195,12 @@ async function request(url, _init, config) {
241
195
  params.headers.set("request-id", crypto.randomUUID());
242
196
  params.cache = "no-store";
243
197
  }
198
+ await config.extensionCtx?.runExtensions(
199
+ "onRequest" /* onRequest */,
200
+ config,
201
+ params,
202
+ _init
203
+ );
244
204
  try {
245
205
  const res = await fetch(fullUrl, {
246
206
  ...params
@@ -260,6 +220,14 @@ async function request(url, _init, config) {
260
220
  statusText: res?.statusText,
261
221
  text: await loggingRes?.text()
262
222
  });
223
+ const updatedRes = await config.extensionCtx?.runExtensions(
224
+ "onResponse" /* onResponse */,
225
+ config,
226
+ params
227
+ );
228
+ if (updatedRes) {
229
+ return updatedRes;
230
+ }
263
231
  return res;
264
232
  } catch (e) {
265
233
  if (e instanceof Error) {
@@ -277,22 +245,19 @@ async function request(url, _init, config) {
277
245
 
278
246
  // src/api/utils/auth.ts
279
247
  async function auth(req, config) {
280
- const { info, error } = Logger(config, "[nileauth]");
248
+ const { info, error } = config.logger("[nileauth]");
281
249
  info("checking auth");
282
250
  const sessionUrl = `${config.apiUrl}/auth/session`;
283
251
  info(`using session ${sessionUrl}`);
284
252
  req.headers.delete("content-length");
285
253
  const res = await request(sessionUrl, { request: req }, config);
286
- if (!res) {
287
- info("no session found");
288
- return void 0;
289
- }
290
- info("session active");
291
254
  try {
292
255
  const session = await new Response(res.body).json();
293
256
  if (Object.keys(session).length === 0) {
257
+ info("no session found");
294
258
  return void 0;
295
259
  }
260
+ info("session active");
296
261
  return session;
297
262
  } catch (e) {
298
263
  error(e);
@@ -378,8 +343,8 @@ function getTokenFromCookie(headers, cookieKey) {
378
343
  }
379
344
  }
380
345
  function getTenantFromHttp(headers, config) {
381
- const cookieTenant = getTokenFromCookie(headers, X_NILE_TENANT);
382
- return cookieTenant ?? headers?.get(X_NILE_TENANT) ?? config?.tenantId;
346
+ const cookieTenant = getTokenFromCookie(headers, TENANT_COOKIE);
347
+ return cookieTenant ? cookieTenant : config?.tenantId;
383
348
  }
384
349
 
385
350
  // src/api/routes/users/POST.ts
@@ -389,7 +354,7 @@ async function POST(config, init) {
389
354
  const yurl = new URL(init.request.url);
390
355
  const tenantId = yurl.searchParams.get("tenantId");
391
356
  const newTenantName = yurl.searchParams.get("newTenantName");
392
- const tenant = tenantId ?? getTenantFromHttp(init.request.headers);
357
+ const tenant = tenantId ?? getTenantFromHttp(init.request.headers, config);
393
358
  const url = apiRoutes(config).USERS({ tenantId: tenant, newTenantName });
394
359
  return await request(url, init, config);
395
360
  }
@@ -398,21 +363,18 @@ async function POST(config, init) {
398
363
  async function GET2(config, init, log) {
399
364
  const yurl = new URL(init.request.url);
400
365
  const tenantId = yurl.searchParams.get("tenantId");
401
- const tenant = tenantId ?? getTenantFromHttp(init.request.headers);
366
+ const tenant = tenantId ?? getTenantFromHttp(init.request.headers, config);
402
367
  if (!tenant) {
403
368
  log("[GET] No tenant id provided.");
404
369
  return new Response(null, { status: 404 });
405
370
  }
406
- const url = apiRoutes(config).TENANT_USERS(tenant);
407
371
  init.method = "GET";
372
+ const url = apiRoutes(config).TENANT_USERS(tenant);
408
373
  return await request(url, init, config);
409
374
  }
410
375
 
411
376
  // src/api/routes/users/[userId]/PUT.ts
412
- async function PUT2(config, session, init) {
413
- if (!session) {
414
- return new Response(null, { status: 401 });
415
- }
377
+ async function PUT2(config, init) {
416
378
  init.body = init.request.body;
417
379
  init.method = "PUT";
418
380
  const [userId] = new URL(init.request.url).pathname.split("/").reverse();
@@ -423,18 +385,14 @@ async function PUT2(config, session, init) {
423
385
  // src/api/routes/users/index.ts
424
386
  var key2 = "USERS";
425
387
  async function route2(request2, config) {
426
- const { info } = Logger(
427
- { ...config, debug: config.debug },
428
- `[ROUTES][${key2}]`
429
- );
430
- const session = await auth(request2, config);
388
+ const { info } = config.logger(`[ROUTES][${key2}]`);
431
389
  switch (request2.method) {
432
390
  case "GET":
433
391
  return await GET2(config, { request: request2 }, info);
434
392
  case "POST":
435
393
  return await POST(config, { request: request2 });
436
394
  case "PUT":
437
- return await PUT2(config, session, { request: request2 });
395
+ return await PUT2(config, { request: request2 });
438
396
  default:
439
397
  return new Response("method not allowed", { status: 405 });
440
398
  }
@@ -452,7 +410,11 @@ async function GET3(config, init) {
452
410
  }
453
411
 
454
412
  // src/api/routes/tenants/[tenantId]/users/POST.ts
455
- async function POST2(config, session, init) {
413
+ async function POST2(config, init) {
414
+ const session = await auth(init.request, config);
415
+ if (!session) {
416
+ return new Response(null, { status: 401 });
417
+ }
456
418
  const yurl = new URL(init.request.url);
457
419
  const [, tenantId] = yurl.pathname.split("/").reverse();
458
420
  init.body = JSON.stringify({ email: session.email });
@@ -464,15 +426,7 @@ async function POST2(config, session, init) {
464
426
  // src/api/routes/tenants/[tenantId]/users/index.ts
465
427
  var key3 = "TENANT_USERS";
466
428
  async function route3(request2, config) {
467
- const { info } = Logger(
468
- { ...config, debug: config.debug },
469
- `[ROUTES][${key3}]`
470
- );
471
- const session = await auth(request2, config);
472
- if (!session) {
473
- info("401");
474
- return new Response(null, { status: 401 });
475
- }
429
+ const { info } = config.logger(`[ROUTES][${key3}]`);
476
430
  const yurl = new URL(request2.url);
477
431
  const [, tenantId] = yurl.pathname.split("/").reverse();
478
432
  if (!tenantId) {
@@ -483,7 +437,7 @@ async function route3(request2, config) {
483
437
  case "GET":
484
438
  return await GET3(config, { request: request2 });
485
439
  case "POST":
486
- return await POST2(config, session, { request: request2 });
440
+ return await POST2(config, { request: request2 });
487
441
  default:
488
442
  return new Response("method not allowed", { status: 405 });
489
443
  }
@@ -491,21 +445,21 @@ async function route3(request2, config) {
491
445
  function matches3(configRoutes, request2) {
492
446
  const url = new URL(request2.url);
493
447
  const [userId, possibleTenantId, tenantId] = url.pathname.split("/").reverse();
494
- let route17 = configRoutes[key3].replace("{tenantId}", tenantId).replace("{userId}", userId);
448
+ let route20 = configRoutes[key3].replace("{tenantId}", tenantId).replace("{userId}", userId);
495
449
  if (userId === "users") {
496
- route17 = configRoutes[key3].replace("{tenantId}", possibleTenantId);
450
+ route20 = configRoutes[key3].replace("{tenantId}", possibleTenantId);
497
451
  }
498
- return urlMatches(request2.url, route17);
452
+ return urlMatches(request2.url, route20);
499
453
  }
500
454
  async function fetchTenantUsers(config, method, payload) {
501
455
  const { body, params } = {};
502
456
  if (!config.tenantId) {
503
457
  throw new Error(
504
- 'Unable to fetch tenant, the tenantId context is missing. Call nile.setContext({ tenantId }), set nile.tenantId = "tenantId", or add it to the function call'
458
+ "Unable to fetch the user's tenants, the tenantId context is missing. Call nile.setContext({ tenantId })"
505
459
  );
506
460
  }
507
- if (!isUUID(config.tenantId) && config.logger?.warn) {
508
- config.logger?.warn(
461
+ if (!isUUID(config.tenantId)) {
462
+ config.logger("fetchTenantUsers").warn(
509
463
  "nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
510
464
  );
511
465
  }
@@ -529,8 +483,139 @@ async function fetchTenantUsers(config, method, payload) {
529
483
  return await config.handlers[m](req);
530
484
  }
531
485
 
486
+ // src/api/routes/tenants/[tenantId]/invite/PUT.ts
487
+ async function PUT3(config, init) {
488
+ const yurl = new URL(init.request.url);
489
+ const [, tenantId] = yurl.pathname.split("/").reverse();
490
+ if (!tenantId) {
491
+ return new Response(null, { status: 404 });
492
+ }
493
+ if (yurl.searchParams.size > 0) {
494
+ init.body = new URLSearchParams(yurl.searchParams).toString();
495
+ }
496
+ init.method = "PUT";
497
+ const url = `${apiRoutes(config).INVITE(tenantId)}`;
498
+ const res = await request(url, init, config);
499
+ const location = res?.headers?.get("location");
500
+ if (location) {
501
+ return new Response(res?.body, {
502
+ status: 302,
503
+ headers: res?.headers
504
+ });
505
+ }
506
+ return new Response(res?.body, {
507
+ status: res?.status,
508
+ headers: res?.headers
509
+ });
510
+ }
511
+
512
+ // src/api/routes/tenants/[tenantId]/invite/POST.ts
513
+ async function POST3(config, init) {
514
+ const yurl = new URL(init.request.url);
515
+ const [, tenantId] = yurl.pathname.split("/").reverse();
516
+ if (!tenantId) {
517
+ return new Response(null, { status: 404 });
518
+ }
519
+ init.method = "POST";
520
+ init.body = init.request.body;
521
+ const url = `${apiRoutes(config).INVITE(tenantId)}`;
522
+ return await request(url, init, config);
523
+ }
524
+
525
+ // src/api/routes/tenants/[tenantId]/invite/index.ts
526
+ var key4 = "INVITE";
527
+ async function route4(request2, config) {
528
+ switch (request2.method) {
529
+ // the browser is a GET, but we need to PUT it into nile-auth
530
+ // server side, this is a put
531
+ case "GET":
532
+ case "PUT":
533
+ return await PUT3(config, { request: request2 });
534
+ case "POST":
535
+ return await POST3(config, { request: request2 });
536
+ default:
537
+ return new Response("method not allowed", { status: 405 });
538
+ }
539
+ }
540
+ function matches4(configRoutes, request2) {
541
+ const url = new URL(request2.url);
542
+ const [, tenantId] = url.pathname.split("/").reverse();
543
+ const route20 = configRoutes[key4].replace("{tenantId}", tenantId);
544
+ return urlMatches(request2.url, route20);
545
+ }
546
+ async function fetchInvite(config, method, body) {
547
+ if (!config.tenantId) {
548
+ throw new Error(
549
+ "Unable to fetch the invite for the tenant, the tenantId context is missing. Call nile.setContext({ tenantId })"
550
+ );
551
+ }
552
+ if (!isUUID(config.tenantId)) {
553
+ config.logger("fetchInvite").warn(
554
+ "nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
555
+ );
556
+ }
557
+ let clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace("{tenantId}", config.tenantId)}`;
558
+ const m = method ?? "GET";
559
+ const init = {
560
+ method: m,
561
+ headers: config.headers
562
+ };
563
+ if (method === "POST" || method === "PUT") {
564
+ init.body = body;
565
+ }
566
+ if (method === "DELETE") {
567
+ clientUrl = `${clientUrl}/${body}`;
568
+ }
569
+ const req = new Request(clientUrl, init);
570
+ return await config.handlers[m](req);
571
+ }
572
+
573
+ // src/api/routes/tenants/[tenantId]/invites/GET.ts
574
+ async function GET4(config, init) {
575
+ const yurl = new URL(init.request.url);
576
+ const [, tenantId] = yurl.pathname.split("/").reverse();
577
+ if (!tenantId) {
578
+ return new Response(null, { status: 404 });
579
+ }
580
+ init.method = "GET";
581
+ const url = `${apiRoutes(config).INVITES(tenantId)}`;
582
+ return await request(url, init, config);
583
+ }
584
+
585
+ // src/api/routes/tenants/[tenantId]/invites/index.ts
586
+ var key5 = "INVITES";
587
+ async function route5(request2, config) {
588
+ switch (request2.method) {
589
+ case "GET":
590
+ return await GET4(config, { request: request2 });
591
+ default:
592
+ return new Response("method not allowed", { status: 405 });
593
+ }
594
+ }
595
+ function matches5(configRoutes, request2) {
596
+ const url = new URL(request2.url);
597
+ const [, tenantId] = url.pathname.split("/").reverse();
598
+ const route20 = configRoutes[key5].replace("{tenantId}", tenantId);
599
+ return url.pathname.endsWith(route20);
600
+ }
601
+ async function fetchInvites(config) {
602
+ if (!config.tenantId) {
603
+ throw new Error(
604
+ "Unable to fetch invites for the tenant, the tenantId context is missing. Call nile.setContext({ tenantId })"
605
+ );
606
+ }
607
+ if (!isUUID(config.tenantId)) {
608
+ config.logger("fetchInvites").warn(
609
+ "nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
610
+ );
611
+ }
612
+ const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/invites" /* INVITES */.replace("{tenantId}", config.tenantId)}`;
613
+ const req = new Request(clientUrl, { headers: config.headers });
614
+ return await config.handlers.GET(req);
615
+ }
616
+
532
617
  // src/api/routes/tenants/GET.ts
533
- async function GET4(config, session, init) {
618
+ async function GET5(config, session, init) {
534
619
  let url = `${apiRoutes(config).USER_TENANTS(session.id)}`;
535
620
  if (typeof session === "object" && "user" in session && session.user) {
536
621
  url = `${apiRoutes(config).USER_TENANTS(session.user.id)}`;
@@ -540,7 +625,7 @@ async function GET4(config, session, init) {
540
625
  }
541
626
 
542
627
  // src/api/routes/tenants/[tenantId]/GET.ts
543
- async function GET5(config, init, log) {
628
+ async function GET6(config, init, log) {
544
629
  const yurl = new URL(init.request.url);
545
630
  const [tenantId] = yurl.pathname.split("/").reverse();
546
631
  if (!tenantId) {
@@ -565,7 +650,7 @@ async function DELETE2(config, init) {
565
650
  }
566
651
 
567
652
  // src/api/routes/tenants/[tenantId]/PUT.ts
568
- async function PUT3(config, init) {
653
+ async function PUT4(config, init) {
569
654
  const yurl = new URL(init.request.url);
570
655
  const [tenantId] = yurl.pathname.split("/").reverse();
571
656
  if (!tenantId) {
@@ -578,7 +663,7 @@ async function PUT3(config, init) {
578
663
  }
579
664
 
580
665
  // src/api/routes/tenants/POST.ts
581
- async function POST3(config, init) {
666
+ async function POST4(config, init) {
582
667
  init.body = init.request.body;
583
668
  init.method = "POST";
584
669
  const url = `${apiRoutes(config).TENANTS}`;
@@ -586,12 +671,9 @@ async function POST3(config, init) {
586
671
  }
587
672
 
588
673
  // src/api/routes/tenants/index.ts
589
- var key4 = "TENANTS";
590
- async function route4(request2, config) {
591
- const { info } = Logger(
592
- { ...config, debug: config.debug },
593
- `[ROUTES][${key4}]`
594
- );
674
+ var key6 = "TENANTS";
675
+ async function route6(request2, config) {
676
+ const { info } = config.logger(`[ROUTES][${key6}]`);
595
677
  const session = await auth(request2, config);
596
678
  if (!session) {
597
679
  info("401");
@@ -601,21 +683,21 @@ async function route4(request2, config) {
601
683
  switch (request2.method) {
602
684
  case "GET":
603
685
  if (isUUID(possibleTenantId)) {
604
- return await GET5(config, { request: request2 }, info);
686
+ return await GET6(config, { request: request2 }, info);
605
687
  }
606
- return await GET4(config, session, { request: request2 });
688
+ return await GET5(config, session, { request: request2 });
607
689
  case "POST":
608
- return await POST3(config, { request: request2 });
690
+ return await POST4(config, { request: request2 });
609
691
  case "DELETE":
610
692
  return await DELETE2(config, { request: request2 });
611
693
  case "PUT":
612
- return await PUT3(config, { request: request2 });
694
+ return await PUT4(config, { request: request2 });
613
695
  default:
614
696
  return new Response("method not allowed", { status: 405 });
615
697
  }
616
698
  }
617
- function matches4(configRoutes, request2) {
618
- return urlMatches(request2.url, configRoutes[key4]);
699
+ function matches6(configRoutes, request2) {
700
+ return urlMatches(request2.url, configRoutes[key6]);
619
701
  }
620
702
  async function fetchTenants(config, method, body) {
621
703
  const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants" /* TENANTS */}`;
@@ -632,11 +714,11 @@ async function fetchTenants(config, method, body) {
632
714
  async function fetchTenant(config, method, body) {
633
715
  if (!config.tenantId) {
634
716
  throw new Error(
635
- 'Unable to fetch tenant, the tenantId context is missing. Call nile.setContext({ tenantId }), set nile.tenantId = "tenantId", or add it to the function call'
717
+ "Unable to fetch tenants, the tenantId context is missing. Call nile.setContext({ tenantId })"
636
718
  );
637
719
  }
638
- if (!isUUID(config.tenantId) && config.logger?.warn) {
639
- config.logger?.warn(
720
+ if (!isUUID(config.tenantId)) {
721
+ config.logger("fetch tenant").warn(
640
722
  "nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
641
723
  );
642
724
  }
@@ -653,36 +735,32 @@ async function fetchTenant(config, method, body) {
653
735
  return await config.handlers[m](req);
654
736
  }
655
737
  async function fetchTenantsByUser(config) {
656
- if (config.logger?.warn) {
657
- if (!config.userId) {
658
- config.logger?.warn(
659
- "nile.userId is not set. The call will still work for the API, but the database context is not set properly and may lead to unexpected behavior in your application."
660
- );
661
- } else if (!isUUID(config.userId)) {
662
- config.logger?.warn(
663
- "nile.userId is not a valid UUID. This may lead to unexpected behavior in your application."
664
- );
665
- }
738
+ const { warn } = config.logger("fetchTenantsByUser");
739
+ if (!config.userId) {
740
+ warn(
741
+ "nile.userId is not set. The call will still work for the API, but the database context is not set properly and may lead to unexpected behavior in your application."
742
+ );
743
+ } else if (!isUUID(config.userId)) {
744
+ warn(
745
+ "nile.userId is not a valid UUID. This may lead to unexpected behavior in your application."
746
+ );
666
747
  }
667
- const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/users/{userId}/tenants" /* USER_TENANTS */.replace(
668
- "{userId}",
669
- config.userId ?? "WARN_NOT_SET"
670
- )}`;
748
+ const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants" /* TENANTS */}`;
671
749
  const req = new Request(clientUrl, { headers: config.headers });
672
750
  return await config.handlers.GET(req);
673
751
  }
674
752
 
675
753
  // src/api/routes/auth/signin.ts
676
- var key5 = "SIGNIN";
677
- async function route5(req, config) {
678
- let url = proxyRoutes(config)[key5];
754
+ var key7 = "SIGNIN";
755
+ async function route7(req, config) {
756
+ let url = proxyRoutes(config)[key7];
679
757
  const init = {
680
758
  method: req.method,
681
759
  headers: req.headers
682
760
  };
683
761
  if (req.method === "POST") {
684
762
  const [provider] = new URL(req.url).pathname.split("/").reverse();
685
- url = `${proxyRoutes(config)[key5]}/${provider}`;
763
+ url = `${proxyRoutes(config)[key7]}/${provider}`;
686
764
  }
687
765
  const passThroughUrl = new URL(req.url);
688
766
  const params = new URLSearchParams(passThroughUrl.search);
@@ -690,8 +768,8 @@ async function route5(req, config) {
690
768
  const res = await request(url, { ...init, request: req }, config);
691
769
  return res;
692
770
  }
693
- function matches5(configRoutes, request2) {
694
- return urlMatches(request2.url, configRoutes[key5]);
771
+ function matches7(configRoutes, request2) {
772
+ return urlMatches(request2.url, configRoutes[key7]);
695
773
  }
696
774
  async function fetchSignIn(config, provider, body) {
697
775
  const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/signin" /* SIGNIN */}/${provider}`;
@@ -704,7 +782,7 @@ async function fetchSignIn(config, provider, body) {
704
782
  }
705
783
 
706
784
  // src/api/routes/auth/session.ts
707
- async function route6(req, config) {
785
+ async function route8(req, config) {
708
786
  return request(
709
787
  proxyRoutes(config).SESSION,
710
788
  {
@@ -714,7 +792,7 @@ async function route6(req, config) {
714
792
  config
715
793
  );
716
794
  }
717
- function matches6(configRoutes, request2) {
795
+ function matches8(configRoutes, request2) {
718
796
  return urlMatches(request2.url, configRoutes.SESSION);
719
797
  }
720
798
  async function fetchSession(config) {
@@ -727,7 +805,7 @@ async function fetchSession(config) {
727
805
  }
728
806
 
729
807
  // src/api/routes/auth/providers.ts
730
- async function route7(req, config) {
808
+ async function route9(req, config) {
731
809
  return request(
732
810
  proxyRoutes(config).PROVIDERS,
733
811
  {
@@ -737,7 +815,7 @@ async function route7(req, config) {
737
815
  config
738
816
  );
739
817
  }
740
- function matches7(configRoutes, request2) {
818
+ function matches9(configRoutes, request2) {
741
819
  return urlMatches(request2.url, configRoutes.PROVIDERS);
742
820
  }
743
821
  async function fetchProviders(config) {
@@ -750,7 +828,7 @@ async function fetchProviders(config) {
750
828
  }
751
829
 
752
830
  // src/api/routes/auth/csrf.ts
753
- async function route8(req, config) {
831
+ async function route10(req, config) {
754
832
  return request(
755
833
  proxyRoutes(config).CSRF,
756
834
  {
@@ -760,7 +838,7 @@ async function route8(req, config) {
760
838
  config
761
839
  );
762
840
  }
763
- function matches8(configRoutes, request2) {
841
+ function matches10(configRoutes, request2) {
764
842
  return urlMatches(request2.url, configRoutes.CSRF);
765
843
  }
766
844
  async function fetchCsrf(config) {
@@ -773,17 +851,14 @@ async function fetchCsrf(config) {
773
851
  }
774
852
 
775
853
  // src/api/routes/auth/callback.ts
776
- var key6 = "CALLBACK";
777
- async function route9(req, config) {
778
- const { error } = Logger(
779
- { ...config, debug: config.debug },
780
- `[ROUTES][${key6}]`
781
- );
854
+ var key8 = "CALLBACK";
855
+ async function route11(req, config) {
856
+ const { error } = config.logger(`[ROUTES][${key8}]`);
782
857
  const [provider] = new URL(req.url).pathname.split("/").reverse();
783
858
  try {
784
859
  const passThroughUrl = new URL(req.url);
785
860
  const params = new URLSearchParams(passThroughUrl.search);
786
- const url = `${proxyRoutes(config)[key6]}/${provider}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
861
+ const url = `${proxyRoutes(config)[key8]}/${provider}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
787
862
  const res = await request(
788
863
  url,
789
864
  {
@@ -794,7 +869,7 @@ async function route9(req, config) {
794
869
  ).catch((e) => {
795
870
  error("an error as occurred", e);
796
871
  });
797
- const location = res?.headers.get("location");
872
+ const location = res?.headers?.get("location");
798
873
  if (location) {
799
874
  return new Response(res?.body, {
800
875
  status: 302,
@@ -810,7 +885,7 @@ async function route9(req, config) {
810
885
  }
811
886
  return new Response("An unexpected error has occurred.", { status: 400 });
812
887
  }
813
- function matches9(configRoutes, request2) {
888
+ function matches11(configRoutes, request2) {
814
889
  return urlMatches(request2.url, configRoutes.CALLBACK);
815
890
  }
816
891
  async function fetchCallback(config, provider, body, request2, method = "POST") {
@@ -824,22 +899,22 @@ async function fetchCallback(config, provider, body, request2, method = "POST")
824
899
  }
825
900
 
826
901
  // src/api/routes/auth/signout.ts
827
- var key7 = "SIGNOUT";
828
- async function route10(request2, config) {
829
- let url = proxyRoutes(config)[key7];
902
+ var key9 = "SIGNOUT";
903
+ async function route12(request2, config) {
904
+ let url = proxyRoutes(config)[key9];
830
905
  const init = {
831
906
  method: request2.method
832
907
  };
833
908
  if (request2.method === "POST") {
834
909
  init.body = request2.body;
835
910
  const [provider] = new URL(request2.url).pathname.split("/").reverse();
836
- url = `${proxyRoutes(config)[key7]}${provider !== "signout" ? `/${provider}` : ""}`;
911
+ url = `${proxyRoutes(config)[key9]}${provider !== "signout" ? `/${provider}` : ""}`;
837
912
  }
838
913
  const res = await request(url, { ...init, request: request2 }, config);
839
914
  return res;
840
915
  }
841
- function matches10(configRoutes, request2) {
842
- return urlMatches(request2.url, configRoutes[key7]);
916
+ function matches12(configRoutes, request2) {
917
+ return urlMatches(request2.url, configRoutes[key9]);
843
918
  }
844
919
  async function fetchSignOut(config, body) {
845
920
  const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/signout" /* SIGNOUT */}`;
@@ -852,10 +927,10 @@ async function fetchSignOut(config, body) {
852
927
  }
853
928
 
854
929
  // src/api/routes/auth/error.ts
855
- var key8 = "ERROR";
856
- async function route11(req, config) {
930
+ var key10 = "ERROR";
931
+ async function route13(req, config) {
857
932
  return request(
858
- proxyRoutes(config)[key8],
933
+ proxyRoutes(config)[key10],
859
934
  {
860
935
  method: req.method,
861
936
  request: req
@@ -863,15 +938,15 @@ async function route11(req, config) {
863
938
  config
864
939
  );
865
940
  }
866
- function matches11(configRoutes, request2) {
867
- return urlMatches(request2.url, configRoutes[key8]);
941
+ function matches13(configRoutes, request2) {
942
+ return urlMatches(request2.url, configRoutes[key10]);
868
943
  }
869
944
 
870
945
  // src/api/routes/auth/verify-request.ts
871
- var key9 = "VERIFY_REQUEST";
872
- async function route12(req, config) {
946
+ var key11 = "VERIFY_REQUEST";
947
+ async function route14(req, config) {
873
948
  return request(
874
- proxyRoutes(config)[key9],
949
+ proxyRoutes(config)[key11],
875
950
  {
876
951
  method: req.method,
877
952
  request: req
@@ -879,14 +954,14 @@ async function route12(req, config) {
879
954
  config
880
955
  );
881
956
  }
882
- function matches12(configRoutes, request2) {
883
- return urlMatches(request2.url, configRoutes[key9]);
957
+ function matches14(configRoutes, request2) {
958
+ return urlMatches(request2.url, configRoutes[key11]);
884
959
  }
885
960
 
886
961
  // src/api/routes/auth/password-reset.ts
887
- var key10 = "PASSWORD_RESET";
888
- async function route13(req, config) {
889
- const url = proxyRoutes(config)[key10];
962
+ var key12 = "PASSWORD_RESET";
963
+ async function route15(req, config) {
964
+ const url = proxyRoutes(config)[key12];
890
965
  const res = await request(
891
966
  url,
892
967
  {
@@ -895,7 +970,7 @@ async function route13(req, config) {
895
970
  },
896
971
  config
897
972
  );
898
- const location = res?.headers.get("location");
973
+ const location = res?.headers?.get("location");
899
974
  if (location) {
900
975
  return new Response(res?.body, {
901
976
  status: 302,
@@ -907,12 +982,14 @@ async function route13(req, config) {
907
982
  headers: res?.headers
908
983
  });
909
984
  }
910
- function matches13(configRoutes, request2) {
985
+ function matches15(configRoutes, request2) {
911
986
  return urlMatches(request2.url, configRoutes.PASSWORD_RESET);
912
987
  }
913
- async function fetchResetPassword(config, method, body, params) {
988
+ async function fetchResetPassword(config, method, body, params, useJson = true) {
914
989
  const authParams = new URLSearchParams(params ?? {});
915
- authParams?.set("json", "true");
990
+ if (useJson) {
991
+ authParams?.set("json", "true");
992
+ }
916
993
  const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}?${authParams?.toString()}`;
917
994
  const init = {
918
995
  method,
@@ -926,9 +1003,9 @@ async function fetchResetPassword(config, method, body, params) {
926
1003
  }
927
1004
 
928
1005
  // src/api/routes/auth/verify-email.ts
929
- var key11 = "VERIFY_EMAIL";
930
- async function route14(req, config) {
931
- const url = proxyRoutes(config)[key11];
1006
+ var key13 = "VERIFY_EMAIL";
1007
+ async function route16(req, config) {
1008
+ const url = proxyRoutes(config)[key13];
932
1009
  const res = await request(
933
1010
  url,
934
1011
  {
@@ -937,7 +1014,7 @@ async function route14(req, config) {
937
1014
  },
938
1015
  config
939
1016
  );
940
- const location = res?.headers.get("location");
1017
+ const location = res?.headers?.get("location");
941
1018
  if (location) {
942
1019
  return new Response(res?.body, {
943
1020
  status: 302,
@@ -949,8 +1026,8 @@ async function route14(req, config) {
949
1026
  headers: res?.headers
950
1027
  });
951
1028
  }
952
- function matches14(configRoutes, request2) {
953
- return urlMatches(request2.url, configRoutes[key11]);
1029
+ function matches16(configRoutes, request2) {
1030
+ return urlMatches(request2.url, configRoutes[key13]);
954
1031
  }
955
1032
  async function fetchVerifyEmail(config, method, body) {
956
1033
  const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/verify-email" /* VERIFY_EMAIL */}`;
@@ -967,71 +1044,154 @@ async function fetchVerifyEmail(config, method, body) {
967
1044
 
968
1045
  // src/api/handlers/GET.ts
969
1046
  function GETTER(configRoutes, config) {
970
- const { info, warn } = Logger(config, "[GET MATCHER]");
971
- return async function GET6(req) {
1047
+ const { error, info, warn } = config.logger("[GET MATCHER]");
1048
+ return async function GET7(...params) {
1049
+ const handledRequest = await config.extensionCtx?.runExtensions(
1050
+ "onHandleRequest" /* onHandleRequest */,
1051
+ config,
1052
+ params
1053
+ );
1054
+ if (handledRequest) {
1055
+ return handledRequest;
1056
+ }
1057
+ const req = params[0] instanceof Request ? params[0] : null;
1058
+ if (!req) {
1059
+ error("Proxy requests failed, a Request object was not passed.");
1060
+ return;
1061
+ }
972
1062
  if (matches(configRoutes, req)) {
973
1063
  info("matches me");
974
1064
  return route(req, config);
975
1065
  }
1066
+ if (matches5(configRoutes, req)) {
1067
+ info("matches tenant invites");
1068
+ return route5(req, config);
1069
+ }
1070
+ if (matches4(configRoutes, req)) {
1071
+ info("matches invite");
1072
+ return route4(req, config);
1073
+ }
976
1074
  if (matches3(configRoutes, req)) {
977
1075
  info("matches tenant users");
978
1076
  return route3(req, config);
979
1077
  }
1078
+ if (matches6(configRoutes, req)) {
1079
+ info("matches tenants");
1080
+ return route6(req, config);
1081
+ }
980
1082
  if (matches2(configRoutes, req)) {
981
1083
  info("matches users");
982
1084
  return route2(req, config);
983
1085
  }
984
- if (matches4(configRoutes, req)) {
985
- info("matches tenants");
986
- return route4(req, config);
987
- }
988
- if (matches6(configRoutes, req)) {
1086
+ if (matches8(configRoutes, req)) {
989
1087
  info("matches session");
990
- return route6(req, config);
1088
+ return route8(req, config);
991
1089
  }
992
- if (matches5(configRoutes, req)) {
1090
+ if (matches7(configRoutes, req)) {
993
1091
  info("matches signin");
994
- return route5(req, config);
1092
+ return route7(req, config);
995
1093
  }
996
- if (matches7(configRoutes, req)) {
1094
+ if (matches9(configRoutes, req)) {
997
1095
  info("matches providers");
998
- return route7(req, config);
1096
+ return route9(req, config);
999
1097
  }
1000
- if (matches8(configRoutes, req)) {
1098
+ if (matches10(configRoutes, req)) {
1001
1099
  info("matches csrf");
1002
- return route8(req, config);
1100
+ return route10(req, config);
1003
1101
  }
1004
- if (matches13(configRoutes, req)) {
1102
+ if (matches15(configRoutes, req)) {
1005
1103
  info("matches password reset");
1006
- return route13(req, config);
1104
+ return route15(req, config);
1007
1105
  }
1008
- if (matches9(configRoutes, req)) {
1106
+ if (matches11(configRoutes, req)) {
1009
1107
  info("matches callback");
1010
- return route9(req, config);
1011
- }
1012
- if (matches10(configRoutes, req)) {
1013
- info("matches signout");
1014
- return route10(req, config);
1108
+ return route11(req, config);
1015
1109
  }
1016
1110
  if (matches12(configRoutes, req)) {
1017
- info("matches verify-request");
1111
+ info("matches signout");
1018
1112
  return route12(req, config);
1019
1113
  }
1020
1114
  if (matches14(configRoutes, req)) {
1021
- info("matches verify-email");
1115
+ info("matches verify-request");
1022
1116
  return route14(req, config);
1023
1117
  }
1024
- if (matches11(configRoutes, req)) {
1118
+ if (matches16(configRoutes, req)) {
1119
+ info("matches verify-email");
1120
+ return route16(req, config);
1121
+ }
1122
+ if (matches13(configRoutes, req)) {
1025
1123
  info("matches error");
1026
- return route11(req, config);
1124
+ return route13(req, config);
1027
1125
  }
1028
1126
  warn(`No GET routes matched ${req.url}`);
1029
1127
  return new Response(null, { status: 404 });
1030
1128
  };
1031
1129
  }
1032
1130
 
1131
+ // src/utils/Logger.ts
1132
+ var red = "\x1B[31m";
1133
+ var yellow = "\x1B[38;2;255;255;0m";
1134
+ var purple = "\x1B[38;2;200;160;255m";
1135
+ var orange = "\x1B[38;2;255;165;0m";
1136
+ var reset = "\x1B[0m";
1137
+ var baseLogger = (config, ...params) => ({
1138
+ info(message, meta) {
1139
+ if (config?.debug) {
1140
+ console.info(
1141
+ `${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
1142
+ ""
1143
+ )}${reset} ${message}`,
1144
+ meta ? `${JSON.stringify(meta)}` : ""
1145
+ );
1146
+ }
1147
+ },
1148
+ debug(message, meta) {
1149
+ if (config?.debug) {
1150
+ console.debug(
1151
+ `${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
1152
+ ""
1153
+ )}${reset} ${message}`,
1154
+ meta ? `${JSON.stringify(meta)}` : ""
1155
+ );
1156
+ }
1157
+ },
1158
+ warn(message, meta) {
1159
+ if (config?.debug) {
1160
+ console.warn(
1161
+ `${orange}[niledb]${reset}${yellow}[WARN]${reset}${params.join(
1162
+ ""
1163
+ )}${reset} ${message}`,
1164
+ meta ? JSON.stringify(meta) : ""
1165
+ );
1166
+ }
1167
+ },
1168
+ error(message, meta) {
1169
+ console.error(
1170
+ `${orange}[niledb]${reset}${red}[ERROR]${reset}${params.join(
1171
+ ""
1172
+ )}${red} ${message}`,
1173
+ meta ? meta : "",
1174
+ `${reset}`
1175
+ );
1176
+ }
1177
+ });
1178
+ function Logger(config) {
1179
+ return (prefixes) => {
1180
+ const { info, debug, warn, error } = config && typeof config?.logger === "function" ? config.logger(prefixes) : baseLogger(config, prefixes);
1181
+ return {
1182
+ info,
1183
+ debug,
1184
+ warn,
1185
+ error
1186
+ };
1187
+ };
1188
+ }
1189
+ function matchesLog(configRoutes, request2) {
1190
+ return urlMatches(request2.url, configRoutes.LOG);
1191
+ }
1192
+
1033
1193
  // src/api/routes/signup/POST.ts
1034
- async function POST4(config, init) {
1194
+ async function POST5(config, init) {
1035
1195
  init.body = init.request.body;
1036
1196
  init.method = "POST";
1037
1197
  const url = `${apiRoutes(config).SIGNUP}`;
@@ -1039,17 +1199,17 @@ async function POST4(config, init) {
1039
1199
  }
1040
1200
 
1041
1201
  // src/api/routes/signup/index.tsx
1042
- var key12 = "SIGNUP";
1043
- async function route15(request2, config) {
1202
+ var key14 = "SIGNUP";
1203
+ async function route17(request2, config) {
1044
1204
  switch (request2.method) {
1045
1205
  case "POST":
1046
- return await POST4(config, { request: request2 });
1206
+ return await POST5(config, { request: request2 });
1047
1207
  default:
1048
1208
  return new Response("method not allowed", { status: 405 });
1049
1209
  }
1050
1210
  }
1051
- function matches15(configRoutes, request2) {
1052
- return urlMatches(request2.url, configRoutes[key12]);
1211
+ function matches17(configRoutes, request2) {
1212
+ return urlMatches(request2.url, configRoutes[key14]);
1053
1213
  }
1054
1214
  async function fetchSignUp(config, payload) {
1055
1215
  const { body, params } = payload ?? {};
@@ -1071,8 +1231,21 @@ async function fetchSignUp(config, payload) {
1071
1231
 
1072
1232
  // src/api/handlers/POST.ts
1073
1233
  function POSTER(configRoutes, config) {
1074
- const { info, warn, error } = Logger(config, "[POST MATCHER]");
1075
- return async function POST5(req) {
1234
+ const { info, warn, error } = config.logger("[POST MATCHER]");
1235
+ return async function POST6(...params) {
1236
+ const handledRequest = await config.extensionCtx?.runExtensions(
1237
+ "onHandleRequest" /* onHandleRequest */,
1238
+ config,
1239
+ params
1240
+ );
1241
+ if (handledRequest) {
1242
+ return handledRequest;
1243
+ }
1244
+ const req = params[0] instanceof Request ? params[0] : null;
1245
+ if (!req) {
1246
+ error("Proxy requests failed, a Request object was not passed.");
1247
+ return;
1248
+ }
1076
1249
  if (matchesLog(configRoutes, req)) {
1077
1250
  try {
1078
1251
  const json = await req.clone().json();
@@ -1086,49 +1259,53 @@ function POSTER(configRoutes, config) {
1086
1259
  info("matches tenant users");
1087
1260
  return route3(req, config);
1088
1261
  }
1089
- if (matches15(configRoutes, req)) {
1262
+ if (matches4(configRoutes, req)) {
1263
+ info("matches tenant invite");
1264
+ return route4(req, config);
1265
+ }
1266
+ if (matches17(configRoutes, req)) {
1090
1267
  info("matches signup");
1091
- return route15(req, config);
1268
+ return route17(req, config);
1092
1269
  }
1093
1270
  if (matches2(configRoutes, req)) {
1094
1271
  info("matches users");
1095
1272
  return route2(req, config);
1096
1273
  }
1097
- if (matches4(configRoutes, req)) {
1098
- info("matches tenants");
1099
- return route4(req, config);
1100
- }
1101
1274
  if (matches6(configRoutes, req)) {
1102
- info("matches session");
1275
+ info("matches tenants");
1103
1276
  return route6(req, config);
1104
1277
  }
1105
- if (matches5(configRoutes, req)) {
1106
- info("matches signin");
1107
- return route5(req, config);
1108
- }
1109
- if (matches13(configRoutes, req)) {
1110
- info("matches password reset");
1111
- return route13(req, config);
1278
+ if (matches8(configRoutes, req)) {
1279
+ info("matches session");
1280
+ return route8(req, config);
1112
1281
  }
1113
1282
  if (matches7(configRoutes, req)) {
1114
- info("matches providers");
1283
+ info("matches signin");
1115
1284
  return route7(req, config);
1116
1285
  }
1117
- if (matches8(configRoutes, req)) {
1118
- info("matches csrf");
1119
- return route8(req, config);
1286
+ if (matches15(configRoutes, req)) {
1287
+ info("matches password reset");
1288
+ return route15(req, config);
1120
1289
  }
1121
1290
  if (matches9(configRoutes, req)) {
1122
- info("matches callback");
1291
+ info("matches providers");
1123
1292
  return route9(req, config);
1124
1293
  }
1125
1294
  if (matches10(configRoutes, req)) {
1126
- info("matches signout");
1295
+ info("matches csrf");
1127
1296
  return route10(req, config);
1128
1297
  }
1129
- if (matches14(configRoutes, req)) {
1298
+ if (matches11(configRoutes, req)) {
1299
+ info("matches callback");
1300
+ return route11(req, config);
1301
+ }
1302
+ if (matches12(configRoutes, req)) {
1303
+ info("matches signout");
1304
+ return route12(req, config);
1305
+ }
1306
+ if (matches16(configRoutes, req)) {
1130
1307
  info("matches verify-email");
1131
- return route14(req, config);
1308
+ return route16(req, config);
1132
1309
  }
1133
1310
  warn(`No POST routes matched ${req.url}`);
1134
1311
  return new Response(null, { status: 404 });
@@ -1147,7 +1324,7 @@ async function DELETE3(config, init) {
1147
1324
  }
1148
1325
 
1149
1326
  // src/api/routes/tenants/[tenantId]/users/[userId]/PUT.ts
1150
- async function PUT4(config, init) {
1327
+ async function PUT5(config, init) {
1151
1328
  const yurl = new URL(init.request.url);
1152
1329
  const [, userId, , tenantId] = yurl.pathname.split("/").reverse();
1153
1330
  config.tenantId = tenantId;
@@ -1158,12 +1335,9 @@ async function PUT4(config, init) {
1158
1335
  }
1159
1336
 
1160
1337
  // src/api/routes/tenants/[tenantId]/users/[userId]/index.ts
1161
- var key13 = "TENANT_USER";
1162
- async function route16(request2, config) {
1163
- const { info } = Logger(
1164
- { ...config, debug: config.debug },
1165
- `[ROUTES][${key13}]`
1166
- );
1338
+ var key15 = "TENANT_USER";
1339
+ async function route18(request2, config) {
1340
+ const { info } = config.logger(`[ROUTES][${key15}]`);
1167
1341
  const session = await auth(request2, config);
1168
1342
  if (!session) {
1169
1343
  info("401");
@@ -1177,21 +1351,21 @@ async function route16(request2, config) {
1177
1351
  }
1178
1352
  switch (request2.method) {
1179
1353
  case "PUT":
1180
- return await PUT4(config, { request: request2 });
1354
+ return await PUT5(config, { request: request2 });
1181
1355
  case "DELETE":
1182
1356
  return await DELETE3(config, { request: request2 });
1183
1357
  default:
1184
1358
  return new Response("method not allowed", { status: 405 });
1185
1359
  }
1186
1360
  }
1187
- function matches16(configRoutes, request2) {
1361
+ function matches18(configRoutes, request2) {
1188
1362
  const url = new URL(request2.url);
1189
1363
  const [, userId, possibleTenantId, tenantId] = url.pathname.split("/").reverse();
1190
- let route17 = configRoutes[key13].replace("{tenantId}", tenantId).replace("{userId}", userId);
1364
+ let route20 = configRoutes[key15].replace("{tenantId}", tenantId).replace("{userId}", userId);
1191
1365
  if (userId === "users") {
1192
- route17 = configRoutes[key13].replace("{tenantId}", possibleTenantId);
1366
+ route20 = configRoutes[key15].replace("{tenantId}", possibleTenantId);
1193
1367
  }
1194
- return urlMatches(request2.url, route17);
1368
+ return urlMatches(request2.url, route20);
1195
1369
  }
1196
1370
  async function fetchTenantUser(config, method) {
1197
1371
  if (!config.tenantId) {
@@ -1215,21 +1389,63 @@ async function fetchTenantUser(config, method) {
1215
1389
  return await config.handlers[method](req);
1216
1390
  }
1217
1391
 
1392
+ // src/api/routes/tenants/[tenantId]/invite/[inviteId]/DELETE.ts
1393
+ async function DELETE4(config, init) {
1394
+ const yurl = new URL(init.request.url);
1395
+ const [inviteId, , tenantId] = yurl.pathname.split("/").reverse();
1396
+ if (!tenantId) {
1397
+ return new Response(null, { status: 404 });
1398
+ }
1399
+ init.method = "DELETE";
1400
+ const url = `${apiRoutes(config).INVITE(tenantId)}/${inviteId}`;
1401
+ return await request(url, init, config);
1402
+ }
1403
+
1404
+ // src/api/routes/tenants/[tenantId]/invite/[inviteId]/index.ts
1405
+ var key16 = "INVITE";
1406
+ async function route19(request2, config) {
1407
+ switch (request2.method) {
1408
+ case "DELETE":
1409
+ return await DELETE4(config, { request: request2 });
1410
+ default:
1411
+ return new Response("method not allowed", { status: 405 });
1412
+ }
1413
+ }
1414
+ function matches19(configRoutes, request2) {
1415
+ const url = new URL(request2.url);
1416
+ const [inviteId, , tenantId] = url.pathname.split("/").reverse();
1417
+ const route20 = configRoutes[key16].replace("{tenantId}", tenantId).replace("{inviteId}", inviteId);
1418
+ return urlMatches(request2.url, route20);
1419
+ }
1420
+
1218
1421
  // src/api/handlers/DELETE.ts
1219
1422
  function DELETER(configRoutes, config) {
1220
- const { info, warn } = Logger(config, "[DELETE MATCHER]");
1221
- return async function DELETE4(req) {
1222
- if (matches16(configRoutes, req)) {
1223
- info("matches tenant user");
1224
- return route16(req, config);
1423
+ const { error, info, warn } = config.logger("[DELETE MATCHER]");
1424
+ return async function DELETE5(...params) {
1425
+ const handledRequest = await config.extensionCtx?.runExtensions(
1426
+ "onHandleRequest" /* onHandleRequest */,
1427
+ config,
1428
+ params
1429
+ );
1430
+ if (handledRequest) {
1431
+ return handledRequest;
1225
1432
  }
1226
- if (matches3(configRoutes, req)) {
1227
- info("matches tenant users");
1228
- return route3(req, config);
1433
+ const req = params[0] instanceof Request ? params[0] : null;
1434
+ if (!req) {
1435
+ error("Proxy requests failed, a Request object was not passed.");
1436
+ return;
1229
1437
  }
1230
- if (matches4(configRoutes, req)) {
1438
+ if (matches19(configRoutes, req)) {
1439
+ info("matches tenant invite id");
1440
+ return route19(req, config);
1441
+ }
1442
+ if (matches18(configRoutes, req)) {
1443
+ info("matches tenant user");
1444
+ return route18(req, config);
1445
+ }
1446
+ if (matches6(configRoutes, req)) {
1231
1447
  info("matches tenants");
1232
- return route4(req, config);
1448
+ return route6(req, config);
1233
1449
  }
1234
1450
  if (matches(configRoutes, req)) {
1235
1451
  info("matches me");
@@ -1242,11 +1458,28 @@ function DELETER(configRoutes, config) {
1242
1458
 
1243
1459
  // src/api/handlers/PUT.ts
1244
1460
  function PUTER(configRoutes, config) {
1245
- const { info, warn } = Logger(config, "[PUT MATCHER]");
1246
- return async function PUT5(req) {
1247
- if (matches16(configRoutes, req)) {
1461
+ const { error, info, warn } = config.logger("[PUT MATCHER]");
1462
+ return async function PUT6(...params) {
1463
+ const handledRequest = await config.extensionCtx?.runExtensions(
1464
+ "onHandleRequest" /* onHandleRequest */,
1465
+ config,
1466
+ params
1467
+ );
1468
+ if (handledRequest) {
1469
+ return handledRequest;
1470
+ }
1471
+ const req = params[0] instanceof Request ? params[0] : null;
1472
+ if (!req) {
1473
+ error("Proxy requests failed, a Request object was not passed.");
1474
+ return;
1475
+ }
1476
+ if (matches4(configRoutes, req)) {
1477
+ info("matches tenant invite");
1478
+ return route4(req, config);
1479
+ }
1480
+ if (matches18(configRoutes, req)) {
1248
1481
  info("matches tenant user");
1249
- return route16(req, config);
1482
+ return route18(req, config);
1250
1483
  }
1251
1484
  if (matches3(configRoutes, req)) {
1252
1485
  info("matches tenant users");
@@ -1260,13 +1493,13 @@ function PUTER(configRoutes, config) {
1260
1493
  info("matches me");
1261
1494
  return route(req, config);
1262
1495
  }
1263
- if (matches4(configRoutes, req)) {
1496
+ if (matches6(configRoutes, req)) {
1264
1497
  info("matches tenants");
1265
- return route4(req, config);
1498
+ return route6(req, config);
1266
1499
  }
1267
- if (matches13(configRoutes, req)) {
1500
+ if (matches15(configRoutes, req)) {
1268
1501
  info("matches reset password");
1269
- return route13(req, config);
1502
+ return route15(req, config);
1270
1503
  }
1271
1504
  warn("No PUT routes matched");
1272
1505
  return new Response(null, { status: 404 });
@@ -1275,15 +1508,15 @@ function PUTER(configRoutes, config) {
1275
1508
 
1276
1509
  // src/api/handlers/index.ts
1277
1510
  function Handlers(configRoutes, config) {
1278
- const GET6 = GETTER(configRoutes, config);
1279
- const POST5 = POSTER(configRoutes, config);
1280
- const DELETE4 = DELETER(configRoutes, config);
1281
- const PUT5 = PUTER(configRoutes, config);
1511
+ const GET7 = GETTER(configRoutes, config);
1512
+ const POST6 = POSTER(configRoutes, config);
1513
+ const DELETE5 = DELETER(configRoutes, config);
1514
+ const PUT6 = PUTER(configRoutes, config);
1282
1515
  return {
1283
- GET: GET6,
1284
- POST: POST5,
1285
- DELETE: DELETE4,
1286
- PUT: PUT5
1516
+ GET: GET7,
1517
+ POST: POST6,
1518
+ DELETE: DELETE5,
1519
+ PUT: PUT6
1287
1520
  };
1288
1521
  }
1289
1522
  var getApiUrl = (cfg) => {
@@ -1316,15 +1549,16 @@ var getSecureCookies = (cfg) => {
1316
1549
  return void 0;
1317
1550
  };
1318
1551
  var getUsername = (cfg) => {
1319
- const { config, logger } = cfg;
1320
- const { info } = Logger(config, "[username]");
1552
+ const { config } = cfg;
1553
+ const logger = config.logger;
1554
+ const { info } = logger();
1321
1555
  if (config?.user) {
1322
- logger && info(`${logger}[config] ${config.user}`);
1556
+ info(`[config] ${config.user}`);
1323
1557
  return String(config?.user);
1324
1558
  }
1325
1559
  const user = stringCheck(process.env.NILEDB_USER);
1326
1560
  if (user) {
1327
- logger && info(`${logger}[NILEDB_USER] ${user}`);
1561
+ info(`[NILEDB_USER] ${user}`);
1328
1562
  return user;
1329
1563
  }
1330
1564
  const pg2 = stringCheck(process.env.NILEDB_POSTGRES_URL);
@@ -1342,16 +1576,16 @@ var getUsername = (cfg) => {
1342
1576
  );
1343
1577
  };
1344
1578
  var getPassword = (cfg) => {
1345
- const { config, logger } = cfg;
1579
+ const { config } = cfg;
1580
+ const logger = config.logger;
1346
1581
  const log = logProtector(logger);
1347
- const { info } = Logger(config, "[password]");
1348
1582
  if (stringCheck(config?.password)) {
1349
- log && info(`${logger}[config] ***`);
1583
+ log && log("[config]").info("***");
1350
1584
  return String(config?.password);
1351
1585
  }
1352
1586
  const pass = stringCheck(process.env.NILEDB_PASSWORD);
1353
1587
  if (pass) {
1354
- logger && info(`${logger}[NILEDB_PASSWORD] ***`);
1588
+ logger("[NILEDB_PASSWORD]").info("***");
1355
1589
  return pass;
1356
1590
  }
1357
1591
  const pg2 = stringCheck(process.env.NILEDB_POSTGRES_URL);
@@ -1369,15 +1603,15 @@ var getPassword = (cfg) => {
1369
1603
  );
1370
1604
  };
1371
1605
  var getDatabaseName = (cfg) => {
1372
- const { config, logger } = cfg;
1373
- const { info } = Logger(config, "[databaseName]");
1606
+ const { config } = cfg;
1607
+ const { info } = config.logger("[databaseName]");
1374
1608
  if (stringCheck(config?.databaseName)) {
1375
- logger && info(`${logger}[config] ${config?.databaseName}`);
1609
+ info(`[config] ${config?.databaseName}`);
1376
1610
  return String(config?.databaseName);
1377
1611
  }
1378
1612
  const name = stringCheck(process.env.NILEDB_NAME);
1379
1613
  if (name) {
1380
- logger && info(`${logger}[NILEDB_NAME] ${name}`);
1614
+ info(`[NILEDB_NAME] ${name}`);
1381
1615
  return name;
1382
1616
  }
1383
1617
  if (process.env.NILEDB_POSTGRES_URL) {
@@ -1392,50 +1626,52 @@ var getDatabaseName = (cfg) => {
1392
1626
  );
1393
1627
  };
1394
1628
  var getTenantId = (cfg) => {
1395
- const { config, logger } = cfg;
1396
- const { info } = Logger(config, "[tenantId]");
1629
+ const { config } = cfg;
1630
+ const { info } = config.logger("[tenantId]");
1397
1631
  if (stringCheck(config?.tenantId)) {
1398
- logger && info(`${logger}[config] ${config?.tenantId}`);
1632
+ info(`[config] ${config?.tenantId}`);
1399
1633
  return String(config?.tenantId);
1400
1634
  }
1401
1635
  if (stringCheck(process.env.NILEDB_TENANT)) {
1402
- logger && info(`${logger}[NILEDB_TENANT] ${process.env.NILEDB_TENANT}`);
1636
+ info(`[NILEDB_TENANT] ${process.env.NILEDB_TENANT}`);
1403
1637
  return String(process.env.NILEDB_TENANT);
1404
1638
  }
1405
1639
  return null;
1406
1640
  };
1407
1641
  function getDbHost(cfg) {
1408
- const { config, logger } = cfg;
1409
- const { info } = Logger(config, "[db.host]");
1642
+ const { config } = cfg;
1643
+ const logger = config.logger;
1644
+ const { info } = logger("[db.host]");
1410
1645
  if (stringCheck(config?.db && config.db.host)) {
1411
- logger && info(`${logger}[config] ${config?.db?.host}`);
1646
+ info(`[config] ${config?.db?.host}`);
1412
1647
  return String(config?.db?.host);
1413
1648
  }
1414
1649
  if (stringCheck(process.env.NILEDB_HOST)) {
1415
- logger && info(`${logger}[NILEDB_HOST] ${process.env.NILEDB_HOST}`);
1650
+ info(`[NILEDB_HOST] ${process.env.NILEDB_HOST}`);
1416
1651
  return process.env.NILEDB_HOST;
1417
1652
  }
1418
1653
  const pg2 = stringCheck(process.env.NILEDB_POSTGRES_URL);
1419
1654
  if (pg2) {
1420
1655
  try {
1421
1656
  const pgUrl = new URL(pg2);
1422
- logger && info(`${logger}[NILEDB_POSTGRES_URL] ${pgUrl.hostname}`);
1657
+ info(`[NILEDB_POSTGRES_URL] ${pgUrl.hostname}`);
1423
1658
  return pgUrl.hostname;
1424
1659
  } catch (e) {
1425
1660
  }
1426
1661
  }
1427
- logger && info(`${logger}[default] db.thenile.dev`);
1662
+ info("[default] db.thenile.dev");
1428
1663
  return "db.thenile.dev";
1429
1664
  }
1430
1665
  function getDbPort(cfg) {
1431
- const { config, logger } = cfg;
1432
- const { info } = Logger(config, "[db.port]");
1666
+ const { config } = cfg;
1667
+ const logger = config.logger;
1668
+ const { info } = logger("[db.port]");
1433
1669
  if (config?.db?.port && config.db.port != null) {
1434
- logger && info(`${logger}[config] ${config?.db.port}`);
1670
+ info(`[config] ${config?.db.port}`);
1435
1671
  return Number(config.db?.port);
1436
1672
  }
1437
1673
  if (stringCheck(process.env.NILEDB_PORT)) {
1438
- logger && info(`${logger}[NILEDB_PORT] ${process.env.NILEDB_PORT}`);
1674
+ info(`[NILEDB_PORT] ${process.env.NILEDB_PORT}`);
1439
1675
  return Number(process.env.NILEDB_PORT);
1440
1676
  }
1441
1677
  const pg2 = stringCheck(process.env.NILEDB_POSTGRES_URL);
@@ -1448,7 +1684,7 @@ function getDbPort(cfg) {
1448
1684
  } catch (e) {
1449
1685
  }
1450
1686
  }
1451
- logger && info(`${logger}[default] 5432`);
1687
+ info("[default] 5432");
1452
1688
  return 5432;
1453
1689
  }
1454
1690
  var logProtector = (logger) => {
@@ -1466,6 +1702,8 @@ var Config = class {
1466
1702
  routes;
1467
1703
  handlers;
1468
1704
  paths;
1705
+ extensionCtx;
1706
+ extensions;
1469
1707
  logger;
1470
1708
  /**
1471
1709
  * Stores the set tenant id from Server for use in sub classes
@@ -1499,15 +1737,19 @@ var Config = class {
1499
1737
  */
1500
1738
  routePrefix;
1501
1739
  db;
1502
- // api: ApiConfig;
1503
- constructor(config, logger) {
1504
- const envVarConfig = { config, logger };
1740
+ constructor(config) {
1505
1741
  this.routePrefix = config?.routePrefix ?? "/api";
1506
- this.secureCookies = getSecureCookies(envVarConfig);
1507
- this.callbackUrl = getCallbackUrl(envVarConfig);
1508
1742
  this.debug = config?.debug;
1509
1743
  this.origin = config?.origin;
1744
+ this.extensions = config?.extensions;
1745
+ this.extensionCtx = config?.extensionCtx;
1510
1746
  this.serverOrigin = config?.origin ?? "http://localhost:3000";
1747
+ this.logger = Logger(config);
1748
+ const envVarConfig = {
1749
+ config: { ...config, logger: this.logger }
1750
+ };
1751
+ this.secureCookies = getSecureCookies(envVarConfig);
1752
+ this.callbackUrl = getCallbackUrl(envVarConfig);
1511
1753
  this.apiUrl = getApiUrl(envVarConfig);
1512
1754
  const user = getUsername(envVarConfig);
1513
1755
  const password = getPassword(envVarConfig);
@@ -1574,7 +1816,6 @@ var Config = class {
1574
1816
  };
1575
1817
  this.tenantId = config?.tenantId;
1576
1818
  this.userId = config?.userId;
1577
- this.logger = config?.logger;
1578
1819
  }
1579
1820
  };
1580
1821
 
@@ -1608,6 +1849,9 @@ var Eventer = class {
1608
1849
  }
1609
1850
  };
1610
1851
  var eventer = new Eventer();
1852
+ var updateTenantId = (tenantId) => {
1853
+ eventer.publish("tenantId" /* Tenant */, tenantId);
1854
+ };
1611
1855
  var watchTenantId = (cb) => eventer.subscribe("tenantId" /* Tenant */, cb);
1612
1856
  var watchUserId = (cb) => eventer.subscribe("userId" /* User */, cb);
1613
1857
  var evictPool = (val) => {
@@ -1621,7 +1865,7 @@ var watchHeaders = (cb) => eventer.subscribe("headers" /* Headers */, cb);
1621
1865
 
1622
1866
  // src/db/PoolProxy.ts
1623
1867
  function createProxyForPool(pool, config) {
1624
- const { info, error } = Logger(config, "[pool]");
1868
+ const { info, error } = config.logger("[pool]");
1625
1869
  return new Proxy(pool, {
1626
1870
  get(target, property) {
1627
1871
  if (property === "query") {
@@ -1657,7 +1901,7 @@ var NileDatabase = class {
1657
1901
  config;
1658
1902
  timer;
1659
1903
  constructor(config, id) {
1660
- const { warn, info, debug } = Logger(config, "[NileInstance]");
1904
+ const { warn, info, debug } = config.logger("[NileInstance]");
1661
1905
  this.id = id;
1662
1906
  const poolConfig = {
1663
1907
  min: 0,
@@ -1686,7 +1930,7 @@ var NileDatabase = class {
1686
1930
  `${this.id}-${this.timer}`
1687
1931
  );
1688
1932
  afterCreate2(client, (err) => {
1689
- const { error } = Logger(config, "[after create callback]");
1933
+ const { error } = config.logger("[after create callback]");
1690
1934
  if (err) {
1691
1935
  clearTimeout(this.timer);
1692
1936
  error("after create failed", {
@@ -1714,7 +1958,7 @@ var NileDatabase = class {
1714
1958
  });
1715
1959
  }
1716
1960
  startTimeout() {
1717
- const { debug } = Logger(this.config, "[NileInstance]");
1961
+ const { debug } = this.config.logger("[NileInstance]");
1718
1962
  if (this.timer) {
1719
1963
  clearTimeout(this.timer);
1720
1964
  }
@@ -1729,7 +1973,7 @@ var NileDatabase = class {
1729
1973
  }, Number(this.config.db.idleTimeoutMillis) ?? 3e4);
1730
1974
  }
1731
1975
  shutdown() {
1732
- const { debug } = Logger(this.config, "[NileInstance]");
1976
+ const { debug } = this.config.logger("[NileInstance]");
1733
1977
  debug(`attempting to shut down ${this.id}`);
1734
1978
  clearTimeout(this.timer);
1735
1979
  this.pool.end(() => {
@@ -1739,7 +1983,7 @@ var NileDatabase = class {
1739
1983
  };
1740
1984
  var NileInstance_default = NileDatabase;
1741
1985
  function makeAfterCreate(config, id) {
1742
- const { error, warn, debug } = Logger(config, "[afterCreate]");
1986
+ const { error, warn, debug } = config.logger("[afterCreate]");
1743
1987
  return (conn, done) => {
1744
1988
  conn.on("error", function errorHandler(e) {
1745
1989
  error(`Connection ${id} was terminated by server`, {
@@ -1803,7 +2047,7 @@ var DBManager = class {
1803
2047
  watchEvictPool(this.poolWatcherFn);
1804
2048
  }
1805
2049
  poolWatcher = (config) => (id) => {
1806
- const { info, warn } = Logger(config, "[DBManager]");
2050
+ const { info, warn } = Logger(config)("[DBManager]");
1807
2051
  if (id && this.connections.has(id)) {
1808
2052
  info(`Removing ${id} from db connection pool.`);
1809
2053
  const connection = this.connections.get(id);
@@ -1814,7 +2058,7 @@ var DBManager = class {
1814
2058
  }
1815
2059
  };
1816
2060
  getConnection = (config) => {
1817
- const { info } = Logger(config, "[DBManager]");
2061
+ const { info } = Logger(config)("[DBManager]");
1818
2062
  const id = this.makeId(config.tenantId, config.userId);
1819
2063
  const existing = this.connections.get(id);
1820
2064
  info(`# of instances: ${this.connections.size}`);
@@ -1833,7 +2077,7 @@ var DBManager = class {
1833
2077
  return newOne.pool;
1834
2078
  };
1835
2079
  clear = (config) => {
1836
- const { info } = Logger(config, "[DBManager]");
2080
+ const { info } = Logger(config)("[DBManager]");
1837
2081
  info(`Clearing all connections ${this.connections.size}`);
1838
2082
  this.cleared = true;
1839
2083
  this.connections.forEach((connection) => {
@@ -1847,9 +2091,15 @@ var DBManager = class {
1847
2091
  var Auth = class {
1848
2092
  #logger;
1849
2093
  #config;
2094
+ /**
2095
+ * Create an Auth helper.
2096
+ *
2097
+ * @param config - runtime configuration used by the underlying fetch helpers
2098
+ * such as `serverOrigin`, `routePrefix` and default headers.
2099
+ */
1850
2100
  constructor(config) {
1851
2101
  this.#config = config;
1852
- this.#logger = Logger(config, "[auth]");
2102
+ this.#logger = config.logger("[auth]");
1853
2103
  }
1854
2104
  async getSession(rawResponse = false) {
1855
2105
  const res = await fetchSession(this.#config);
@@ -1867,7 +2117,7 @@ var Auth = class {
1867
2117
  }
1868
2118
  }
1869
2119
  async getCsrf(rawResponse = false) {
1870
- return await getCsrf(this.#config, rawResponse);
2120
+ return await obtainCsrf(this.#config, rawResponse);
1871
2121
  }
1872
2122
  async listProviders(rawResponse = false) {
1873
2123
  const res = await fetchProviders(this.#config);
@@ -1880,6 +2130,12 @@ var Auth = class {
1880
2130
  return res;
1881
2131
  }
1882
2132
  }
2133
+ /**
2134
+ * Sign the current user out by calling `/api/auth/signout`.
2135
+ *
2136
+ * The CSRF token is fetched automatically and the stored cookies are cleared
2137
+ * from the internal configuration once the request completes.
2138
+ */
1883
2139
  async signOut() {
1884
2140
  const csrfRes = await this.getCsrf();
1885
2141
  if (!("csrfToken" in csrfRes)) {
@@ -1937,16 +2193,71 @@ var Auth = class {
1937
2193
  return res;
1938
2194
  }
1939
2195
  try {
1940
- return await res.clone().json();
2196
+ const json = await res.clone().json();
2197
+ if (json && typeof json === "object" && "tenants" in json) {
2198
+ const tenantId = json.tenants[0];
2199
+ if (tenantId) {
2200
+ updateTenantId(tenantId);
2201
+ }
2202
+ }
2203
+ return json;
1941
2204
  } catch {
1942
2205
  return res;
1943
2206
  }
1944
2207
  }
2208
+ /**
2209
+ * Request a password reset email.
2210
+ *
2211
+ * Sends a `POST` to `/api/auth/password-reset` with the provided email and
2212
+ * optional callback information. The endpoint responds with a redirect URL
2213
+ * which is returned as a {@link Response} object.
2214
+ */
2215
+ async forgotPassword(req) {
2216
+ let email = "";
2217
+ const defaults = defaultCallbackUrl({
2218
+ config: this.#config
2219
+ });
2220
+ let callbackUrl = defaults.callbackUrl;
2221
+ let redirectUrl = defaults.redirectUrl;
2222
+ if ("email" in req) {
2223
+ email = req.email;
2224
+ }
2225
+ if ("callbackUrl" in req) {
2226
+ callbackUrl = req.callbackUrl ? req.callbackUrl : null;
2227
+ }
2228
+ if ("redirectUrl" in req) {
2229
+ redirectUrl = req.redirectUrl ? req.redirectUrl : null;
2230
+ }
2231
+ const body = JSON.stringify({
2232
+ email,
2233
+ redirectUrl,
2234
+ callbackUrl
2235
+ });
2236
+ const data = await fetchResetPassword(
2237
+ this.#config,
2238
+ "POST",
2239
+ body,
2240
+ new URLSearchParams(),
2241
+ false
2242
+ );
2243
+ return data;
2244
+ }
2245
+ /**
2246
+ * Complete a password reset.
2247
+ *
2248
+ * This workflow expects a token obtained from {@link forgotPassword}. The
2249
+ * function performs a POST/GET/PUT sequence against
2250
+ * `/api/auth/password-reset` as described in the OpenAPI specification.
2251
+ *
2252
+ * @param req - either a {@link Request} with a JSON body or an object
2253
+ * containing the necessary fields.
2254
+ */
1945
2255
  async resetPassword(req) {
1946
2256
  let email = "";
1947
2257
  let password = "";
1948
- let callbackUrl = null;
1949
- let redirectUrl = null;
2258
+ const defaults = defaultCallbackUrl({ config: this.#config });
2259
+ let callbackUrl = defaults.callbackUrl;
2260
+ let redirectUrl = defaults.redirectUrl;
1950
2261
  if (req instanceof Request) {
1951
2262
  const body2 = await req.json();
1952
2263
  email = body2.email;
@@ -1975,19 +2286,6 @@ var Auth = class {
1975
2286
  redirectUrl = req.redirectUrl ? req.redirectUrl : null;
1976
2287
  }
1977
2288
  }
1978
- const fallbackCb = parseCallback(this.#config.headers);
1979
- if (fallbackCb) {
1980
- const [, value] = fallbackCb.split("=");
1981
- if (value) {
1982
- const parsedUrl = decodeURIComponent(value);
1983
- if (!redirectUrl) {
1984
- redirectUrl = `${new URL(parsedUrl).origin}${"/auth/reset-password" /* PASSWORD_RESET */}`;
1985
- }
1986
- }
1987
- if (!callbackUrl) {
1988
- callbackUrl = value;
1989
- }
1990
- }
1991
2289
  await this.getCsrf();
1992
2290
  const body = JSON.stringify({
1993
2291
  email,
@@ -2043,6 +2341,12 @@ var Auth = class {
2043
2341
  updateHeaders(updatedHeaders);
2044
2342
  return res;
2045
2343
  }
2344
+ /**
2345
+ * Low level helper used by {@link signIn} to complete provider flows.
2346
+ *
2347
+ * Depending on the provider this issues either a GET or POST request to
2348
+ * `/api/auth/callback/{provider}` via {@link fetchCallback}.
2349
+ */
2046
2350
  async callback(provider, body) {
2047
2351
  if (body instanceof Request) {
2048
2352
  this.#config.headers = body.headers;
@@ -2107,6 +2411,9 @@ var Auth = class {
2107
2411
  }
2108
2412
  info(`Obtaining providers for ${email}`);
2109
2413
  info(`Attempting sign in with email ${email}`);
2414
+ if (!email) {
2415
+ throw new Error("Email missing from payload, unable to sign in");
2416
+ }
2110
2417
  const body = JSON.stringify({
2111
2418
  email,
2112
2419
  password,
@@ -2128,7 +2435,7 @@ var Auth = class {
2128
2435
  }
2129
2436
  if (urlError) {
2130
2437
  error("Unable to log user in", { error: urlError });
2131
- return void 0;
2438
+ return new Response(urlError, { status: signInRes.status });
2132
2439
  }
2133
2440
  }
2134
2441
  if (!token) {
@@ -2206,11 +2513,25 @@ function parseResetToken(headers) {
2206
2513
  const [, token] = /((__Secure-)?nile\.reset=[^;]+)/.exec(authCookie) ?? [];
2207
2514
  return token;
2208
2515
  }
2516
+ function defaultCallbackUrl({ config }) {
2517
+ let cb = null;
2518
+ let redirect = null;
2519
+ const fallbackCb = parseCallback(config.headers);
2520
+ if (fallbackCb) {
2521
+ const [, value] = fallbackCb.split("=");
2522
+ cb = decodeURIComponent(value);
2523
+ if (value) {
2524
+ redirect = `${new URL(cb).origin}${"/auth/reset-password" /* PASSWORD_RESET */}`;
2525
+ }
2526
+ }
2527
+ return { callbackUrl: cb, redirectUrl: redirect };
2528
+ }
2209
2529
 
2210
- // src/auth/getCsrf.ts
2211
- async function getCsrf(config, rawResponse = false) {
2530
+ // src/auth/obtainCsrf.ts
2531
+ async function obtainCsrf(config, rawResponse = false) {
2212
2532
  const res = await fetchCsrf(config);
2213
2533
  const csrfCook = parseCSRF(res.headers);
2534
+ const h = new Headers();
2214
2535
  if (csrfCook) {
2215
2536
  const [, value] = csrfCook.split("=");
2216
2537
  const [token] = decodeURIComponent(value).split("|");
@@ -2222,7 +2543,8 @@ async function getCsrf(config, rawResponse = false) {
2222
2543
  parseToken(res.headers)
2223
2544
  ].filter(Boolean).join("; ");
2224
2545
  config.headers.set("cookie", cookie);
2225
- updateHeaders(new Headers({ cookie }));
2546
+ h.set("cookie", cookie);
2547
+ updateHeaders(h);
2226
2548
  }
2227
2549
  if (!rawResponse) {
2228
2550
  return { csrfToken: token };
@@ -2259,10 +2581,23 @@ async function getCsrf(config, rawResponse = false) {
2259
2581
  var Users = class {
2260
2582
  #config;
2261
2583
  #logger;
2584
+ /**
2585
+ * Create a new Users helper.
2586
+ * @param config - The configuration used for requests.
2587
+ */
2262
2588
  constructor(config) {
2263
2589
  this.#config = config;
2264
- this.#logger = Logger(config, "[me]");
2590
+ this.#logger = config.logger("[me]");
2265
2591
  }
2592
+ /**
2593
+ * Update the current user via `PUT /api/me`.
2594
+ *
2595
+ * The OpenAPI description for this endpoint can be found in
2596
+ * `packages/server/src/api/routes/me/index.ts` under `updateSelf`.
2597
+ *
2598
+ * @param req - Partial user fields to send.
2599
+ * @param [rawResponse] - When `true`, return the raw {@link Response}.
2600
+ */
2266
2601
  async updateSelf(req, rawResponse) {
2267
2602
  const res = await fetchMe(this.#config, "PUT", JSON.stringify(req));
2268
2603
  if (rawResponse) {
@@ -2274,6 +2609,13 @@ var Users = class {
2274
2609
  return res;
2275
2610
  }
2276
2611
  }
2612
+ /**
2613
+ * Remove the current user using `DELETE /api/me`.
2614
+ *
2615
+ * After the request the authentication headers are cleared with
2616
+ * {@link updateHeaders}. The OpenAPI docs for this route are in
2617
+ * `packages/server/src/api/routes/me/index.ts` under `removeSelf`.
2618
+ */
2277
2619
  async removeSelf() {
2278
2620
  const me = await this.getSelf();
2279
2621
  if ("id" in me) {
@@ -2294,50 +2636,71 @@ var Users = class {
2294
2636
  return res;
2295
2637
  }
2296
2638
  }
2297
- async verifySelf(bypassEmail = process.env.NODE_ENV !== "production", rawResponse = false) {
2639
+ async verifySelf(options, rawResponse = false) {
2640
+ const bypassEmail = typeof options === "object" ? options.bypassEmail ?? process.env.NODE_ENV !== "production" : process.env.NODE_ENV !== "production";
2641
+ const callbackUrl = typeof options === "object" ? options.callbackUrl : defaultCallbackUrl2(this.#config).callbackUrl;
2642
+ let res;
2298
2643
  try {
2299
2644
  const me = await this.getSelf();
2300
2645
  if (me instanceof Response) {
2301
2646
  return me;
2302
2647
  }
2303
- const res = await verifyEmailAddress(this.#config, me);
2648
+ res = await verifyEmailAddress(this.#config, me, String(callbackUrl));
2304
2649
  return res;
2305
2650
  } catch {
2306
- this.#logger?.warn(
2307
- "Unable to verify email. The current user's email will be set to verified any way. Be sure to configure emails for production."
2308
- );
2651
+ const message = "Unable to verify email.";
2652
+ this.#logger?.warn(message);
2653
+ res = new Response(message, { status: 400 });
2309
2654
  }
2310
2655
  if (bypassEmail) {
2311
- return await this.updateSelf({ emailVerified: true }, rawResponse);
2656
+ res = this.updateSelf({ emailVerified: true }, rawResponse);
2312
2657
  }
2313
2658
  this.#logger.error(
2314
2659
  "Unable to verify email address. Configure your SMTP server in the console."
2315
2660
  );
2316
- return void 0;
2661
+ return res;
2317
2662
  }
2318
2663
  };
2319
- async function verifyEmailAddress(config, user) {
2664
+ async function verifyEmailAddress(config, user, callback) {
2320
2665
  config.headers.set("content-type", "application/x-www-form-urlencoded");
2321
- const { csrfToken } = await getCsrf(config);
2666
+ const { csrfToken } = await obtainCsrf(config);
2667
+ const defaults = defaultCallbackUrl2(config);
2668
+ const callbackUrl = callback ?? String(defaults.callbackUrl);
2322
2669
  const res = await fetchVerifyEmail(
2323
2670
  config,
2324
2671
  "POST",
2325
- new URLSearchParams({ csrfToken, email: user.email }).toString()
2672
+ new URLSearchParams({
2673
+ csrfToken,
2674
+ email: user.email,
2675
+ callbackUrl
2676
+ }).toString()
2326
2677
  );
2327
2678
  if (res.status > 299) {
2328
2679
  throw new Error(await res.text());
2329
2680
  }
2330
2681
  return res;
2331
2682
  }
2683
+ function defaultCallbackUrl2(config) {
2684
+ let cb = null;
2685
+ const fallbackCb = parseCallback(config.headers);
2686
+ if (fallbackCb) {
2687
+ const [, value] = fallbackCb.split("=");
2688
+ cb = decodeURIComponent(value);
2689
+ }
2690
+ return { callbackUrl: cb };
2691
+ }
2332
2692
 
2333
2693
  // src/tenants/index.ts
2334
2694
  var Tenants = class {
2335
- #logger;
2336
2695
  #config;
2337
2696
  constructor(config) {
2338
- this.#logger = Logger(config, "[tenants]");
2339
2697
  this.#config = config;
2340
2698
  }
2699
+ /**
2700
+ * Create a new tenant using `POST /api/tenants`.
2701
+ * See `packages/server/src/api/routes/tenants/POST.ts` for the
2702
+ * `createTenant` operation definition.
2703
+ */
2341
2704
  async create(req, rawResponse) {
2342
2705
  let res;
2343
2706
  if (typeof req === "string") {
@@ -2358,6 +2721,11 @@ var Tenants = class {
2358
2721
  return res;
2359
2722
  }
2360
2723
  }
2724
+ /**
2725
+ * Remove a tenant via `DELETE /api/tenants/{tenantId}`.
2726
+ *
2727
+ * @param req - The tenant to remove or context containing the id.
2728
+ */
2361
2729
  async delete(req) {
2362
2730
  if (typeof req === "string") {
2363
2731
  this.#config.tenantId = req;
@@ -2368,6 +2736,12 @@ var Tenants = class {
2368
2736
  const res = await fetchTenant(this.#config, "DELETE");
2369
2737
  return res;
2370
2738
  }
2739
+ /**
2740
+ * Fetch details for a tenant using `GET /api/tenants/{tenantId}`.
2741
+ *
2742
+ * @param req - Tenant identifier or context.
2743
+ * @param [rawResponse] - When true, return the raw {@link Response}.
2744
+ */
2371
2745
  async get(req, rawResponse) {
2372
2746
  if (typeof req === "string") {
2373
2747
  this.#config.tenantId = req;
@@ -2402,6 +2776,10 @@ var Tenants = class {
2402
2776
  return res;
2403
2777
  }
2404
2778
  }
2779
+ /**
2780
+ * List tenants for the current user via `GET /api/tenants`.
2781
+ * See `packages/server/src/api/routes/tenants/GET.ts` for details.
2782
+ */
2405
2783
  async list(req) {
2406
2784
  const res = await fetchTenantsByUser(this.#config);
2407
2785
  if (req === true) {
@@ -2413,6 +2791,11 @@ var Tenants = class {
2413
2791
  return res;
2414
2792
  }
2415
2793
  }
2794
+ /**
2795
+ * Leave the current tenant using `DELETE /api/tenants/{tenantId}/users/{userId}`.
2796
+ *
2797
+ * @param [req] - Optionally specify the tenant id to leave.
2798
+ */
2416
2799
  async leaveTenant(req) {
2417
2800
  const me = await fetchMe(this.#config);
2418
2801
  try {
@@ -2438,6 +2821,12 @@ var Tenants = class {
2438
2821
  const res = await fetchTenantUser(this.#config, "PUT");
2439
2822
  return responseHandler(res, rawResponse);
2440
2823
  }
2824
+ /**
2825
+ * Remove a user from a tenant with `DELETE /api/tenants/{tenantId}/users/{userId}`.
2826
+ *
2827
+ * @param req - User and tenant identifiers or context.
2828
+ * @param [rawResponse] - When true, return the raw {@link Response}.
2829
+ */
2441
2830
  async removeMember(req, rawResponse) {
2442
2831
  this.#handleContext(req);
2443
2832
  const res = await fetchTenantUser(this.#config, "DELETE");
@@ -2451,6 +2840,88 @@ var Tenants = class {
2451
2840
  rawResponse || typeof req === "boolean" && req
2452
2841
  );
2453
2842
  }
2843
+ /**
2844
+ * List invites for the current tenant via `GET /api/tenants/{tenantId}/invites`.
2845
+ */
2846
+ async invites() {
2847
+ const res = await fetchInvites(this.#config);
2848
+ return responseHandler(res);
2849
+ }
2850
+ async invite(req, rawResponse) {
2851
+ const { csrfToken } = await obtainCsrf(this.#config);
2852
+ const defaults = defaultCallbackUrl3(this.#config);
2853
+ let identifier = req;
2854
+ let callbackUrl = defaults.callbackUrl;
2855
+ let redirectUrl = defaults.redirectUrl;
2856
+ if (typeof req === "object") {
2857
+ if ("email" in req) {
2858
+ identifier = req.email;
2859
+ }
2860
+ if ("callbackUrl" in req) {
2861
+ callbackUrl = req.callbackUrl ? req.callbackUrl : "";
2862
+ }
2863
+ if ("redirectUrl" in req) {
2864
+ redirectUrl = req.redirectUrl ? req.redirectUrl : "";
2865
+ }
2866
+ }
2867
+ this.#config.headers.set(
2868
+ "Content-Type",
2869
+ "application/x-www-form-urlencoded"
2870
+ );
2871
+ const res = await fetchInvite(
2872
+ this.#config,
2873
+ "POST",
2874
+ new URLSearchParams({
2875
+ identifier,
2876
+ csrfToken,
2877
+ callbackUrl,
2878
+ redirectUrl
2879
+ }).toString()
2880
+ );
2881
+ return responseHandler(res, rawResponse);
2882
+ }
2883
+ /**
2884
+ * Accept an invite using `PUT /api/tenants/{tenantId}/invite`.
2885
+ *
2886
+ * @param req - Identifier and token from the invite email.
2887
+ * @param [rawResponse] - When true, return the raw {@link Response}.
2888
+ */
2889
+ async acceptInvite(req, rawResponse) {
2890
+ if (!req) {
2891
+ throw new Error("The identifier and token are required.");
2892
+ }
2893
+ const { identifier, token } = req;
2894
+ const defaults = defaultCallbackUrl3(this.#config);
2895
+ const callbackUrl = String(defaults.callbackUrl);
2896
+ const res = await fetchInvite(
2897
+ this.#config,
2898
+ "PUT",
2899
+ new URLSearchParams({
2900
+ identifier,
2901
+ token,
2902
+ callbackUrl
2903
+ }).toString()
2904
+ );
2905
+ return responseHandler(res, rawResponse);
2906
+ }
2907
+ /**
2908
+ * Delete a pending invite using `DELETE /api/tenants/{tenantId}/invite/{inviteId}`.
2909
+ *
2910
+ * @param req - Identifier of the invite to remove.
2911
+ */
2912
+ async deleteInvite(req) {
2913
+ let id = "";
2914
+ if (typeof req === "object") {
2915
+ id = req.id;
2916
+ } else {
2917
+ id = req;
2918
+ }
2919
+ if (!id) {
2920
+ throw new Error("An invite id is required.");
2921
+ }
2922
+ const res = await fetchInvite(this.#config, "DELETE", id);
2923
+ return responseHandler(res, true);
2924
+ }
2454
2925
  #handleContext(req) {
2455
2926
  if (typeof req === "object") {
2456
2927
  if ("tenantId" in req) {
@@ -2472,31 +2943,47 @@ async function responseHandler(res, rawResponse) {
2472
2943
  return res;
2473
2944
  }
2474
2945
  }
2946
+ function defaultCallbackUrl3(config) {
2947
+ let cb = null;
2948
+ let redirect = null;
2949
+ const fallbackCb = parseCallback(config.headers);
2950
+ if (fallbackCb) {
2951
+ const [, value] = fallbackCb.split("=");
2952
+ cb = decodeURIComponent(value);
2953
+ if (value) {
2954
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace(
2955
+ "{tenantId}",
2956
+ String(config.tenantId)
2957
+ )}`;
2958
+ }
2959
+ }
2960
+ return { callbackUrl: cb, redirectUrl: redirect };
2961
+ }
2475
2962
 
2476
2963
  // src/api/handlers/withContext/index.ts
2477
2964
  function handlersWithContext(config) {
2478
- const GET6 = GETTER(config.routes, config);
2479
- const POST5 = POSTER(config.routes, config);
2480
- const DELETE4 = DELETER(config.routes, config);
2481
- const PUT5 = PUTER(config.routes, config);
2965
+ const GET7 = GETTER(config.routes, config);
2966
+ const POST6 = POSTER(config.routes, config);
2967
+ const DELETE5 = DELETER(config.routes, config);
2968
+ const PUT6 = PUTER(config.routes, config);
2482
2969
  return {
2483
2970
  GET: async (req) => {
2484
- const response = await GET6(req);
2971
+ const response = await GET7(req);
2485
2972
  const updatedConfig = updateConfig(response, config);
2486
2973
  return { response, nile: new Server(updatedConfig) };
2487
2974
  },
2488
2975
  POST: async (req) => {
2489
- const response = await POST5(req);
2976
+ const response = await POST6(req);
2490
2977
  const updatedConfig = updateConfig(response, config);
2491
2978
  return { response, nile: new Server(updatedConfig) };
2492
2979
  },
2493
2980
  DELETE: async (req) => {
2494
- const response = await DELETE4(req);
2981
+ const response = await DELETE5(req);
2495
2982
  const updatedConfig = updateConfig(response, config);
2496
2983
  return { response, nile: new Server(updatedConfig) };
2497
2984
  },
2498
2985
  PUT: async (req) => {
2499
- const response = await PUT5(req);
2986
+ const response = await PUT6(req);
2500
2987
  const updatedConfig = updateConfig(response, config);
2501
2988
  return { response, nile: new Server(updatedConfig) };
2502
2989
  }
@@ -2505,31 +2992,126 @@ function handlersWithContext(config) {
2505
2992
  function updateConfig(response, config) {
2506
2993
  let origin = "http://localhost:3000";
2507
2994
  let headers = null;
2508
- if (response?.status === 302) {
2509
- const location = response.headers.get("location");
2510
- if (location) {
2511
- const urlLocation = new URL(location);
2512
- origin = urlLocation.origin;
2995
+ if (response instanceof Response) {
2996
+ if (response?.status === 302) {
2997
+ const location = response.headers.get("location");
2998
+ if (location) {
2999
+ const urlLocation = new URL(location);
3000
+ origin = urlLocation.origin;
3001
+ }
2513
3002
  }
2514
- }
2515
- const setCookies = [];
2516
- if (response?.headers) {
2517
- for (const [key14, value] of response.headers) {
2518
- if (key14.toLowerCase() === "set-cookie") {
2519
- setCookies.push(value);
3003
+ const setCookies = [];
3004
+ if (response?.headers) {
3005
+ for (const [key17, value] of response.headers) {
3006
+ if (key17.toLowerCase() === "set-cookie") {
3007
+ setCookies.push(value);
3008
+ }
2520
3009
  }
2521
3010
  }
2522
- }
2523
- if (setCookies.length > 0) {
2524
- const cookieHeader = setCookies.map((cookieStr) => cookieStr.split(";")[0]).join("; ");
2525
- headers = new Headers({ cookie: cookieHeader });
3011
+ if (setCookies.length > 0) {
3012
+ const cookieHeader = setCookies.map((cookieStr) => cookieStr.split(";")[0]).join("; ");
3013
+ headers = new Headers({ cookie: cookieHeader });
3014
+ }
2526
3015
  }
2527
3016
  return {
2528
3017
  ...config,
2529
3018
  origin,
2530
- headers: headers ?? void 0
3019
+ headers: headers ?? void 0,
3020
+ preserveHeaders: true
3021
+ };
3022
+ }
3023
+
3024
+ // src/api/utils/extensions.ts
3025
+ function getRequestConfig(params) {
3026
+ if (typeof params[1] === "object") {
3027
+ return params[1];
3028
+ }
3029
+ return {};
3030
+ }
3031
+ function bindRunExtensions(instance) {
3032
+ return async function runExtensions(toRun, config, params, _init) {
3033
+ const { debug } = config.logger("[EXTENSIONS]");
3034
+ const extensionConfig = getRequestConfig(
3035
+ Array.isArray(params) ? params : [null, params]
3036
+ );
3037
+ if (config.extensions) {
3038
+ for (const create2 of config.extensions) {
3039
+ if (typeof create2 !== "function") {
3040
+ continue;
3041
+ }
3042
+ const ext = create2(instance);
3043
+ if (extensionConfig.disableExtensions?.includes(ext.id)) {
3044
+ continue;
3045
+ }
3046
+ if (ext.onHandleRequest && toRun === "onHandleRequest" /* onHandleRequest */) {
3047
+ const result = await ext.onHandleRequest(
3048
+ ...Array.isArray(params) ? params : [params]
3049
+ );
3050
+ if (result != null) {
3051
+ return result;
3052
+ }
3053
+ continue;
3054
+ }
3055
+ const [param] = Array.isArray(params) ? params : [params];
3056
+ if (ext.onRequest && toRun === "onRequest" /* onRequest */) {
3057
+ const previousContext = instance.getContext();
3058
+ if (previousContext.preserveHeaders) {
3059
+ instance.setContext({ preserveHeaders: false });
3060
+ }
3061
+ if (!_init) {
3062
+ continue;
3063
+ }
3064
+ await ext.onRequest(_init.request);
3065
+ const updatedContext = instance.getContext();
3066
+ if (updatedContext?.headers) {
3067
+ const cookie = updatedContext.headers.get("cookie");
3068
+ if (cookie && param.headers) {
3069
+ param.headers.set(
3070
+ "cookie",
3071
+ mergeCookies(
3072
+ previousContext.preserveHeaders ? previousContext.headers?.get("cookie") : null,
3073
+ updatedContext.headers.get("cookie")
3074
+ )
3075
+ );
3076
+ }
3077
+ if (updatedContext.tenantId && param.headers) {
3078
+ param.headers.set(
3079
+ TENANT_COOKIE,
3080
+ String(updatedContext.headers.get(TENANT_COOKIE))
3081
+ );
3082
+ }
3083
+ }
3084
+ debug(`${ext.id ?? create2.name} ran onRequest`);
3085
+ continue;
3086
+ }
3087
+ if (ext.onResponse && toRun === "onResponse" /* onResponse */) {
3088
+ const result = await ext.onResponse(param);
3089
+ if (result != null) {
3090
+ return result;
3091
+ }
3092
+ continue;
3093
+ }
3094
+ }
3095
+ }
3096
+ return void 0;
2531
3097
  };
2532
3098
  }
3099
+ function buildExtensionConfig(instance) {
3100
+ return {
3101
+ runExtensions: bindRunExtensions(instance)
3102
+ };
3103
+ }
3104
+ function mergeCookies(...cookieStrings) {
3105
+ const cookieMap = /* @__PURE__ */ new Map();
3106
+ for (const str of cookieStrings) {
3107
+ if (!str) continue;
3108
+ for (const part of str.split(";")) {
3109
+ const [key17, value] = part.split("=").map((s) => s.trim());
3110
+ if (key17 && value) cookieMap.set(key17, value);
3111
+ }
3112
+ }
3113
+ return [...cookieMap.entries()].map(([k, v]) => `${k}=${v}`).join("; ");
3114
+ }
2533
3115
 
2534
3116
  // src/Server.ts
2535
3117
  var Server = class {
@@ -2538,11 +3120,14 @@ var Server = class {
2538
3120
  auth;
2539
3121
  #config;
2540
3122
  #handlers;
2541
- #paths;
2542
3123
  #manager;
2543
3124
  #headers;
3125
+ #preserveHeaders;
2544
3126
  constructor(config) {
2545
- this.#config = new Config(config, "[initial config]");
3127
+ this.#config = new Config({
3128
+ ...config,
3129
+ extensionCtx: buildExtensionConfig(this)
3130
+ });
2546
3131
  watchTenantId((tenantId) => {
2547
3132
  if (tenantId !== this.#config.tenantId) {
2548
3133
  this.#config.tenantId = tenantId;
@@ -2563,13 +3148,24 @@ var Server = class {
2563
3148
  ...this.#config.handlers,
2564
3149
  withContext: handlersWithContext(this.#config)
2565
3150
  };
2566
- this.#paths = this.#config.paths;
3151
+ this.#preserveHeaders = config?.preserveHeaders ?? false;
2567
3152
  this.#config.tenantId = getTenantId({ config: this.#config });
2568
3153
  this.#manager = new DBManager(this.#config);
2569
3154
  this.#handleHeaders(config);
2570
3155
  this.users = new Users(this.#config);
2571
3156
  this.tenants = new Tenants(this.#config);
2572
3157
  this.auth = new Auth(this.#config);
3158
+ if (config?.extensions) {
3159
+ for (const create2 of config.extensions) {
3160
+ if (typeof create2 !== "function") {
3161
+ continue;
3162
+ }
3163
+ const ext = create2(this);
3164
+ if (ext.onConfigure) {
3165
+ ext.onConfigure();
3166
+ }
3167
+ }
3168
+ }
2573
3169
  }
2574
3170
  get db() {
2575
3171
  const pool = this.#manager.getConnection(this.#config);
@@ -2579,6 +3175,28 @@ var Server = class {
2579
3175
  }
2580
3176
  });
2581
3177
  }
3178
+ get logger() {
3179
+ return this.#config.logger;
3180
+ }
3181
+ get extensions() {
3182
+ return {
3183
+ remove: async (id) => {
3184
+ if (!this.#config.extensions) return;
3185
+ const resolved = this.#config.extensions.map((ext) => ext(this));
3186
+ const index = resolved.findIndex((ext) => ext.id === id);
3187
+ if (index !== -1) {
3188
+ this.#config.extensions.splice(index, 1);
3189
+ }
3190
+ return resolved;
3191
+ },
3192
+ add: (extension) => {
3193
+ if (!this.#config.extensions) {
3194
+ this.#config.extensions = [];
3195
+ }
3196
+ this.#config.extensions.push(extension);
3197
+ }
3198
+ };
3199
+ }
2582
3200
  /**
2583
3201
  * A convenience function that applies a config and ensures whatever was passed is set properly
2584
3202
  */
@@ -2594,12 +3212,15 @@ var Server = class {
2594
3212
  this.#reset();
2595
3213
  return this;
2596
3214
  }
2597
- getPaths() {
2598
- return this.#paths;
2599
- }
2600
3215
  get handlers() {
2601
3216
  return this.#handlers;
2602
3217
  }
3218
+ get paths() {
3219
+ return this.#config.paths;
3220
+ }
3221
+ set paths(paths) {
3222
+ this.#config.paths = paths;
3223
+ }
2603
3224
  /**
2604
3225
  * Allow the setting of headers from a req or header object.
2605
3226
  * Makes it possible to handle REST requests easily
@@ -2607,7 +3228,40 @@ var Server = class {
2607
3228
  * @param req
2608
3229
  * @returns undefined
2609
3230
  */
2610
- setContext(req) {
3231
+ setContext = (req, ...remaining) => {
3232
+ let ok = false;
3233
+ if (req && typeof req === "object" && "tenantId" in req) {
3234
+ ok = true;
3235
+ this.#config.tenantId = req.tenantId;
3236
+ }
3237
+ if (req && typeof req === "object" && "userId" in req) {
3238
+ ok = true;
3239
+ this.#config.userId = req.userId;
3240
+ }
3241
+ if (req && typeof req === "object" && "preserveHeaders" in req) {
3242
+ ok = true;
3243
+ this.#preserveHeaders = Boolean(req.preserveHeaders);
3244
+ }
3245
+ let atLeastOne = false;
3246
+ if (this.#config?.extensions) {
3247
+ for (const create2 of this.#config.extensions) {
3248
+ if (typeof create2 !== "function") {
3249
+ continue;
3250
+ }
3251
+ const ext = create2(this);
3252
+ if (typeof ext.onSetContext === "function") {
3253
+ if (req) {
3254
+ ext.onSetContext(req, ...remaining);
3255
+ atLeastOne = true;
3256
+ } else {
3257
+ this.#config.logger("extension").warn("attempted to call onSetContext without a value");
3258
+ }
3259
+ }
3260
+ }
3261
+ }
3262
+ if (atLeastOne) {
3263
+ return;
3264
+ }
2611
3265
  try {
2612
3266
  if (req instanceof Headers) {
2613
3267
  this.#handleHeaders(req);
@@ -2620,38 +3274,44 @@ var Server = class {
2620
3274
  }
2621
3275
  } catch {
2622
3276
  }
2623
- let ok = false;
2624
- if (req && typeof req === "object" && "tenantId" in req) {
2625
- ok = true;
2626
- this.#config.tenantId = req.tenantId;
2627
- }
2628
- if (req && typeof req === "object" && "userId" in req) {
2629
- ok = true;
2630
- this.#config.userId = req.userId;
2631
- }
2632
3277
  if (ok) {
2633
3278
  return;
2634
3279
  }
2635
3280
  if (typeof req === "object") {
2636
- const headers = new Headers(req);
2637
- if (headers) {
2638
- this.#handleHeaders(headers);
2639
- this.#reset();
2640
- return;
3281
+ try {
3282
+ const headers = new Headers(req);
3283
+ if (headers) {
3284
+ this.#handleHeaders(headers);
3285
+ this.#reset();
3286
+ return;
3287
+ }
3288
+ } catch {
2641
3289
  }
2642
3290
  }
2643
- const { warn } = Logger(this.#config, "[API]");
3291
+ const { warn } = Logger(this.#config)("[API]");
2644
3292
  if (warn) {
2645
3293
  warn(
2646
3294
  "Set context expects a Request, Header instance or an object of Record<string, string>"
2647
3295
  );
2648
3296
  }
2649
- }
3297
+ };
2650
3298
  getContext() {
3299
+ if (this.#config?.extensions) {
3300
+ for (const create2 of this.#config.extensions) {
3301
+ if (typeof create2 !== "function") {
3302
+ continue;
3303
+ }
3304
+ const ext = create2(this);
3305
+ if (typeof ext.onGetContext === "function") {
3306
+ return ext.onGetContext();
3307
+ }
3308
+ }
3309
+ }
2651
3310
  return {
2652
3311
  headers: this.#headers,
2653
- userId: this.#config.userId,
2654
- tenantId: this.#config.tenantId
3312
+ userId: this.#config?.userId,
3313
+ tenantId: this.#config?.tenantId,
3314
+ preserveHeaders: this.#preserveHeaders
2655
3315
  };
2656
3316
  }
2657
3317
  /**
@@ -2667,33 +3327,35 @@ var Server = class {
2667
3327
  } else if (config?.headers) {
2668
3328
  headers = config?.headers;
2669
3329
  if (config && config.origin) {
2670
- this.#headers.set(X_NILE_ORIGIN, config.origin);
3330
+ this.#headers.set(HEADER_ORIGIN, config.origin);
2671
3331
  }
2672
3332
  if (config && config.secureCookies != null) {
2673
- this.#headers.set(X_NILE_SECURECOOKIES, String(config.secureCookies));
3333
+ this.#headers.set(HEADER_SECURE_COOKIES, String(config.secureCookies));
2674
3334
  }
2675
3335
  }
2676
3336
  if (headers instanceof Headers) {
2677
- headers.forEach((value, key14) => {
2678
- updates.push([key14.toLowerCase(), value]);
3337
+ headers.forEach((value, key17) => {
3338
+ updates.push([key17.toLowerCase(), value]);
2679
3339
  });
2680
3340
  } else {
2681
- for (const [key14, value] of Object.entries(headers ?? {})) {
2682
- updates.push([key14.toLowerCase(), value]);
3341
+ for (const [key17, value] of Object.entries(headers ?? {})) {
3342
+ updates.push([key17.toLowerCase(), value]);
2683
3343
  }
2684
3344
  }
2685
3345
  const merged = {};
2686
- this.#headers?.forEach((value, key14) => {
2687
- if (key14.toLowerCase() !== "cookie") {
2688
- merged[key14.toLowerCase()] = value;
3346
+ this.#config.tenantId = getTenantFromHttp(this.#headers, this.#config);
3347
+ this.#headers?.forEach((value, key17) => {
3348
+ if (key17.toLowerCase() !== "cookie") {
3349
+ merged[key17.toLowerCase()] = value;
2689
3350
  }
2690
3351
  });
2691
- for (const [key14, value] of updates) {
2692
- merged[key14] = value;
3352
+ for (const [key17, value] of updates) {
3353
+ merged[key17] = value;
2693
3354
  }
2694
- for (const [key14, value] of Object.entries(merged)) {
2695
- this.#headers.set(key14, value);
3355
+ for (const [key17, value] of Object.entries(merged)) {
3356
+ this.#headers.set(key17, value);
2696
3357
  }
3358
+ this.#config.logger("[handleHeaders]").debug(JSON.stringify(merged));
2697
3359
  this.#config.headers = this.#headers;
2698
3360
  }
2699
3361
  /**
@@ -2701,6 +3363,7 @@ var Server = class {
2701
3363
  */
2702
3364
  #reset = () => {
2703
3365
  this.#config.headers = this.#headers ?? new Headers();
3366
+ this.#config.extensionCtx = buildExtensionConfig(this);
2704
3367
  this.users = new Users(this.#config);
2705
3368
  this.tenants = new Tenants(this.#config);
2706
3369
  this.auth = new Auth(this.#config);
@@ -2715,11 +3378,17 @@ function create(config) {
2715
3378
  }
2716
3379
 
2717
3380
  exports.APIErrorErrorCodeEnum = APIErrorErrorCodeEnum;
3381
+ exports.ExtensionState = ExtensionState;
3382
+ exports.HEADER_ORIGIN = HEADER_ORIGIN;
3383
+ exports.HEADER_SECURE_COOKIES = HEADER_SECURE_COOKIES;
2718
3384
  exports.LoginUserResponseTokenTypeEnum = LoginUserResponseTokenTypeEnum;
2719
3385
  exports.Nile = create;
2720
3386
  exports.Server = Server;
3387
+ exports.TENANT_COOKIE = TENANT_COOKIE;
3388
+ exports.USER_COOKIE = USER_COOKIE;
2721
3389
  exports.parseCSRF = parseCSRF;
2722
3390
  exports.parseCallback = parseCallback;
3391
+ exports.parseResetToken = parseResetToken;
2723
3392
  exports.parseToken = parseToken;
2724
3393
  //# sourceMappingURL=index.js.map
2725
3394
  //# sourceMappingURL=index.js.map