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

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.mjs CHANGED
@@ -47,6 +47,8 @@ var appRoutes = (prefix = DEFAULT_PREFIX) => ({
47
47
  TENANT_USER: `${prefix}${"/tenants/{tenantId}/users/{userId}" /* TENANT_USER */}`,
48
48
  TENANT_USERS: `${prefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */}`,
49
49
  SIGNUP: `${prefix}${"/signup" /* SIGNUP */}`,
50
+ INVITES: `${prefix}${"/tenants/{tenantId}/invites" /* INVITES */}`,
51
+ INVITE: `${prefix}${"/tenants/{tenantId}/invite" /* INVITE */}`,
50
52
  LOG: `${prefix}/_log`
51
53
  });
52
54
  var apiRoutes = (config) => ({
@@ -57,6 +59,8 @@ var apiRoutes = (config) => ({
57
59
  TENANT: (tenantId) => makeRestUrl(config, `/tenants/${tenantId}`),
58
60
  SIGNUP: makeRestUrl(config, "/signup"),
59
61
  TENANT_USERS: (tenantId) => makeRestUrl(config, `/tenants/${tenantId}/users`),
62
+ INVITES: (tenantId) => makeRestUrl(config, `/tenants/${tenantId}/invites`),
63
+ INVITE: (tenantId) => makeRestUrl(config, `/tenants/${tenantId}/invite`),
60
64
  TENANT_USER: makeRestUrl(
61
65
  config,
62
66
  `/tenants/${config.tenantId}/users/${config.userId}`
@@ -98,9 +102,9 @@ function makeRestUrl(config, path, qp) {
98
102
  const strParams = params.toString();
99
103
  return `${[url, path.substring(1, path.length)].join("/")}${strParams ? `?${strParams}` : ""}`;
100
104
  }
101
- function urlMatches(requestUrl, route17) {
105
+ function urlMatches(requestUrl, route20) {
102
106
  const url = new URL(requestUrl);
103
- return url.pathname.startsWith(route17);
107
+ return url.pathname.startsWith(route20);
104
108
  }
105
109
  function isUUID(value) {
106
110
  if (!value) {
@@ -170,9 +174,10 @@ function matchesLog(configRoutes, request2) {
170
174
  }
171
175
 
172
176
  // src/utils/constants.ts
173
- var X_NILE_TENANT = "nile-tenant-id";
174
- var X_NILE_ORIGIN = "nile-origin";
175
- var X_NILE_SECURECOOKIES = "nile-secure-cookies";
177
+ var TENANT_COOKIE = "nile.tenant-id";
178
+ var USER_COOKIE = "nile.user-id";
179
+ var HEADER_ORIGIN = "nile-origin";
180
+ var HEADER_SECURE_COOKIES = "nile-secure-cookies";
176
181
 
177
182
  // src/api/utils/request.ts
178
183
  async function request(url, _init, config) {
@@ -183,17 +188,17 @@ async function request(url, _init, config) {
183
188
  if (request2.headers.get("cookie")) {
184
189
  updatedHeaders.set("cookie", String(request2.headers.get("cookie")));
185
190
  }
186
- if (request2.headers.get(X_NILE_TENANT)) {
191
+ if (request2.headers.get(TENANT_COOKIE)) {
187
192
  updatedHeaders.set(
188
- X_NILE_TENANT,
189
- String(request2.headers.get(X_NILE_TENANT))
193
+ TENANT_COOKIE,
194
+ String(request2.headers.get(TENANT_COOKIE))
190
195
  );
191
196
  }
192
197
  if (config.secureCookies != null) {
193
- updatedHeaders.set(X_NILE_SECURECOOKIES, String(config.secureCookies));
198
+ updatedHeaders.set(HEADER_SECURE_COOKIES, String(config.secureCookies));
194
199
  } else {
195
200
  updatedHeaders.set(
196
- X_NILE_SECURECOOKIES,
201
+ HEADER_SECURE_COOKIES,
197
202
  process.env.NODE_ENV === "production" ? "true" : "false"
198
203
  );
199
204
  }
@@ -201,17 +206,17 @@ async function request(url, _init, config) {
201
206
  if (config.callbackUrl) {
202
207
  const cbUrl = new URL(config.callbackUrl);
203
208
  debug(`Obtained origin from config.callbackUrl ${config.callbackUrl}`);
204
- updatedHeaders.set(X_NILE_ORIGIN, cbUrl.origin);
209
+ updatedHeaders.set(HEADER_ORIGIN, cbUrl.origin);
205
210
  } else if (config.origin) {
206
211
  debug(`Obtained origin from config.origin ${config.origin}`);
207
- updatedHeaders.set(X_NILE_ORIGIN, config.origin);
212
+ updatedHeaders.set(HEADER_ORIGIN, config.origin);
208
213
  } else {
209
- const passedOrigin = request2.headers.get(X_NILE_ORIGIN);
214
+ const passedOrigin = request2.headers.get(HEADER_ORIGIN);
210
215
  if (passedOrigin) {
211
- updatedHeaders.set(X_NILE_ORIGIN, passedOrigin);
216
+ updatedHeaders.set(HEADER_ORIGIN, passedOrigin);
212
217
  } else {
213
218
  const reqOrigin = config.routePrefix !== DEFAULT_PREFIX ? `${requestUrl.origin}${config.routePrefix}` : requestUrl.origin;
214
- updatedHeaders.set(X_NILE_ORIGIN, reqOrigin);
219
+ updatedHeaders.set(HEADER_ORIGIN, reqOrigin);
215
220
  debug(`Obtained origin from request ${reqOrigin}`);
216
221
  }
217
222
  }
@@ -219,14 +224,16 @@ async function request(url, _init, config) {
219
224
  if (params.method?.toLowerCase() === "post" || params.method?.toLowerCase() === "put") {
220
225
  try {
221
226
  updatedHeaders.set("content-type", "application/json");
222
- const initBody = await new Response(_init.request.clone().body).json();
223
- const requestBody = await new Response(request2.clone().body).json();
224
- params.body = JSON.stringify(initBody ?? requestBody);
227
+ const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
228
+ const bodyText = await new Response(bodyStream).text();
229
+ try {
230
+ params.body = JSON.stringify(JSON.parse(bodyText));
231
+ } catch {
232
+ updatedHeaders.set("content-type", "application/x-www-form-urlencoded");
233
+ params.body = bodyText;
234
+ }
225
235
  } catch (e) {
226
- updatedHeaders.set("content-type", "application/x-www-form-urlencoded");
227
- const initBody = await new Response(_init.request.clone().body).text();
228
- const requestBody = await new Response(request2.clone().body).text();
229
- params.body = initBody ?? requestBody;
236
+ error("Failed to parse request body");
230
237
  }
231
238
  }
232
239
  params.headers = updatedHeaders;
@@ -235,6 +242,7 @@ async function request(url, _init, config) {
235
242
  params.headers.set("request-id", crypto.randomUUID());
236
243
  params.cache = "no-store";
237
244
  }
245
+ await config.extensionCtx?.handleOnRequest(config, _init, params);
238
246
  try {
239
247
  const res = await fetch(fullUrl, {
240
248
  ...params
@@ -372,8 +380,8 @@ function getTokenFromCookie(headers, cookieKey) {
372
380
  }
373
381
  }
374
382
  function getTenantFromHttp(headers, config) {
375
- const cookieTenant = getTokenFromCookie(headers, X_NILE_TENANT);
376
- return cookieTenant ?? headers?.get(X_NILE_TENANT) ?? config?.tenantId;
383
+ const cookieTenant = getTokenFromCookie(headers, TENANT_COOKIE);
384
+ return cookieTenant ? cookieTenant : config?.tenantId;
377
385
  }
378
386
 
379
387
  // src/api/routes/users/POST.ts
@@ -383,7 +391,7 @@ async function POST(config, init) {
383
391
  const yurl = new URL(init.request.url);
384
392
  const tenantId = yurl.searchParams.get("tenantId");
385
393
  const newTenantName = yurl.searchParams.get("newTenantName");
386
- const tenant = tenantId ?? getTenantFromHttp(init.request.headers);
394
+ const tenant = tenantId ?? getTenantFromHttp(init.request.headers, config);
387
395
  const url = apiRoutes(config).USERS({ tenantId: tenant, newTenantName });
388
396
  return await request(url, init, config);
389
397
  }
@@ -392,21 +400,18 @@ async function POST(config, init) {
392
400
  async function GET2(config, init, log) {
393
401
  const yurl = new URL(init.request.url);
394
402
  const tenantId = yurl.searchParams.get("tenantId");
395
- const tenant = tenantId ?? getTenantFromHttp(init.request.headers);
403
+ const tenant = tenantId ?? getTenantFromHttp(init.request.headers, config);
396
404
  if (!tenant) {
397
405
  log("[GET] No tenant id provided.");
398
406
  return new Response(null, { status: 404 });
399
407
  }
400
- const url = apiRoutes(config).TENANT_USERS(tenant);
401
408
  init.method = "GET";
409
+ const url = apiRoutes(config).TENANT_USERS(tenant);
402
410
  return await request(url, init, config);
403
411
  }
404
412
 
405
413
  // src/api/routes/users/[userId]/PUT.ts
406
- async function PUT2(config, session, init) {
407
- if (!session) {
408
- return new Response(null, { status: 401 });
409
- }
414
+ async function PUT2(config, init) {
410
415
  init.body = init.request.body;
411
416
  init.method = "PUT";
412
417
  const [userId] = new URL(init.request.url).pathname.split("/").reverse();
@@ -421,14 +426,13 @@ async function route2(request2, config) {
421
426
  { ...config, debug: config.debug },
422
427
  `[ROUTES][${key2}]`
423
428
  );
424
- const session = await auth(request2, config);
425
429
  switch (request2.method) {
426
430
  case "GET":
427
431
  return await GET2(config, { request: request2 }, info);
428
432
  case "POST":
429
433
  return await POST(config, { request: request2 });
430
434
  case "PUT":
431
- return await PUT2(config, session, { request: request2 });
435
+ return await PUT2(config, { request: request2 });
432
436
  default:
433
437
  return new Response("method not allowed", { status: 405 });
434
438
  }
@@ -446,7 +450,11 @@ async function GET3(config, init) {
446
450
  }
447
451
 
448
452
  // src/api/routes/tenants/[tenantId]/users/POST.ts
449
- async function POST2(config, session, init) {
453
+ async function POST2(config, init) {
454
+ const session = await auth(init.request, config);
455
+ if (!session) {
456
+ return new Response(null, { status: 401 });
457
+ }
450
458
  const yurl = new URL(init.request.url);
451
459
  const [, tenantId] = yurl.pathname.split("/").reverse();
452
460
  init.body = JSON.stringify({ email: session.email });
@@ -462,11 +470,6 @@ async function route3(request2, config) {
462
470
  { ...config, debug: config.debug },
463
471
  `[ROUTES][${key3}]`
464
472
  );
465
- const session = await auth(request2, config);
466
- if (!session) {
467
- info("401");
468
- return new Response(null, { status: 401 });
469
- }
470
473
  const yurl = new URL(request2.url);
471
474
  const [, tenantId] = yurl.pathname.split("/").reverse();
472
475
  if (!tenantId) {
@@ -477,7 +480,7 @@ async function route3(request2, config) {
477
480
  case "GET":
478
481
  return await GET3(config, { request: request2 });
479
482
  case "POST":
480
- return await POST2(config, session, { request: request2 });
483
+ return await POST2(config, { request: request2 });
481
484
  default:
482
485
  return new Response("method not allowed", { status: 405 });
483
486
  }
@@ -485,11 +488,11 @@ async function route3(request2, config) {
485
488
  function matches3(configRoutes, request2) {
486
489
  const url = new URL(request2.url);
487
490
  const [userId, possibleTenantId, tenantId] = url.pathname.split("/").reverse();
488
- let route17 = configRoutes[key3].replace("{tenantId}", tenantId).replace("{userId}", userId);
491
+ let route20 = configRoutes[key3].replace("{tenantId}", tenantId).replace("{userId}", userId);
489
492
  if (userId === "users") {
490
- route17 = configRoutes[key3].replace("{tenantId}", possibleTenantId);
493
+ route20 = configRoutes[key3].replace("{tenantId}", possibleTenantId);
491
494
  }
492
- return urlMatches(request2.url, route17);
495
+ return urlMatches(request2.url, route20);
493
496
  }
494
497
  async function fetchTenantUsers(config, method, payload) {
495
498
  const { body, params } = {};
@@ -523,8 +526,139 @@ async function fetchTenantUsers(config, method, payload) {
523
526
  return await config.handlers[m](req);
524
527
  }
525
528
 
529
+ // src/api/routes/tenants/[tenantId]/invite/PUT.ts
530
+ async function PUT3(config, init) {
531
+ const yurl = new URL(init.request.url);
532
+ const [, tenantId] = yurl.pathname.split("/").reverse();
533
+ if (!tenantId) {
534
+ return new Response(null, { status: 404 });
535
+ }
536
+ if (yurl.searchParams.size > 0) {
537
+ init.body = new URLSearchParams(yurl.searchParams).toString();
538
+ }
539
+ init.method = "PUT";
540
+ const url = `${apiRoutes(config).INVITE(tenantId)}`;
541
+ const res = await request(url, init, config);
542
+ const location = res?.headers.get("location");
543
+ if (location) {
544
+ return new Response(res?.body, {
545
+ status: 302,
546
+ headers: res?.headers
547
+ });
548
+ }
549
+ return new Response(res?.body, {
550
+ status: res?.status,
551
+ headers: res?.headers
552
+ });
553
+ }
554
+
555
+ // src/api/routes/tenants/[tenantId]/invite/POST.ts
556
+ async function POST3(config, init) {
557
+ const yurl = new URL(init.request.url);
558
+ const [, tenantId] = yurl.pathname.split("/").reverse();
559
+ if (!tenantId) {
560
+ return new Response(null, { status: 404 });
561
+ }
562
+ init.method = "POST";
563
+ init.body = init.request.body;
564
+ const url = `${apiRoutes(config).INVITE(tenantId)}`;
565
+ return await request(url, init, config);
566
+ }
567
+
568
+ // src/api/routes/tenants/[tenantId]/invite/index.ts
569
+ var key4 = "INVITE";
570
+ async function route4(request2, config) {
571
+ switch (request2.method) {
572
+ // the browser is a GET, but we need to PUT it into nile-auth
573
+ // server side, this is a put
574
+ case "GET":
575
+ case "PUT":
576
+ return await PUT3(config, { request: request2 });
577
+ case "POST":
578
+ return await POST3(config, { request: request2 });
579
+ default:
580
+ return new Response("method not allowed", { status: 405 });
581
+ }
582
+ }
583
+ function matches4(configRoutes, request2) {
584
+ const url = new URL(request2.url);
585
+ const [, tenantId] = url.pathname.split("/").reverse();
586
+ const route20 = configRoutes[key4].replace("{tenantId}", tenantId);
587
+ return urlMatches(request2.url, route20);
588
+ }
589
+ async function fetchInvite(config, method, body) {
590
+ if (!config.tenantId) {
591
+ throw new Error(
592
+ 'Unable to fetch tenant, the tenantId context is missing. Call nile.setContext({ tenantId }), set nile.tenantId = "tenantId", or add it to the function call'
593
+ );
594
+ }
595
+ if (!isUUID(config.tenantId) && config.logger?.warn) {
596
+ config.logger?.warn(
597
+ "nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
598
+ );
599
+ }
600
+ let clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace("{tenantId}", config.tenantId)}`;
601
+ const m = method ?? "GET";
602
+ const init = {
603
+ method: m,
604
+ headers: config.headers
605
+ };
606
+ if (method === "POST" || method === "PUT") {
607
+ init.body = body;
608
+ }
609
+ if (method === "DELETE") {
610
+ clientUrl = `${clientUrl}/${body}`;
611
+ }
612
+ const req = new Request(clientUrl, init);
613
+ return await config.handlers[m](req);
614
+ }
615
+
616
+ // src/api/routes/tenants/[tenantId]/invites/GET.ts
617
+ async function GET4(config, init) {
618
+ const yurl = new URL(init.request.url);
619
+ const [, tenantId] = yurl.pathname.split("/").reverse();
620
+ if (!tenantId) {
621
+ return new Response(null, { status: 404 });
622
+ }
623
+ init.method = "GET";
624
+ const url = `${apiRoutes(config).INVITES(tenantId)}`;
625
+ return await request(url, init, config);
626
+ }
627
+
628
+ // src/api/routes/tenants/[tenantId]/invites/index.ts
629
+ var key5 = "INVITES";
630
+ async function route5(request2, config) {
631
+ switch (request2.method) {
632
+ case "GET":
633
+ return await GET4(config, { request: request2 });
634
+ default:
635
+ return new Response("method not allowed", { status: 405 });
636
+ }
637
+ }
638
+ function matches5(configRoutes, request2) {
639
+ const url = new URL(request2.url);
640
+ const [, tenantId] = url.pathname.split("/").reverse();
641
+ const route20 = configRoutes[key5].replace("{tenantId}", tenantId);
642
+ return url.pathname.endsWith(route20);
643
+ }
644
+ async function fetchInvites(config) {
645
+ if (!config.tenantId) {
646
+ throw new Error(
647
+ 'Unable to fetch tenant, the tenantId context is missing. Call nile.setContext({ tenantId }), set nile.tenantId = "tenantId", or add it to the function call'
648
+ );
649
+ }
650
+ if (!isUUID(config.tenantId) && config.logger?.warn) {
651
+ config.logger?.warn(
652
+ "nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
653
+ );
654
+ }
655
+ const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/invites" /* INVITES */.replace("{tenantId}", config.tenantId)}`;
656
+ const req = new Request(clientUrl, { headers: config.headers });
657
+ return await config.handlers.GET(req);
658
+ }
659
+
526
660
  // src/api/routes/tenants/GET.ts
527
- async function GET4(config, session, init) {
661
+ async function GET5(config, session, init) {
528
662
  let url = `${apiRoutes(config).USER_TENANTS(session.id)}`;
529
663
  if (typeof session === "object" && "user" in session && session.user) {
530
664
  url = `${apiRoutes(config).USER_TENANTS(session.user.id)}`;
@@ -534,7 +668,7 @@ async function GET4(config, session, init) {
534
668
  }
535
669
 
536
670
  // src/api/routes/tenants/[tenantId]/GET.ts
537
- async function GET5(config, init, log) {
671
+ async function GET6(config, init, log) {
538
672
  const yurl = new URL(init.request.url);
539
673
  const [tenantId] = yurl.pathname.split("/").reverse();
540
674
  if (!tenantId) {
@@ -559,7 +693,7 @@ async function DELETE2(config, init) {
559
693
  }
560
694
 
561
695
  // src/api/routes/tenants/[tenantId]/PUT.ts
562
- async function PUT3(config, init) {
696
+ async function PUT4(config, init) {
563
697
  const yurl = new URL(init.request.url);
564
698
  const [tenantId] = yurl.pathname.split("/").reverse();
565
699
  if (!tenantId) {
@@ -572,7 +706,7 @@ async function PUT3(config, init) {
572
706
  }
573
707
 
574
708
  // src/api/routes/tenants/POST.ts
575
- async function POST3(config, init) {
709
+ async function POST4(config, init) {
576
710
  init.body = init.request.body;
577
711
  init.method = "POST";
578
712
  const url = `${apiRoutes(config).TENANTS}`;
@@ -580,11 +714,11 @@ async function POST3(config, init) {
580
714
  }
581
715
 
582
716
  // src/api/routes/tenants/index.ts
583
- var key4 = "TENANTS";
584
- async function route4(request2, config) {
717
+ var key6 = "TENANTS";
718
+ async function route6(request2, config) {
585
719
  const { info } = Logger(
586
720
  { ...config, debug: config.debug },
587
- `[ROUTES][${key4}]`
721
+ `[ROUTES][${key6}]`
588
722
  );
589
723
  const session = await auth(request2, config);
590
724
  if (!session) {
@@ -595,21 +729,21 @@ async function route4(request2, config) {
595
729
  switch (request2.method) {
596
730
  case "GET":
597
731
  if (isUUID(possibleTenantId)) {
598
- return await GET5(config, { request: request2 }, info);
732
+ return await GET6(config, { request: request2 }, info);
599
733
  }
600
- return await GET4(config, session, { request: request2 });
734
+ return await GET5(config, session, { request: request2 });
601
735
  case "POST":
602
- return await POST3(config, { request: request2 });
736
+ return await POST4(config, { request: request2 });
603
737
  case "DELETE":
604
738
  return await DELETE2(config, { request: request2 });
605
739
  case "PUT":
606
- return await PUT3(config, { request: request2 });
740
+ return await PUT4(config, { request: request2 });
607
741
  default:
608
742
  return new Response("method not allowed", { status: 405 });
609
743
  }
610
744
  }
611
- function matches4(configRoutes, request2) {
612
- return urlMatches(request2.url, configRoutes[key4]);
745
+ function matches6(configRoutes, request2) {
746
+ return urlMatches(request2.url, configRoutes[key6]);
613
747
  }
614
748
  async function fetchTenants(config, method, body) {
615
749
  const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants" /* TENANTS */}`;
@@ -667,16 +801,16 @@ async function fetchTenantsByUser(config) {
667
801
  }
668
802
 
669
803
  // src/api/routes/auth/signin.ts
670
- var key5 = "SIGNIN";
671
- async function route5(req, config) {
672
- let url = proxyRoutes(config)[key5];
804
+ var key7 = "SIGNIN";
805
+ async function route7(req, config) {
806
+ let url = proxyRoutes(config)[key7];
673
807
  const init = {
674
808
  method: req.method,
675
809
  headers: req.headers
676
810
  };
677
811
  if (req.method === "POST") {
678
812
  const [provider] = new URL(req.url).pathname.split("/").reverse();
679
- url = `${proxyRoutes(config)[key5]}/${provider}`;
813
+ url = `${proxyRoutes(config)[key7]}/${provider}`;
680
814
  }
681
815
  const passThroughUrl = new URL(req.url);
682
816
  const params = new URLSearchParams(passThroughUrl.search);
@@ -684,8 +818,8 @@ async function route5(req, config) {
684
818
  const res = await request(url, { ...init, request: req }, config);
685
819
  return res;
686
820
  }
687
- function matches5(configRoutes, request2) {
688
- return urlMatches(request2.url, configRoutes[key5]);
821
+ function matches7(configRoutes, request2) {
822
+ return urlMatches(request2.url, configRoutes[key7]);
689
823
  }
690
824
  async function fetchSignIn(config, provider, body) {
691
825
  const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/signin" /* SIGNIN */}/${provider}`;
@@ -698,7 +832,7 @@ async function fetchSignIn(config, provider, body) {
698
832
  }
699
833
 
700
834
  // src/api/routes/auth/session.ts
701
- async function route6(req, config) {
835
+ async function route8(req, config) {
702
836
  return request(
703
837
  proxyRoutes(config).SESSION,
704
838
  {
@@ -708,7 +842,7 @@ async function route6(req, config) {
708
842
  config
709
843
  );
710
844
  }
711
- function matches6(configRoutes, request2) {
845
+ function matches8(configRoutes, request2) {
712
846
  return urlMatches(request2.url, configRoutes.SESSION);
713
847
  }
714
848
  async function fetchSession(config) {
@@ -721,7 +855,7 @@ async function fetchSession(config) {
721
855
  }
722
856
 
723
857
  // src/api/routes/auth/providers.ts
724
- async function route7(req, config) {
858
+ async function route9(req, config) {
725
859
  return request(
726
860
  proxyRoutes(config).PROVIDERS,
727
861
  {
@@ -731,7 +865,7 @@ async function route7(req, config) {
731
865
  config
732
866
  );
733
867
  }
734
- function matches7(configRoutes, request2) {
868
+ function matches9(configRoutes, request2) {
735
869
  return urlMatches(request2.url, configRoutes.PROVIDERS);
736
870
  }
737
871
  async function fetchProviders(config) {
@@ -744,7 +878,7 @@ async function fetchProviders(config) {
744
878
  }
745
879
 
746
880
  // src/api/routes/auth/csrf.ts
747
- async function route8(req, config) {
881
+ async function route10(req, config) {
748
882
  return request(
749
883
  proxyRoutes(config).CSRF,
750
884
  {
@@ -754,7 +888,7 @@ async function route8(req, config) {
754
888
  config
755
889
  );
756
890
  }
757
- function matches8(configRoutes, request2) {
891
+ function matches10(configRoutes, request2) {
758
892
  return urlMatches(request2.url, configRoutes.CSRF);
759
893
  }
760
894
  async function fetchCsrf(config) {
@@ -767,17 +901,17 @@ async function fetchCsrf(config) {
767
901
  }
768
902
 
769
903
  // src/api/routes/auth/callback.ts
770
- var key6 = "CALLBACK";
771
- async function route9(req, config) {
904
+ var key8 = "CALLBACK";
905
+ async function route11(req, config) {
772
906
  const { error } = Logger(
773
907
  { ...config, debug: config.debug },
774
- `[ROUTES][${key6}]`
908
+ `[ROUTES][${key8}]`
775
909
  );
776
910
  const [provider] = new URL(req.url).pathname.split("/").reverse();
777
911
  try {
778
912
  const passThroughUrl = new URL(req.url);
779
913
  const params = new URLSearchParams(passThroughUrl.search);
780
- const url = `${proxyRoutes(config)[key6]}/${provider}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
914
+ const url = `${proxyRoutes(config)[key8]}/${provider}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
781
915
  const res = await request(
782
916
  url,
783
917
  {
@@ -804,7 +938,7 @@ async function route9(req, config) {
804
938
  }
805
939
  return new Response("An unexpected error has occurred.", { status: 400 });
806
940
  }
807
- function matches9(configRoutes, request2) {
941
+ function matches11(configRoutes, request2) {
808
942
  return urlMatches(request2.url, configRoutes.CALLBACK);
809
943
  }
810
944
  async function fetchCallback(config, provider, body, request2, method = "POST") {
@@ -818,22 +952,22 @@ async function fetchCallback(config, provider, body, request2, method = "POST")
818
952
  }
819
953
 
820
954
  // src/api/routes/auth/signout.ts
821
- var key7 = "SIGNOUT";
822
- async function route10(request2, config) {
823
- let url = proxyRoutes(config)[key7];
955
+ var key9 = "SIGNOUT";
956
+ async function route12(request2, config) {
957
+ let url = proxyRoutes(config)[key9];
824
958
  const init = {
825
959
  method: request2.method
826
960
  };
827
961
  if (request2.method === "POST") {
828
962
  init.body = request2.body;
829
963
  const [provider] = new URL(request2.url).pathname.split("/").reverse();
830
- url = `${proxyRoutes(config)[key7]}${provider !== "signout" ? `/${provider}` : ""}`;
964
+ url = `${proxyRoutes(config)[key9]}${provider !== "signout" ? `/${provider}` : ""}`;
831
965
  }
832
966
  const res = await request(url, { ...init, request: request2 }, config);
833
967
  return res;
834
968
  }
835
- function matches10(configRoutes, request2) {
836
- return urlMatches(request2.url, configRoutes[key7]);
969
+ function matches12(configRoutes, request2) {
970
+ return urlMatches(request2.url, configRoutes[key9]);
837
971
  }
838
972
  async function fetchSignOut(config, body) {
839
973
  const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/signout" /* SIGNOUT */}`;
@@ -846,10 +980,10 @@ async function fetchSignOut(config, body) {
846
980
  }
847
981
 
848
982
  // src/api/routes/auth/error.ts
849
- var key8 = "ERROR";
850
- async function route11(req, config) {
983
+ var key10 = "ERROR";
984
+ async function route13(req, config) {
851
985
  return request(
852
- proxyRoutes(config)[key8],
986
+ proxyRoutes(config)[key10],
853
987
  {
854
988
  method: req.method,
855
989
  request: req
@@ -857,15 +991,15 @@ async function route11(req, config) {
857
991
  config
858
992
  );
859
993
  }
860
- function matches11(configRoutes, request2) {
861
- return urlMatches(request2.url, configRoutes[key8]);
994
+ function matches13(configRoutes, request2) {
995
+ return urlMatches(request2.url, configRoutes[key10]);
862
996
  }
863
997
 
864
998
  // src/api/routes/auth/verify-request.ts
865
- var key9 = "VERIFY_REQUEST";
866
- async function route12(req, config) {
999
+ var key11 = "VERIFY_REQUEST";
1000
+ async function route14(req, config) {
867
1001
  return request(
868
- proxyRoutes(config)[key9],
1002
+ proxyRoutes(config)[key11],
869
1003
  {
870
1004
  method: req.method,
871
1005
  request: req
@@ -873,14 +1007,14 @@ async function route12(req, config) {
873
1007
  config
874
1008
  );
875
1009
  }
876
- function matches12(configRoutes, request2) {
877
- return urlMatches(request2.url, configRoutes[key9]);
1010
+ function matches14(configRoutes, request2) {
1011
+ return urlMatches(request2.url, configRoutes[key11]);
878
1012
  }
879
1013
 
880
1014
  // src/api/routes/auth/password-reset.ts
881
- var key10 = "PASSWORD_RESET";
882
- async function route13(req, config) {
883
- const url = proxyRoutes(config)[key10];
1015
+ var key12 = "PASSWORD_RESET";
1016
+ async function route15(req, config) {
1017
+ const url = proxyRoutes(config)[key12];
884
1018
  const res = await request(
885
1019
  url,
886
1020
  {
@@ -901,12 +1035,14 @@ async function route13(req, config) {
901
1035
  headers: res?.headers
902
1036
  });
903
1037
  }
904
- function matches13(configRoutes, request2) {
1038
+ function matches15(configRoutes, request2) {
905
1039
  return urlMatches(request2.url, configRoutes.PASSWORD_RESET);
906
1040
  }
907
- async function fetchResetPassword(config, method, body, params) {
1041
+ async function fetchResetPassword(config, method, body, params, useJson = true) {
908
1042
  const authParams = new URLSearchParams(params ?? {});
909
- authParams?.set("json", "true");
1043
+ if (useJson) {
1044
+ authParams?.set("json", "true");
1045
+ }
910
1046
  const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}?${authParams?.toString()}`;
911
1047
  const init = {
912
1048
  method,
@@ -920,9 +1056,9 @@ async function fetchResetPassword(config, method, body, params) {
920
1056
  }
921
1057
 
922
1058
  // src/api/routes/auth/verify-email.ts
923
- var key11 = "VERIFY_EMAIL";
924
- async function route14(req, config) {
925
- const url = proxyRoutes(config)[key11];
1059
+ var key13 = "VERIFY_EMAIL";
1060
+ async function route16(req, config) {
1061
+ const url = proxyRoutes(config)[key13];
926
1062
  const res = await request(
927
1063
  url,
928
1064
  {
@@ -943,8 +1079,8 @@ async function route14(req, config) {
943
1079
  headers: res?.headers
944
1080
  });
945
1081
  }
946
- function matches14(configRoutes, request2) {
947
- return urlMatches(request2.url, configRoutes[key11]);
1082
+ function matches16(configRoutes, request2) {
1083
+ return urlMatches(request2.url, configRoutes[key13]);
948
1084
  }
949
1085
  async function fetchVerifyEmail(config, method, body) {
950
1086
  const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/verify-email" /* VERIFY_EMAIL */}`;
@@ -962,62 +1098,70 @@ async function fetchVerifyEmail(config, method, body) {
962
1098
  // src/api/handlers/GET.ts
963
1099
  function GETTER(configRoutes, config) {
964
1100
  const { info, warn } = Logger(config, "[GET MATCHER]");
965
- return async function GET6(req) {
1101
+ return async function GET7(req) {
966
1102
  if (matches(configRoutes, req)) {
967
1103
  info("matches me");
968
1104
  return route(req, config);
969
1105
  }
1106
+ if (matches5(configRoutes, req)) {
1107
+ info("matches tenant invites");
1108
+ return route5(req, config);
1109
+ }
1110
+ if (matches4(configRoutes, req)) {
1111
+ info("matches invite");
1112
+ return route4(req, config);
1113
+ }
970
1114
  if (matches3(configRoutes, req)) {
971
1115
  info("matches tenant users");
972
1116
  return route3(req, config);
973
1117
  }
1118
+ if (matches6(configRoutes, req)) {
1119
+ info("matches tenants");
1120
+ return route6(req, config);
1121
+ }
974
1122
  if (matches2(configRoutes, req)) {
975
1123
  info("matches users");
976
1124
  return route2(req, config);
977
1125
  }
978
- if (matches4(configRoutes, req)) {
979
- info("matches tenants");
980
- return route4(req, config);
981
- }
982
- if (matches6(configRoutes, req)) {
1126
+ if (matches8(configRoutes, req)) {
983
1127
  info("matches session");
984
- return route6(req, config);
1128
+ return route8(req, config);
985
1129
  }
986
- if (matches5(configRoutes, req)) {
1130
+ if (matches7(configRoutes, req)) {
987
1131
  info("matches signin");
988
- return route5(req, config);
1132
+ return route7(req, config);
989
1133
  }
990
- if (matches7(configRoutes, req)) {
1134
+ if (matches9(configRoutes, req)) {
991
1135
  info("matches providers");
992
- return route7(req, config);
1136
+ return route9(req, config);
993
1137
  }
994
- if (matches8(configRoutes, req)) {
1138
+ if (matches10(configRoutes, req)) {
995
1139
  info("matches csrf");
996
- return route8(req, config);
1140
+ return route10(req, config);
997
1141
  }
998
- if (matches13(configRoutes, req)) {
1142
+ if (matches15(configRoutes, req)) {
999
1143
  info("matches password reset");
1000
- return route13(req, config);
1144
+ return route15(req, config);
1001
1145
  }
1002
- if (matches9(configRoutes, req)) {
1146
+ if (matches11(configRoutes, req)) {
1003
1147
  info("matches callback");
1004
- return route9(req, config);
1005
- }
1006
- if (matches10(configRoutes, req)) {
1007
- info("matches signout");
1008
- return route10(req, config);
1148
+ return route11(req, config);
1009
1149
  }
1010
1150
  if (matches12(configRoutes, req)) {
1011
- info("matches verify-request");
1151
+ info("matches signout");
1012
1152
  return route12(req, config);
1013
1153
  }
1014
1154
  if (matches14(configRoutes, req)) {
1015
- info("matches verify-email");
1155
+ info("matches verify-request");
1016
1156
  return route14(req, config);
1017
1157
  }
1018
- if (matches11(configRoutes, req)) {
1158
+ if (matches16(configRoutes, req)) {
1159
+ info("matches verify-email");
1160
+ return route16(req, config);
1161
+ }
1162
+ if (matches13(configRoutes, req)) {
1019
1163
  info("matches error");
1020
- return route11(req, config);
1164
+ return route13(req, config);
1021
1165
  }
1022
1166
  warn(`No GET routes matched ${req.url}`);
1023
1167
  return new Response(null, { status: 404 });
@@ -1025,7 +1169,7 @@ function GETTER(configRoutes, config) {
1025
1169
  }
1026
1170
 
1027
1171
  // src/api/routes/signup/POST.ts
1028
- async function POST4(config, init) {
1172
+ async function POST5(config, init) {
1029
1173
  init.body = init.request.body;
1030
1174
  init.method = "POST";
1031
1175
  const url = `${apiRoutes(config).SIGNUP}`;
@@ -1033,17 +1177,17 @@ async function POST4(config, init) {
1033
1177
  }
1034
1178
 
1035
1179
  // src/api/routes/signup/index.tsx
1036
- var key12 = "SIGNUP";
1037
- async function route15(request2, config) {
1180
+ var key14 = "SIGNUP";
1181
+ async function route17(request2, config) {
1038
1182
  switch (request2.method) {
1039
1183
  case "POST":
1040
- return await POST4(config, { request: request2 });
1184
+ return await POST5(config, { request: request2 });
1041
1185
  default:
1042
1186
  return new Response("method not allowed", { status: 405 });
1043
1187
  }
1044
1188
  }
1045
- function matches15(configRoutes, request2) {
1046
- return urlMatches(request2.url, configRoutes[key12]);
1189
+ function matches17(configRoutes, request2) {
1190
+ return urlMatches(request2.url, configRoutes[key14]);
1047
1191
  }
1048
1192
  async function fetchSignUp(config, payload) {
1049
1193
  const { body, params } = payload ?? {};
@@ -1066,7 +1210,7 @@ async function fetchSignUp(config, payload) {
1066
1210
  // src/api/handlers/POST.ts
1067
1211
  function POSTER(configRoutes, config) {
1068
1212
  const { info, warn, error } = Logger(config, "[POST MATCHER]");
1069
- return async function POST5(req) {
1213
+ return async function POST6(req) {
1070
1214
  if (matchesLog(configRoutes, req)) {
1071
1215
  try {
1072
1216
  const json = await req.clone().json();
@@ -1080,49 +1224,53 @@ function POSTER(configRoutes, config) {
1080
1224
  info("matches tenant users");
1081
1225
  return route3(req, config);
1082
1226
  }
1083
- if (matches15(configRoutes, req)) {
1227
+ if (matches4(configRoutes, req)) {
1228
+ info("matches tenant invite");
1229
+ return route4(req, config);
1230
+ }
1231
+ if (matches17(configRoutes, req)) {
1084
1232
  info("matches signup");
1085
- return route15(req, config);
1233
+ return route17(req, config);
1086
1234
  }
1087
1235
  if (matches2(configRoutes, req)) {
1088
1236
  info("matches users");
1089
1237
  return route2(req, config);
1090
1238
  }
1091
- if (matches4(configRoutes, req)) {
1239
+ if (matches6(configRoutes, req)) {
1092
1240
  info("matches tenants");
1093
- return route4(req, config);
1241
+ return route6(req, config);
1094
1242
  }
1095
- if (matches6(configRoutes, req)) {
1243
+ if (matches8(configRoutes, req)) {
1096
1244
  info("matches session");
1097
- return route6(req, config);
1245
+ return route8(req, config);
1098
1246
  }
1099
- if (matches5(configRoutes, req)) {
1247
+ if (matches7(configRoutes, req)) {
1100
1248
  info("matches signin");
1101
- return route5(req, config);
1249
+ return route7(req, config);
1102
1250
  }
1103
- if (matches13(configRoutes, req)) {
1251
+ if (matches15(configRoutes, req)) {
1104
1252
  info("matches password reset");
1105
- return route13(req, config);
1253
+ return route15(req, config);
1106
1254
  }
1107
- if (matches7(configRoutes, req)) {
1255
+ if (matches9(configRoutes, req)) {
1108
1256
  info("matches providers");
1109
- return route7(req, config);
1257
+ return route9(req, config);
1110
1258
  }
1111
- if (matches8(configRoutes, req)) {
1259
+ if (matches10(configRoutes, req)) {
1112
1260
  info("matches csrf");
1113
- return route8(req, config);
1261
+ return route10(req, config);
1114
1262
  }
1115
- if (matches9(configRoutes, req)) {
1263
+ if (matches11(configRoutes, req)) {
1116
1264
  info("matches callback");
1117
- return route9(req, config);
1265
+ return route11(req, config);
1118
1266
  }
1119
- if (matches10(configRoutes, req)) {
1267
+ if (matches12(configRoutes, req)) {
1120
1268
  info("matches signout");
1121
- return route10(req, config);
1269
+ return route12(req, config);
1122
1270
  }
1123
- if (matches14(configRoutes, req)) {
1271
+ if (matches16(configRoutes, req)) {
1124
1272
  info("matches verify-email");
1125
- return route14(req, config);
1273
+ return route16(req, config);
1126
1274
  }
1127
1275
  warn(`No POST routes matched ${req.url}`);
1128
1276
  return new Response(null, { status: 404 });
@@ -1141,7 +1289,7 @@ async function DELETE3(config, init) {
1141
1289
  }
1142
1290
 
1143
1291
  // src/api/routes/tenants/[tenantId]/users/[userId]/PUT.ts
1144
- async function PUT4(config, init) {
1292
+ async function PUT5(config, init) {
1145
1293
  const yurl = new URL(init.request.url);
1146
1294
  const [, userId, , tenantId] = yurl.pathname.split("/").reverse();
1147
1295
  config.tenantId = tenantId;
@@ -1152,11 +1300,11 @@ async function PUT4(config, init) {
1152
1300
  }
1153
1301
 
1154
1302
  // src/api/routes/tenants/[tenantId]/users/[userId]/index.ts
1155
- var key13 = "TENANT_USER";
1156
- async function route16(request2, config) {
1303
+ var key15 = "TENANT_USER";
1304
+ async function route18(request2, config) {
1157
1305
  const { info } = Logger(
1158
1306
  { ...config, debug: config.debug },
1159
- `[ROUTES][${key13}]`
1307
+ `[ROUTES][${key15}]`
1160
1308
  );
1161
1309
  const session = await auth(request2, config);
1162
1310
  if (!session) {
@@ -1171,21 +1319,21 @@ async function route16(request2, config) {
1171
1319
  }
1172
1320
  switch (request2.method) {
1173
1321
  case "PUT":
1174
- return await PUT4(config, { request: request2 });
1322
+ return await PUT5(config, { request: request2 });
1175
1323
  case "DELETE":
1176
1324
  return await DELETE3(config, { request: request2 });
1177
1325
  default:
1178
1326
  return new Response("method not allowed", { status: 405 });
1179
1327
  }
1180
1328
  }
1181
- function matches16(configRoutes, request2) {
1329
+ function matches18(configRoutes, request2) {
1182
1330
  const url = new URL(request2.url);
1183
1331
  const [, userId, possibleTenantId, tenantId] = url.pathname.split("/").reverse();
1184
- let route17 = configRoutes[key13].replace("{tenantId}", tenantId).replace("{userId}", userId);
1332
+ let route20 = configRoutes[key15].replace("{tenantId}", tenantId).replace("{userId}", userId);
1185
1333
  if (userId === "users") {
1186
- route17 = configRoutes[key13].replace("{tenantId}", possibleTenantId);
1334
+ route20 = configRoutes[key15].replace("{tenantId}", possibleTenantId);
1187
1335
  }
1188
- return urlMatches(request2.url, route17);
1336
+ return urlMatches(request2.url, route20);
1189
1337
  }
1190
1338
  async function fetchTenantUser(config, method) {
1191
1339
  if (!config.tenantId) {
@@ -1209,21 +1357,54 @@ async function fetchTenantUser(config, method) {
1209
1357
  return await config.handlers[method](req);
1210
1358
  }
1211
1359
 
1360
+ // src/api/routes/tenants/[tenantId]/invite/[inviteId]/DELETE.ts
1361
+ async function DELETE4(config, init) {
1362
+ const yurl = new URL(init.request.url);
1363
+ const [inviteId, , tenantId] = yurl.pathname.split("/").reverse();
1364
+ if (!tenantId) {
1365
+ return new Response(null, { status: 404 });
1366
+ }
1367
+ init.method = "DELETE";
1368
+ const url = `${apiRoutes(config).INVITE(tenantId)}/${inviteId}`;
1369
+ return await request(url, init, config);
1370
+ }
1371
+
1372
+ // src/api/routes/tenants/[tenantId]/invite/[inviteId]/index.ts
1373
+ var key16 = "INVITE";
1374
+ async function route19(request2, config) {
1375
+ switch (request2.method) {
1376
+ case "DELETE":
1377
+ return await DELETE4(config, { request: request2 });
1378
+ default:
1379
+ return new Response("method not allowed", { status: 405 });
1380
+ }
1381
+ }
1382
+ function matches19(configRoutes, request2) {
1383
+ const url = new URL(request2.url);
1384
+ const [inviteId, , tenantId] = url.pathname.split("/").reverse();
1385
+ const route20 = configRoutes[key16].replace("{tenantId}", tenantId).replace("{inviteId}", inviteId);
1386
+ return urlMatches(request2.url, route20);
1387
+ }
1388
+
1212
1389
  // src/api/handlers/DELETE.ts
1213
1390
  function DELETER(configRoutes, config) {
1214
1391
  const { info, warn } = Logger(config, "[DELETE MATCHER]");
1215
- return async function DELETE4(req) {
1216
- if (matches16(configRoutes, req)) {
1392
+ return async function DELETE5(req) {
1393
+ if (matches19(configRoutes, req)) {
1394
+ info("matches tenant invite id");
1395
+ return route19(req, config);
1396
+ }
1397
+ if (matches18(configRoutes, req)) {
1217
1398
  info("matches tenant user");
1218
- return route16(req, config);
1399
+ return route18(req, config);
1219
1400
  }
1220
1401
  if (matches3(configRoutes, req)) {
1221
1402
  info("matches tenant users");
1222
1403
  return route3(req, config);
1223
1404
  }
1224
- if (matches4(configRoutes, req)) {
1405
+ if (matches6(configRoutes, req)) {
1225
1406
  info("matches tenants");
1226
- return route4(req, config);
1407
+ return route6(req, config);
1227
1408
  }
1228
1409
  if (matches(configRoutes, req)) {
1229
1410
  info("matches me");
@@ -1237,10 +1418,14 @@ function DELETER(configRoutes, config) {
1237
1418
  // src/api/handlers/PUT.ts
1238
1419
  function PUTER(configRoutes, config) {
1239
1420
  const { info, warn } = Logger(config, "[PUT MATCHER]");
1240
- return async function PUT5(req) {
1241
- if (matches16(configRoutes, req)) {
1421
+ return async function PUT6(req) {
1422
+ if (matches4(configRoutes, req)) {
1423
+ info("matches tenant invite");
1424
+ return route4(req, config);
1425
+ }
1426
+ if (matches18(configRoutes, req)) {
1242
1427
  info("matches tenant user");
1243
- return route16(req, config);
1428
+ return route18(req, config);
1244
1429
  }
1245
1430
  if (matches3(configRoutes, req)) {
1246
1431
  info("matches tenant users");
@@ -1254,13 +1439,13 @@ function PUTER(configRoutes, config) {
1254
1439
  info("matches me");
1255
1440
  return route(req, config);
1256
1441
  }
1257
- if (matches4(configRoutes, req)) {
1442
+ if (matches6(configRoutes, req)) {
1258
1443
  info("matches tenants");
1259
- return route4(req, config);
1444
+ return route6(req, config);
1260
1445
  }
1261
- if (matches13(configRoutes, req)) {
1446
+ if (matches15(configRoutes, req)) {
1262
1447
  info("matches reset password");
1263
- return route13(req, config);
1448
+ return route15(req, config);
1264
1449
  }
1265
1450
  warn("No PUT routes matched");
1266
1451
  return new Response(null, { status: 404 });
@@ -1269,15 +1454,15 @@ function PUTER(configRoutes, config) {
1269
1454
 
1270
1455
  // src/api/handlers/index.ts
1271
1456
  function Handlers(configRoutes, config) {
1272
- const GET6 = GETTER(configRoutes, config);
1273
- const POST5 = POSTER(configRoutes, config);
1274
- const DELETE4 = DELETER(configRoutes, config);
1275
- const PUT5 = PUTER(configRoutes, config);
1457
+ const GET7 = GETTER(configRoutes, config);
1458
+ const POST6 = POSTER(configRoutes, config);
1459
+ const DELETE5 = DELETER(configRoutes, config);
1460
+ const PUT6 = PUTER(configRoutes, config);
1276
1461
  return {
1277
- GET: GET6,
1278
- POST: POST5,
1279
- DELETE: DELETE4,
1280
- PUT: PUT5
1462
+ GET: GET7,
1463
+ POST: POST6,
1464
+ DELETE: DELETE5,
1465
+ PUT: PUT6
1281
1466
  };
1282
1467
  }
1283
1468
  var getApiUrl = (cfg) => {
@@ -1310,7 +1495,8 @@ var getSecureCookies = (cfg) => {
1310
1495
  return void 0;
1311
1496
  };
1312
1497
  var getUsername = (cfg) => {
1313
- const { config, logger } = cfg;
1498
+ const { config } = cfg;
1499
+ const logger = config.logger;
1314
1500
  const { info } = Logger(config, "[username]");
1315
1501
  if (config?.user) {
1316
1502
  logger && info(`${logger}[config] ${config.user}`);
@@ -1336,7 +1522,8 @@ var getUsername = (cfg) => {
1336
1522
  );
1337
1523
  };
1338
1524
  var getPassword = (cfg) => {
1339
- const { config, logger } = cfg;
1525
+ const { config } = cfg;
1526
+ const logger = config.logger;
1340
1527
  const log = logProtector(logger);
1341
1528
  const { info } = Logger(config, "[password]");
1342
1529
  if (stringCheck(config?.password)) {
@@ -1363,7 +1550,8 @@ var getPassword = (cfg) => {
1363
1550
  );
1364
1551
  };
1365
1552
  var getDatabaseName = (cfg) => {
1366
- const { config, logger } = cfg;
1553
+ const { config } = cfg;
1554
+ const logger = config.logger;
1367
1555
  const { info } = Logger(config, "[databaseName]");
1368
1556
  if (stringCheck(config?.databaseName)) {
1369
1557
  logger && info(`${logger}[config] ${config?.databaseName}`);
@@ -1386,7 +1574,8 @@ var getDatabaseName = (cfg) => {
1386
1574
  );
1387
1575
  };
1388
1576
  var getTenantId = (cfg) => {
1389
- const { config, logger } = cfg;
1577
+ const { config } = cfg;
1578
+ const logger = config.logger;
1390
1579
  const { info } = Logger(config, "[tenantId]");
1391
1580
  if (stringCheck(config?.tenantId)) {
1392
1581
  logger && info(`${logger}[config] ${config?.tenantId}`);
@@ -1399,7 +1588,8 @@ var getTenantId = (cfg) => {
1399
1588
  return null;
1400
1589
  };
1401
1590
  function getDbHost(cfg) {
1402
- const { config, logger } = cfg;
1591
+ const { config } = cfg;
1592
+ const logger = config.logger;
1403
1593
  const { info } = Logger(config, "[db.host]");
1404
1594
  if (stringCheck(config?.db && config.db.host)) {
1405
1595
  logger && info(`${logger}[config] ${config?.db?.host}`);
@@ -1422,7 +1612,8 @@ function getDbHost(cfg) {
1422
1612
  return "db.thenile.dev";
1423
1613
  }
1424
1614
  function getDbPort(cfg) {
1425
- const { config, logger } = cfg;
1615
+ const { config } = cfg;
1616
+ const logger = config.logger;
1426
1617
  const { info } = Logger(config, "[db.port]");
1427
1618
  if (config?.db?.port && config.db.port != null) {
1428
1619
  logger && info(`${logger}[config] ${config?.db.port}`);
@@ -1460,6 +1651,8 @@ var Config = class {
1460
1651
  routes;
1461
1652
  handlers;
1462
1653
  paths;
1654
+ extensionCtx;
1655
+ extensions;
1463
1656
  logger;
1464
1657
  /**
1465
1658
  * Stores the set tenant id from Server for use in sub classes
@@ -1494,14 +1687,19 @@ var Config = class {
1494
1687
  routePrefix;
1495
1688
  db;
1496
1689
  // api: ApiConfig;
1497
- constructor(config, logger) {
1498
- const envVarConfig = { config, logger };
1690
+ constructor(config) {
1499
1691
  this.routePrefix = config?.routePrefix ?? "/api";
1500
- this.secureCookies = getSecureCookies(envVarConfig);
1501
- this.callbackUrl = getCallbackUrl(envVarConfig);
1502
1692
  this.debug = config?.debug;
1503
1693
  this.origin = config?.origin;
1694
+ this.extensions = config?.extensions;
1695
+ this.extensionCtx = config?.extensionCtx;
1504
1696
  this.serverOrigin = config?.origin ?? "http://localhost:3000";
1697
+ this.logger = config?.logger ?? Logger(this);
1698
+ const envVarConfig = {
1699
+ config: { ...config, logger: this.logger }
1700
+ };
1701
+ this.secureCookies = getSecureCookies(envVarConfig);
1702
+ this.callbackUrl = getCallbackUrl(envVarConfig);
1505
1703
  this.apiUrl = getApiUrl(envVarConfig);
1506
1704
  const user = getUsername(envVarConfig);
1507
1705
  const password = getPassword(envVarConfig);
@@ -1568,7 +1766,6 @@ var Config = class {
1568
1766
  };
1569
1767
  this.tenantId = config?.tenantId;
1570
1768
  this.userId = config?.userId;
1571
- this.logger = config?.logger;
1572
1769
  }
1573
1770
  };
1574
1771
 
@@ -1602,6 +1799,9 @@ var Eventer = class {
1602
1799
  }
1603
1800
  };
1604
1801
  var eventer = new Eventer();
1802
+ var updateTenantId = (tenantId) => {
1803
+ eventer.publish("tenantId" /* Tenant */, tenantId);
1804
+ };
1605
1805
  var watchTenantId = (cb) => eventer.subscribe("tenantId" /* Tenant */, cb);
1606
1806
  var watchUserId = (cb) => eventer.subscribe("userId" /* User */, cb);
1607
1807
  var evictPool = (val) => {
@@ -1861,7 +2061,7 @@ var Auth = class {
1861
2061
  }
1862
2062
  }
1863
2063
  async getCsrf(rawResponse = false) {
1864
- return await getCsrf(this.#config, rawResponse);
2064
+ return await obtainCsrf(this.#config, rawResponse);
1865
2065
  }
1866
2066
  async listProviders(rawResponse = false) {
1867
2067
  const res = await fetchProviders(this.#config);
@@ -1931,16 +2131,54 @@ var Auth = class {
1931
2131
  return res;
1932
2132
  }
1933
2133
  try {
1934
- return await res.clone().json();
2134
+ const json = await res.clone().json();
2135
+ if (json && typeof json === "object" && "tenants" in json) {
2136
+ const tenantId = json.tenants[0];
2137
+ if (tenantId) {
2138
+ updateTenantId(tenantId);
2139
+ }
2140
+ }
2141
+ return json;
1935
2142
  } catch {
1936
2143
  return res;
1937
2144
  }
1938
2145
  }
2146
+ async forgotPassword(req) {
2147
+ let email = "";
2148
+ const defaults = defaultCallbackUrl({
2149
+ config: this.#config
2150
+ });
2151
+ let callbackUrl = defaults.callbackUrl;
2152
+ let redirectUrl = defaults.redirectUrl;
2153
+ if ("email" in req) {
2154
+ email = req.email;
2155
+ }
2156
+ if ("callbackUrl" in req) {
2157
+ callbackUrl = req.callbackUrl ? req.callbackUrl : null;
2158
+ }
2159
+ if ("redirectUrl" in req) {
2160
+ redirectUrl = req.redirectUrl ? req.redirectUrl : null;
2161
+ }
2162
+ const body = JSON.stringify({
2163
+ email,
2164
+ redirectUrl,
2165
+ callbackUrl
2166
+ });
2167
+ const data = await fetchResetPassword(
2168
+ this.#config,
2169
+ "POST",
2170
+ body,
2171
+ new URLSearchParams(),
2172
+ false
2173
+ );
2174
+ return data;
2175
+ }
1939
2176
  async resetPassword(req) {
1940
2177
  let email = "";
1941
2178
  let password = "";
1942
- let callbackUrl = null;
1943
- let redirectUrl = null;
2179
+ const defaults = defaultCallbackUrl({ config: this.#config });
2180
+ let callbackUrl = defaults.callbackUrl;
2181
+ let redirectUrl = defaults.redirectUrl;
1944
2182
  if (req instanceof Request) {
1945
2183
  const body2 = await req.json();
1946
2184
  email = body2.email;
@@ -1969,19 +2207,6 @@ var Auth = class {
1969
2207
  redirectUrl = req.redirectUrl ? req.redirectUrl : null;
1970
2208
  }
1971
2209
  }
1972
- const fallbackCb = parseCallback(this.#config.headers);
1973
- if (fallbackCb) {
1974
- const [, value] = fallbackCb.split("=");
1975
- if (value) {
1976
- const parsedUrl = decodeURIComponent(value);
1977
- if (!redirectUrl) {
1978
- redirectUrl = `${new URL(parsedUrl).origin}${"/auth/reset-password" /* PASSWORD_RESET */}`;
1979
- }
1980
- }
1981
- if (!callbackUrl) {
1982
- callbackUrl = value;
1983
- }
1984
- }
1985
2210
  await this.getCsrf();
1986
2211
  const body = JSON.stringify({
1987
2212
  email,
@@ -2200,9 +2425,22 @@ function parseResetToken(headers) {
2200
2425
  const [, token] = /((__Secure-)?nile\.reset=[^;]+)/.exec(authCookie) ?? [];
2201
2426
  return token;
2202
2427
  }
2428
+ function defaultCallbackUrl({ config }) {
2429
+ let cb = null;
2430
+ let redirect = null;
2431
+ const fallbackCb = parseCallback(config.headers);
2432
+ if (fallbackCb) {
2433
+ const [, value] = fallbackCb.split("=");
2434
+ cb = decodeURIComponent(value);
2435
+ if (value) {
2436
+ redirect = `${new URL(cb).origin}${"/auth/reset-password" /* PASSWORD_RESET */}`;
2437
+ }
2438
+ }
2439
+ return { callbackUrl: cb, redirectUrl: redirect };
2440
+ }
2203
2441
 
2204
- // src/auth/getCsrf.ts
2205
- async function getCsrf(config, rawResponse = false) {
2442
+ // src/auth/obtainCsrf.ts
2443
+ async function obtainCsrf(config, rawResponse = false) {
2206
2444
  const res = await fetchCsrf(config);
2207
2445
  const csrfCook = parseCSRF(res.headers);
2208
2446
  if (csrfCook) {
@@ -2288,21 +2526,27 @@ var Users = class {
2288
2526
  return res;
2289
2527
  }
2290
2528
  }
2291
- async verifySelf(bypassEmail = process.env.NODE_ENV !== "production", rawResponse = false) {
2529
+ async verifySelf(options, rawResponse = false) {
2530
+ const bypassEmail = typeof options === "object" ? options.bypassEmail ?? process.env.NODE_ENV !== "production" : process.env.NODE_ENV !== "production";
2531
+ const callbackUrl = typeof options === "object" ? options.callbackUrl : defaultCallbackUrl2(this.#config).callbackUrl;
2292
2532
  try {
2293
2533
  const me = await this.getSelf();
2294
2534
  if (me instanceof Response) {
2295
2535
  return me;
2296
2536
  }
2297
- const res = await verifyEmailAddress(this.#config, me);
2537
+ const res = await verifyEmailAddress(
2538
+ this.#config,
2539
+ me,
2540
+ String(callbackUrl)
2541
+ );
2298
2542
  return res;
2299
2543
  } catch {
2300
2544
  this.#logger?.warn(
2301
- "Unable to verify email. The current user's email will be set to verified any way. Be sure to configure emails for production."
2545
+ "Unable to verify email. The current user's email will be set to verified anyway. Be sure to configure emails for production."
2302
2546
  );
2303
2547
  }
2304
2548
  if (bypassEmail) {
2305
- return await this.updateSelf({ emailVerified: true }, rawResponse);
2549
+ return this.updateSelf({ emailVerified: true }, rawResponse);
2306
2550
  }
2307
2551
  this.#logger.error(
2308
2552
  "Unable to verify email address. Configure your SMTP server in the console."
@@ -2310,19 +2554,34 @@ var Users = class {
2310
2554
  return void 0;
2311
2555
  }
2312
2556
  };
2313
- async function verifyEmailAddress(config, user) {
2557
+ async function verifyEmailAddress(config, user, callback) {
2314
2558
  config.headers.set("content-type", "application/x-www-form-urlencoded");
2315
- const { csrfToken } = await getCsrf(config);
2559
+ const { csrfToken } = await obtainCsrf(config);
2560
+ const defaults = defaultCallbackUrl2(config);
2561
+ const callbackUrl = callback ?? String(defaults.callbackUrl);
2316
2562
  const res = await fetchVerifyEmail(
2317
2563
  config,
2318
2564
  "POST",
2319
- new URLSearchParams({ csrfToken, email: user.email }).toString()
2565
+ new URLSearchParams({
2566
+ csrfToken,
2567
+ email: user.email,
2568
+ callbackUrl
2569
+ }).toString()
2320
2570
  );
2321
2571
  if (res.status > 299) {
2322
2572
  throw new Error(await res.text());
2323
2573
  }
2324
2574
  return res;
2325
2575
  }
2576
+ function defaultCallbackUrl2(config) {
2577
+ let cb = null;
2578
+ const fallbackCb = parseCallback(config.headers);
2579
+ if (fallbackCb) {
2580
+ const [, value] = fallbackCb.split("=");
2581
+ cb = decodeURIComponent(value);
2582
+ }
2583
+ return { callbackUrl: cb };
2584
+ }
2326
2585
 
2327
2586
  // src/tenants/index.ts
2328
2587
  var Tenants = class {
@@ -2445,6 +2704,74 @@ var Tenants = class {
2445
2704
  rawResponse || typeof req === "boolean" && req
2446
2705
  );
2447
2706
  }
2707
+ async invites() {
2708
+ const res = await fetchInvites(this.#config);
2709
+ return responseHandler(res);
2710
+ }
2711
+ async invite(req, rawResponse) {
2712
+ const { csrfToken } = await obtainCsrf(this.#config);
2713
+ const defaults = defaultCallbackUrl3(this.#config);
2714
+ let identifier = req;
2715
+ let callbackUrl = defaults.callbackUrl;
2716
+ let redirectUrl = defaults.redirectUrl;
2717
+ if (typeof req === "object") {
2718
+ if ("email" in req) {
2719
+ identifier = req.email;
2720
+ }
2721
+ if ("callbackUrl" in req) {
2722
+ callbackUrl = req.callbackUrl ? req.callbackUrl : "";
2723
+ }
2724
+ if ("redirectUrl" in req) {
2725
+ redirectUrl = req.redirectUrl ? req.redirectUrl : "";
2726
+ }
2727
+ }
2728
+ this.#config.headers.set(
2729
+ "Content-Type",
2730
+ "application/x-www-form-urlencoded"
2731
+ );
2732
+ const res = await fetchInvite(
2733
+ this.#config,
2734
+ "POST",
2735
+ new URLSearchParams({
2736
+ identifier,
2737
+ csrfToken,
2738
+ callbackUrl,
2739
+ redirectUrl
2740
+ }).toString()
2741
+ );
2742
+ return responseHandler(res, rawResponse);
2743
+ }
2744
+ async acceptInvite(req, rawResponse) {
2745
+ if (!req) {
2746
+ throw new Error("The identifier and token are required.");
2747
+ }
2748
+ const { identifier, token } = req;
2749
+ const defaults = defaultCallbackUrl3(this.#config);
2750
+ const callbackUrl = String(defaults.callbackUrl);
2751
+ const res = await fetchInvite(
2752
+ this.#config,
2753
+ "PUT",
2754
+ new URLSearchParams({
2755
+ identifier,
2756
+ token,
2757
+ callbackUrl
2758
+ }).toString()
2759
+ );
2760
+ return responseHandler(res, rawResponse);
2761
+ }
2762
+ async deleteInvite(req) {
2763
+ let id = "";
2764
+ if (typeof req === "object") {
2765
+ id = req.id;
2766
+ } else {
2767
+ id = req;
2768
+ }
2769
+ if (!id) {
2770
+ throw new Error("An invite id is required.");
2771
+ }
2772
+ const res = await fetchInvite(this.#config, "DELETE", id);
2773
+ return responseHandler(res, true);
2774
+ }
2448
2775
  #handleContext(req) {
2449
2776
  if (typeof req === "object") {
2450
2777
  if ("tenantId" in req) {
@@ -2466,31 +2793,47 @@ async function responseHandler(res, rawResponse) {
2466
2793
  return res;
2467
2794
  }
2468
2795
  }
2796
+ function defaultCallbackUrl3(config) {
2797
+ let cb = null;
2798
+ let redirect = null;
2799
+ const fallbackCb = parseCallback(config.headers);
2800
+ if (fallbackCb) {
2801
+ const [, value] = fallbackCb.split("=");
2802
+ cb = decodeURIComponent(value);
2803
+ if (value) {
2804
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace(
2805
+ "{tenantId}",
2806
+ String(config.tenantId)
2807
+ )}`;
2808
+ }
2809
+ }
2810
+ return { callbackUrl: cb, redirectUrl: redirect };
2811
+ }
2469
2812
 
2470
2813
  // src/api/handlers/withContext/index.ts
2471
2814
  function handlersWithContext(config) {
2472
- const GET6 = GETTER(config.routes, config);
2473
- const POST5 = POSTER(config.routes, config);
2474
- const DELETE4 = DELETER(config.routes, config);
2475
- const PUT5 = PUTER(config.routes, config);
2815
+ const GET7 = GETTER(config.routes, config);
2816
+ const POST6 = POSTER(config.routes, config);
2817
+ const DELETE5 = DELETER(config.routes, config);
2818
+ const PUT6 = PUTER(config.routes, config);
2476
2819
  return {
2477
2820
  GET: async (req) => {
2478
- const response = await GET6(req);
2821
+ const response = await GET7(req);
2479
2822
  const updatedConfig = updateConfig(response, config);
2480
2823
  return { response, nile: new Server(updatedConfig) };
2481
2824
  },
2482
2825
  POST: async (req) => {
2483
- const response = await POST5(req);
2826
+ const response = await POST6(req);
2484
2827
  const updatedConfig = updateConfig(response, config);
2485
2828
  return { response, nile: new Server(updatedConfig) };
2486
2829
  },
2487
2830
  DELETE: async (req) => {
2488
- const response = await DELETE4(req);
2831
+ const response = await DELETE5(req);
2489
2832
  const updatedConfig = updateConfig(response, config);
2490
2833
  return { response, nile: new Server(updatedConfig) };
2491
2834
  },
2492
2835
  PUT: async (req) => {
2493
- const response = await PUT5(req);
2836
+ const response = await PUT6(req);
2494
2837
  const updatedConfig = updateConfig(response, config);
2495
2838
  return { response, nile: new Server(updatedConfig) };
2496
2839
  }
@@ -2508,8 +2851,8 @@ function updateConfig(response, config) {
2508
2851
  }
2509
2852
  const setCookies = [];
2510
2853
  if (response?.headers) {
2511
- for (const [key14, value] of response.headers) {
2512
- if (key14.toLowerCase() === "set-cookie") {
2854
+ for (const [key17, value] of response.headers) {
2855
+ if (key17.toLowerCase() === "set-cookie") {
2513
2856
  setCookies.push(value);
2514
2857
  }
2515
2858
  }
@@ -2525,6 +2868,36 @@ function updateConfig(response, config) {
2525
2868
  };
2526
2869
  }
2527
2870
 
2871
+ // src/api/utils/extensions.ts
2872
+ function bindHandleOnRequest(instance) {
2873
+ return async function handleOnRequest(config, _init, params) {
2874
+ if (config.extensions) {
2875
+ for (const create2 of config.extensions) {
2876
+ const ext = await create2(instance);
2877
+ if (ext.onRequest) {
2878
+ const modified = await ext.onRequest(_init.request);
2879
+ if (modified?.headers) {
2880
+ const modHeaders = new Headers(modified.headers);
2881
+ const cookie = modHeaders.get("cookie");
2882
+ if (cookie) {
2883
+ params.headers.set("cookie", cookie);
2884
+ config.logger.debug(
2885
+ `extension ${ext.id ?? create2.name} modified cookie`
2886
+ );
2887
+ }
2888
+ }
2889
+ }
2890
+ config.logger.debug(`extension ${ext.id ?? create2.name} ran onRequest`);
2891
+ }
2892
+ }
2893
+ };
2894
+ }
2895
+ function buildExtensionConfig(instance) {
2896
+ return {
2897
+ handleOnRequest: bindHandleOnRequest(instance)
2898
+ };
2899
+ }
2900
+
2528
2901
  // src/Server.ts
2529
2902
  var Server = class {
2530
2903
  users;
@@ -2536,7 +2909,10 @@ var Server = class {
2536
2909
  #manager;
2537
2910
  #headers;
2538
2911
  constructor(config) {
2539
- this.#config = new Config(config, "[initial config]");
2912
+ this.#config = new Config({
2913
+ ...config,
2914
+ extensionCtx: buildExtensionConfig(this)
2915
+ });
2540
2916
  watchTenantId((tenantId) => {
2541
2917
  if (tenantId !== this.#config.tenantId) {
2542
2918
  this.#config.tenantId = tenantId;
@@ -2661,32 +3037,33 @@ var Server = class {
2661
3037
  } else if (config?.headers) {
2662
3038
  headers = config?.headers;
2663
3039
  if (config && config.origin) {
2664
- this.#headers.set(X_NILE_ORIGIN, config.origin);
3040
+ this.#headers.set(HEADER_ORIGIN, config.origin);
2665
3041
  }
2666
3042
  if (config && config.secureCookies != null) {
2667
- this.#headers.set(X_NILE_SECURECOOKIES, String(config.secureCookies));
3043
+ this.#headers.set(HEADER_SECURE_COOKIES, String(config.secureCookies));
2668
3044
  }
2669
3045
  }
2670
3046
  if (headers instanceof Headers) {
2671
- headers.forEach((value, key14) => {
2672
- updates.push([key14.toLowerCase(), value]);
3047
+ headers.forEach((value, key17) => {
3048
+ updates.push([key17.toLowerCase(), value]);
2673
3049
  });
2674
3050
  } else {
2675
- for (const [key14, value] of Object.entries(headers ?? {})) {
2676
- updates.push([key14.toLowerCase(), value]);
3051
+ for (const [key17, value] of Object.entries(headers ?? {})) {
3052
+ updates.push([key17.toLowerCase(), value]);
2677
3053
  }
2678
3054
  }
2679
3055
  const merged = {};
2680
- this.#headers?.forEach((value, key14) => {
2681
- if (key14.toLowerCase() !== "cookie") {
2682
- merged[key14.toLowerCase()] = value;
3056
+ this.#config.tenantId = getTenantFromHttp(this.#headers, this.#config);
3057
+ this.#headers?.forEach((value, key17) => {
3058
+ if (key17.toLowerCase() !== "cookie") {
3059
+ merged[key17.toLowerCase()] = value;
2683
3060
  }
2684
3061
  });
2685
- for (const [key14, value] of updates) {
2686
- merged[key14] = value;
3062
+ for (const [key17, value] of updates) {
3063
+ merged[key17] = value;
2687
3064
  }
2688
- for (const [key14, value] of Object.entries(merged)) {
2689
- this.#headers.set(key14, value);
3065
+ for (const [key17, value] of Object.entries(merged)) {
3066
+ this.#headers.set(key17, value);
2690
3067
  }
2691
3068
  this.#config.headers = this.#headers;
2692
3069
  }
@@ -2708,6 +3085,6 @@ function create(config) {
2708
3085
  return server;
2709
3086
  }
2710
3087
 
2711
- export { APIErrorErrorCodeEnum, LoginUserResponseTokenTypeEnum, create as Nile, Server, parseCSRF, parseCallback, parseToken };
3088
+ export { APIErrorErrorCodeEnum, HEADER_ORIGIN, HEADER_SECURE_COOKIES, LoginUserResponseTokenTypeEnum, create as Nile, Server, TENANT_COOKIE, USER_COOKIE, parseCSRF, parseCallback, parseToken };
2712
3089
  //# sourceMappingURL=index.mjs.map
2713
3090
  //# sourceMappingURL=index.mjs.map