@niledatabase/server 5.3.3-alpha.1 → 5.3.3-alpha.2

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
@@ -15,17 +15,34 @@ var ExtensionState = /* @__PURE__ */ ((ExtensionState2) => {
15
15
  var APIErrorErrorCodeEnum = {
16
16
  InternalError: "internal_error",
17
17
  BadRequest: "bad_request",
18
+ UnsupportedOperation: "unsupported_operation",
18
19
  EntityNotFound: "entity_not_found",
19
20
  DuplicateEntity: "duplicate_entity",
20
21
  InvalidCredentials: "invalid_credentials",
21
22
  UnknownOidcProvider: "unknown_oidc_provider",
23
+ UnknownOidcParty: "unknown_oidc_party",
22
24
  ProviderAlreadyExists: "provider_already_exists",
23
25
  ProviderConfigError: "provider_config_error",
24
26
  ProviderMismatch: "provider_mismatch",
25
27
  ProviderUpdateError: "provider_update_error",
28
+ ProviderDisabled: "provider_disabled",
26
29
  SessionStateMissing: "session_state_missing",
27
30
  SessionStateMismatch: "session_state_mismatch",
28
- OidcCodeMissing: "oidc_code_missing"
31
+ OidcCodeMissing: "oidc_code_missing",
32
+ TenantNotFound: "tenant_not_found",
33
+ ConstraintViolation: "constraint_violation",
34
+ SqlException: "sql_exception",
35
+ DbCreationFailure: "db_creation_failure",
36
+ DbStatusFailure: "db_status_failure",
37
+ DbInitializationFailure: "db_initialization_failure",
38
+ DbConfigMissing: "db_config_missing",
39
+ UnauthorizedWorkspaceAccess: "unauthorized_workspace_access",
40
+ EmailSendFailure: "email_send_failure",
41
+ JdbcException: "jdbc_exception",
42
+ OidcException: "oidc_exception",
43
+ RegionMismatch: "region_mismatch",
44
+ CredentialCreationFailure: "credential_creation_failure",
45
+ CredentialPropagationFailure: "credential_propagation_failure"
29
46
  };
30
47
 
31
48
  // src/users/types.ts
@@ -303,24 +320,47 @@ function matchesLog(configRoutes, request2) {
303
320
  }
304
321
 
305
322
  // src/api/utils/extensions.ts
323
+ var extensionInstanceCache = /* @__PURE__ */ new WeakMap();
324
+ function resolveExtension(create2, instance) {
325
+ let perServer = extensionInstanceCache.get(instance);
326
+ if (!perServer) {
327
+ perServer = /* @__PURE__ */ new WeakMap();
328
+ extensionInstanceCache.set(instance, perServer);
329
+ }
330
+ let ext = perServer.get(create2);
331
+ if (!ext) {
332
+ ext = create2(instance);
333
+ perServer.set(create2, ext);
334
+ }
335
+ return ext;
336
+ }
337
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
338
+ "host",
339
+ "content-length",
340
+ "transfer-encoding",
341
+ "connection",
342
+ "keep-alive",
343
+ "upgrade"
344
+ ]);
306
345
  function getRequestConfig(params) {
307
- if (typeof params[1] === "object") {
346
+ if (params[1] !== null && typeof params[1] === "object") {
308
347
  return params[1];
309
348
  }
310
349
  return {};
311
350
  }
312
351
  function bindRunExtensions(instance) {
313
352
  return async function runExtensions(toRun, config, params, _init) {
314
- const { debug } = config.logger("[EXTENSIONS]");
353
+ const { debug, warn } = config.logger("[EXTENSIONS]");
315
354
  const extensionConfig = getRequestConfig(
316
355
  Array.isArray(params) ? params : [null, params]
317
356
  );
357
+ let chainedResponse = void 0;
318
358
  if (config.extensions) {
319
359
  for (const create2 of config.extensions) {
320
360
  if (typeof create2 !== "function") {
321
361
  continue;
322
362
  }
323
- const ext = create2(instance);
363
+ const ext = resolveExtension(create2, instance);
324
364
  if (extensionConfig.disableExtensions?.includes(ext.id)) {
325
365
  continue;
326
366
  }
@@ -351,40 +391,86 @@ function bindRunExtensions(instance) {
351
391
  continue;
352
392
  }
353
393
  const previousHeaders = new Headers(previousContext.headers);
394
+ let returnedInit = void 0;
354
395
  try {
355
- await ext.onRequest(_init.request, ctx);
356
- } catch {
396
+ returnedInit = await ext.onRequest(_init.request, ctx);
397
+ } catch (err) {
398
+ warn(`${ext.id ?? create2.name} onRequest failed`, {
399
+ message: err instanceof Error ? err.message : String(err)
400
+ });
357
401
  }
358
402
  const updatedContext = ctx.get();
359
- if (updatedContext?.headers) {
360
- const cookie = updatedContext.headers.get("cookie");
361
- if (cookie && param.headers) {
403
+ const paramObj = param && typeof param === "object" ? param : void 0;
404
+ if (updatedContext?.headers && paramObj?.headers instanceof Headers) {
405
+ const prevCookie = previousHeaders.get("cookie");
406
+ const nextCookie = updatedContext.headers.get("cookie");
407
+ if (nextCookie && nextCookie !== prevCookie) {
362
408
  const updatedCookies = mergeCookies(
363
- previousHeaders?.get("cookie"),
364
- updatedContext.headers.get("cookie")
409
+ prevCookie,
410
+ paramObj.headers.get("cookie"),
411
+ nextCookie
365
412
  );
366
- param.headers.set("cookie", updatedCookies);
413
+ if (updatedCookies) {
414
+ paramObj.headers.set("cookie", updatedCookies);
415
+ }
367
416
  }
368
- if (updatedContext.tenantId && param.headers) {
369
- param.headers.set(
370
- TENANT_COOKIE,
371
- String(updatedContext.headers.get(TENANT_COOKIE))
372
- );
417
+ updatedContext.headers.forEach((value, key18) => {
418
+ const lower = key18.toLowerCase();
419
+ if (lower === "cookie" || HOP_BY_HOP_HEADERS.has(lower)) {
420
+ return;
421
+ }
422
+ if (previousHeaders.get(key18) !== value) {
423
+ paramObj.headers?.set(key18, value);
424
+ }
425
+ });
426
+ if (updatedContext.tenantId) {
427
+ const tenantHeader = updatedContext.headers.get(TENANT_COOKIE) ?? String(updatedContext.tenantId);
428
+ paramObj.headers.set(TENANT_COOKIE, tenantHeader);
429
+ }
430
+ } else if (updatedContext?.tenantId && paramObj?.headers instanceof Headers) {
431
+ paramObj.headers.set(
432
+ TENANT_COOKIE,
433
+ String(updatedContext.tenantId)
434
+ );
435
+ }
436
+ if (returnedInit && typeof returnedInit === "object" && paramObj) {
437
+ const { headers: returnedHeaders, ...restInit } = returnedInit;
438
+ Object.assign(paramObj, restInit);
439
+ if (returnedHeaders && paramObj.headers instanceof Headers) {
440
+ new Headers(returnedHeaders).forEach((value, key18) => {
441
+ if (key18.toLowerCase() === "cookie") {
442
+ const merged = mergeCookies(
443
+ paramObj.headers?.get("cookie"),
444
+ value
445
+ );
446
+ if (merged) {
447
+ paramObj.headers?.set("cookie", merged);
448
+ }
449
+ } else {
450
+ paramObj.headers?.set(key18, value);
451
+ }
452
+ });
373
453
  }
374
- ctx.set({ headers: param.headers });
375
454
  }
376
455
  debug(`${ext.id ?? create2.name} ran onRequest`);
377
456
  }
378
457
  if (ext.onResponse && toRun === "onResponse" /* onResponse */) {
379
- const result = await ext.onResponse(param, ctx);
458
+ let responseParam = param;
459
+ if (chainedResponse instanceof Response && param && typeof param === "object") {
460
+ responseParam = {
461
+ ...param,
462
+ response: chainedResponse
463
+ };
464
+ }
465
+ const result = await ext.onResponse(responseParam, ctx);
380
466
  debug(`${ext.id ?? create2.name} ran onResponse`);
381
467
  if (result != null) {
382
- return result;
468
+ chainedResponse = result;
383
469
  }
384
470
  }
385
471
  }
386
472
  }
387
- return void 0;
473
+ return chainedResponse;
388
474
  };
389
475
  }
390
476
  function buildExtensionConfig(instance) {
@@ -396,8 +482,12 @@ function mergeCookies(...cookieStrings) {
396
482
  const cookieMap = /* @__PURE__ */ new Map();
397
483
  for (const str of cookieStrings) {
398
484
  if (!str) continue;
399
- for (const part of str.split(";")) {
400
- const [key18, value] = part.split("=").map((s) => s.trim());
485
+ for (const part of str.split(/;\s*/)) {
486
+ if (!part) continue;
487
+ const eqIdx = part.indexOf("=");
488
+ if (eqIdx <= 0) continue;
489
+ const key18 = part.slice(0, eqIdx).trim();
490
+ const value = part.slice(eqIdx + 1).trim();
401
491
  if (key18 && value) cookieMap.set(key18, value);
402
492
  }
403
493
  }
@@ -425,6 +515,7 @@ async function runExtensionContext(config, options) {
425
515
  // src/api/utils/request-context.ts
426
516
  var storage = new AsyncLocalStorage();
427
517
  var hydratedStores = /* @__PURE__ */ new WeakSet();
518
+ var storeOwners = /* @__PURE__ */ new WeakMap();
428
519
  Object.freeze({
429
520
  headers: new Headers(),
430
521
  tenantId: void 0,
@@ -450,6 +541,10 @@ var ctx = {
450
541
  if (hydratedStores.has(inputCtx)) {
451
542
  hydratedStores.add(merged);
452
543
  }
544
+ const owner = storeOwners.get(inputCtx);
545
+ if (owner) {
546
+ storeOwners.set(merged, owner);
547
+ }
453
548
  return storage.run(merged, fn);
454
549
  },
455
550
  get: () => {
@@ -497,7 +592,19 @@ var ctx = {
497
592
  getLastUsed: () => ctx.get()
498
593
  };
499
594
  function shouldUseOwnScopedContext(config, activeStore) {
500
- return Boolean(config.isScoped) && (!activeStore || config.boundStore !== activeStore);
595
+ if (!config.isScoped) {
596
+ return false;
597
+ }
598
+ if (!activeStore) {
599
+ return true;
600
+ }
601
+ if (config.boundStore === activeStore) {
602
+ return false;
603
+ }
604
+ if (storeOwners.get(activeStore) === config) {
605
+ return false;
606
+ }
607
+ return true;
501
608
  }
502
609
  async function resolveNileContext(config, options = {}) {
503
610
  const active = storage.getStore();
@@ -564,6 +671,9 @@ async function withNileContext(config, fn, nameOrOptions = "unknown") {
564
671
  }
565
672
  const resolved = await resolveNileContext(config, options);
566
673
  hydratedStores.add(resolved);
674
+ if (config.isScoped) {
675
+ storeOwners.set(resolved, config);
676
+ }
567
677
  const shouldSyncToScopedConfig = useOwnScoped && !options.overrides && !options.resetBase;
568
678
  return ctx.run(resolved, async () => {
569
679
  try {
@@ -660,10 +770,10 @@ async function request(url, _init, config) {
660
770
  }
661
771
  }
662
772
  const params = { ...init };
663
- if (params.method?.toLowerCase() === "post" || params.method?.toLowerCase() === "put") {
773
+ const lowerMethod = params.method?.toLowerCase();
774
+ const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
775
+ if (lowerMethod === "post" || lowerMethod === "put" || lowerMethod === "delete" && bodyStream != null) {
664
776
  try {
665
- updatedHeaders.set("content-type", "application/json");
666
- const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
667
777
  let bodyText;
668
778
  if (bodyStream === request2.body) {
669
779
  try {
@@ -674,11 +784,17 @@ async function request(url, _init, config) {
674
784
  } else {
675
785
  bodyText = await new Response(bodyStream).text();
676
786
  }
677
- try {
678
- params.body = JSON.stringify(JSON.parse(bodyText));
679
- } catch {
680
- updatedHeaders.set("content-type", "application/x-www-form-urlencoded");
681
- params.body = bodyText;
787
+ if (lowerMethod !== "delete" || bodyText.length > 0) {
788
+ updatedHeaders.set("content-type", "application/json");
789
+ try {
790
+ params.body = JSON.stringify(JSON.parse(bodyText));
791
+ } catch {
792
+ updatedHeaders.set(
793
+ "content-type",
794
+ "application/x-www-form-urlencoded"
795
+ );
796
+ params.body = bodyText;
797
+ }
682
798
  }
683
799
  } catch (e) {
684
800
  error("Failed to parse request body");
@@ -904,11 +1020,13 @@ function getTokenFromCookie(headers, cookieKey) {
904
1020
  if (!cookieHeader) {
905
1021
  return null;
906
1022
  }
907
- const cookies = cookieHeader.split("; ");
1023
+ const cookies = cookieHeader.split(/;\s*/);
908
1024
  for (const parts of cookies) {
909
- const cookieParts = parts.split("=");
910
- const name = cookieParts[0];
911
- const value = cookieParts.slice(1).join("=");
1025
+ if (!parts) continue;
1026
+ const eqIdx = parts.indexOf("=");
1027
+ if (eqIdx <= 0) continue;
1028
+ const name = parts.slice(0, eqIdx).trim();
1029
+ const value = parts.slice(eqIdx + 1);
912
1030
  if (name === cookieKey) {
913
1031
  return value;
914
1032
  }
@@ -1012,7 +1130,11 @@ async function POST2(config, init) {
1012
1130
  if (!isUUID2(tenantId)) {
1013
1131
  return new Response("Invalid tenantId", { status: 400 });
1014
1132
  }
1015
- init.body = JSON.stringify({ email: session.email });
1133
+ const hasIncomingBody = init.body != null || init.request.body != null;
1134
+ if (!hasIncomingBody) {
1135
+ const sessionEmail = session.email ?? session.user?.email;
1136
+ init.body = JSON.stringify({ email: sessionEmail });
1137
+ }
1016
1138
  init.method = "POST";
1017
1139
  const url = apiRoutes(config.apiUrl).TENANT_USERS(tenantId);
1018
1140
  return await request(url, init, config);
@@ -1060,7 +1182,8 @@ async function fetchTenantUsers(config, method, payload) {
1060
1182
  if (params?.tenantId) {
1061
1183
  q.set("tenantId", params.tenantId);
1062
1184
  }
1063
- const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}`;
1185
+ const queryString = q.toString();
1186
+ const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}${queryString ? `?${queryString}` : ""}`;
1064
1187
  const m = method;
1065
1188
  const init = {
1066
1189
  method: m,
@@ -1080,7 +1203,7 @@ async function PUT3(config, init) {
1080
1203
  if (!isUUID2(tenantId)) {
1081
1204
  return new Response("Invalid tenantId", { status: 400 });
1082
1205
  }
1083
- if (yurl.searchParams.size > 0) {
1206
+ if (init.request.method === "GET" && yurl.searchParams.size > 0) {
1084
1207
  init.body = new URLSearchParams(yurl.searchParams).toString();
1085
1208
  }
1086
1209
  init.method = "PUT";
@@ -1093,10 +1216,7 @@ async function PUT3(config, init) {
1093
1216
  headers: res?.headers
1094
1217
  });
1095
1218
  }
1096
- return new Response(res?.body, {
1097
- status: res?.status,
1098
- headers: res?.headers
1099
- });
1219
+ return res;
1100
1220
  }
1101
1221
 
1102
1222
  // src/api/routes/tenants/[tenantId]/invite/POST.ts
@@ -1487,10 +1607,7 @@ async function route11(req, config) {
1487
1607
  headers: res.headers
1488
1608
  });
1489
1609
  }
1490
- return new Response(res.body, {
1491
- status: res.status ?? 502,
1492
- headers: res.headers
1493
- });
1610
+ return res;
1494
1611
  } catch (e) {
1495
1612
  error("an error has occurred", {
1496
1613
  message: e instanceof Error ? e.message : String(e)
@@ -1603,10 +1720,7 @@ async function route15(req, config) {
1603
1720
  headers: res?.headers
1604
1721
  });
1605
1722
  }
1606
- return new Response(res?.body, {
1607
- status: res?.status,
1608
- headers: res?.headers
1609
- });
1723
+ return res;
1610
1724
  }
1611
1725
  function matches15(configRoutes, request2) {
1612
1726
  return urlMatches(request2.url, configRoutes.PASSWORD_RESET);
@@ -1648,10 +1762,7 @@ async function route16(req, config) {
1648
1762
  headers: res?.headers
1649
1763
  });
1650
1764
  }
1651
- return new Response(res?.body, {
1652
- status: res?.status,
1653
- headers: res?.headers
1654
- });
1765
+ return res;
1655
1766
  }
1656
1767
  function matches16(configRoutes, request2) {
1657
1768
  return urlMatches(request2.url, configRoutes[key13]);
@@ -1712,7 +1823,7 @@ function GETTER(configRoutes, config) {
1712
1823
  const req = params[0] instanceof Request ? params[0] : null;
1713
1824
  if (!req) {
1714
1825
  error("Proxy requests failed, a Request object was not passed.");
1715
- return;
1826
+ return new Response("Invalid request", { status: 400 });
1716
1827
  }
1717
1828
  if (matches(configRoutes, req)) {
1718
1829
  info("matches me");
@@ -1791,7 +1902,7 @@ async function POST5(config, init) {
1791
1902
  return await request(url, init, config);
1792
1903
  }
1793
1904
 
1794
- // src/api/routes/signup/index.tsx
1905
+ // src/api/routes/signup/index.ts
1795
1906
  var key15 = "SIGNUP";
1796
1907
  async function route18(request2, config) {
1797
1908
  switch (request2.method) {
@@ -1838,7 +1949,7 @@ function POSTER(configRoutes, config) {
1838
1949
  const req = params[0] instanceof Request ? params[0] : null;
1839
1950
  if (!req) {
1840
1951
  error("Proxy requests failed, a Request object was not passed.");
1841
- return;
1952
+ return new Response("Invalid request", { status: 400 });
1842
1953
  }
1843
1954
  if (matchesLog(configRoutes, req)) {
1844
1955
  if (!config.debug) {
@@ -2084,7 +2195,7 @@ function DELETER(configRoutes, config) {
2084
2195
  const req = params[0] instanceof Request ? params[0] : null;
2085
2196
  if (!req) {
2086
2197
  error("Proxy requests failed, a Request object was not passed.");
2087
- return;
2198
+ return new Response("Invalid request", { status: 400 });
2088
2199
  }
2089
2200
  if (matches20(configRoutes, req)) {
2090
2201
  info("matches tenant invite id");
@@ -2126,7 +2237,7 @@ function PUTER(configRoutes, config) {
2126
2237
  const req = params[0] instanceof Request ? params[0] : null;
2127
2238
  if (!req) {
2128
2239
  error("Proxy requests failed, a Request object was not passed.");
2129
- return;
2240
+ return new Response("Invalid request", { status: 400 });
2130
2241
  }
2131
2242
  if (matches4(configRoutes, req)) {
2132
2243
  info("matches tenant invite");
@@ -2198,8 +2309,16 @@ var getSecureCookies = (cfg) => {
2198
2309
  if (config?.secureCookies != null) {
2199
2310
  return config?.secureCookies;
2200
2311
  }
2201
- if (stringCheck(process.env.NILEDB_SECURECOOKIES)) {
2202
- return Boolean(process.env.NILEDB_SECURECOOKIES);
2312
+ const envSecure = stringCheck(process.env.NILEDB_SECURECOOKIES);
2313
+ if (envSecure !== void 0) {
2314
+ const normalized = envSecure.trim().toLowerCase();
2315
+ if (normalized === "false" || normalized === "0") {
2316
+ return false;
2317
+ }
2318
+ if (normalized === "true" || normalized === "1") {
2319
+ return true;
2320
+ }
2321
+ return Boolean(envSecure);
2203
2322
  }
2204
2323
  return void 0;
2205
2324
  };
@@ -2221,7 +2340,7 @@ var getUsername = (cfg) => {
2221
2340
  try {
2222
2341
  const url = new URL(pg2);
2223
2342
  if (url.username) {
2224
- return url.username;
2343
+ return decodeURIComponent(url.username);
2225
2344
  }
2226
2345
  } catch (e) {
2227
2346
  }
@@ -2248,7 +2367,7 @@ var getPassword = (cfg) => {
2248
2367
  try {
2249
2368
  const url = new URL(pg2);
2250
2369
  if (url.password) {
2251
- return url.password;
2370
+ return decodeURIComponent(url.password);
2252
2371
  }
2253
2372
  } catch (e) {
2254
2373
  }
@@ -2269,15 +2388,19 @@ var getDatabaseName = (cfg) => {
2269
2388
  info(`[NILEDB_NAME] ${name}`);
2270
2389
  return name;
2271
2390
  }
2272
- if (process.env.NILEDB_POSTGRES_URL) {
2391
+ const pg2 = stringCheck(process.env.NILEDB_POSTGRES_URL);
2392
+ if (pg2) {
2273
2393
  try {
2274
- const pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
2275
- return pgUrl.pathname.substring(1);
2394
+ const pgUrl = new URL(pg2);
2395
+ const dbName = decodeURIComponent(pgUrl.pathname.replace(/^\/+/, ""));
2396
+ if (dbName) {
2397
+ return dbName;
2398
+ }
2276
2399
  } catch (e) {
2277
2400
  }
2278
2401
  }
2279
2402
  throw new Error(
2280
- "A database name is required. Set NILEDB_PASSWORD as an environment variable."
2403
+ "A database name is required. Set NILEDB_NAME as an environment variable."
2281
2404
  );
2282
2405
  };
2283
2406
  var getTenantId = (cfg) => {
@@ -2395,7 +2518,7 @@ var Config = class {
2395
2518
  this.routePrefix = config?.routePrefix ?? "/api";
2396
2519
  this.debug = config?.debug;
2397
2520
  this.origin = config?.origin;
2398
- this.extensions = config?.extensions;
2521
+ this.extensions = config?.extensions ? [...config.extensions] : void 0;
2399
2522
  this.skipHostHeader = config?.skipHostHeader;
2400
2523
  this.extensionCtx = config?.extensionCtx;
2401
2524
  this.serverOrigin = config?.origin ?? "http://localhost:3000";
@@ -2525,7 +2648,6 @@ var eventer = new Eventer();
2525
2648
  var evictPool = (val) => {
2526
2649
  eventer.publish("EvictPool" /* EvictPool */, val);
2527
2650
  };
2528
- var watchEvictPool = (cb) => eventer.subscribe("EvictPool" /* EvictPool */, cb);
2529
2651
  var PoolWithLogger = class extends pg.Pool {
2530
2652
  nileConfig;
2531
2653
  logger;
@@ -2649,6 +2771,7 @@ var PoolWithLogger = class extends pg.Pool {
2649
2771
  };
2650
2772
 
2651
2773
  // src/db/NileInstance.ts
2774
+ var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
2652
2775
  var NileDatabase = class {
2653
2776
  pool;
2654
2777
  tenantId;
@@ -2657,9 +2780,13 @@ var NileDatabase = class {
2657
2780
  logger;
2658
2781
  timer;
2659
2782
  config;
2660
- constructor(config, logger, id, dbContext) {
2783
+ isShuttingDown = false;
2784
+ shutdownPromise = null;
2785
+ onEvict;
2786
+ constructor(config, logger, id, dbContext, onEvict) {
2661
2787
  this.logger = logger("[NileInstance]");
2662
2788
  this.id = id;
2789
+ this.onEvict = onEvict;
2663
2790
  this.tenantId = assertValidUUID(dbContext?.tenantId, "tenantId");
2664
2791
  this.userId = assertValidUUID(dbContext?.userId, "userId");
2665
2792
  if (this.userId && !this.tenantId) {
@@ -2670,10 +2797,12 @@ var NileDatabase = class {
2670
2797
  const poolConfig = {
2671
2798
  min: 0,
2672
2799
  max: 10,
2673
- idleTimeoutMillis: 3e4,
2800
+ idleTimeoutMillis: DEFAULT_IDLE_TIMEOUT_MS,
2674
2801
  ...config
2675
2802
  };
2676
- const { afterCreate, ...remaining } = poolConfig;
2803
+ const remaining = { ...poolConfig };
2804
+ delete remaining.afterCreate;
2805
+ delete remaining.maxPools;
2677
2806
  this.config = remaining;
2678
2807
  const cloned = { ...config };
2679
2808
  cloned.password = "***";
@@ -2682,63 +2811,88 @@ var NileDatabase = class {
2682
2811
  tenantId: this.tenantId,
2683
2812
  userId: this.userId
2684
2813
  });
2685
- if (typeof afterCreate === "function") {
2686
- this.logger.warn(
2687
- "Providing an pool configuration will stop automatic tenant context setting."
2688
- );
2689
- }
2690
2814
  this.startTimeout();
2691
2815
  this.pool.on("connect", () => {
2692
2816
  this.logger.debug(`pool connected ${this.id}`);
2693
2817
  this.startTimeout();
2694
2818
  });
2695
2819
  this.pool.on("error", (err) => {
2696
- clearTimeout(this.timer);
2697
- this.logger.info(`pool ${this.id} failed`, {
2820
+ this.logger.info(`pool ${this.id} idle client error`, {
2698
2821
  message: err.message,
2699
2822
  stack: err.stack
2700
2823
  });
2701
- evictPool(this.id);
2702
- });
2703
- this.pool.on("release", (destroy) => {
2704
- if (destroy) {
2705
- clearTimeout(this.timer);
2706
- evictPool(this.id);
2707
- this.logger.debug(`destroying pool ${this.id}`);
2708
- }
2709
2824
  });
2710
2825
  }
2826
+ get shuttingDown() {
2827
+ return this.isShuttingDown;
2828
+ }
2829
+ getIdleTimeoutMs() {
2830
+ const raw = this.config.idleTimeoutMillis;
2831
+ if (raw === void 0 || raw === null) {
2832
+ return DEFAULT_IDLE_TIMEOUT_MS;
2833
+ }
2834
+ const parsed = Number(raw);
2835
+ if (!Number.isFinite(parsed) || parsed <= 0) {
2836
+ return null;
2837
+ }
2838
+ return parsed;
2839
+ }
2711
2840
  startTimeout() {
2841
+ if (this.isShuttingDown) {
2842
+ return;
2843
+ }
2712
2844
  const { debug } = this.logger;
2713
2845
  if (this.timer) {
2714
2846
  clearTimeout(this.timer);
2847
+ this.timer = void 0;
2848
+ }
2849
+ const timeoutMs = this.getIdleTimeoutMs();
2850
+ if (timeoutMs === null) {
2851
+ return;
2715
2852
  }
2716
2853
  this.timer = setTimeout(() => {
2717
2854
  debug(
2718
- `Pool reached idleTimeoutMillis. ${this.id} evicted after ${Number(this.config.idleTimeoutMillis) ?? 3e4}ms`
2855
+ `Pool reached idleTimeoutMillis. ${this.id} evicted after ${timeoutMs}ms`
2719
2856
  );
2720
- this.pool.end(() => {
2721
- clearTimeout(this.timer);
2857
+ this.timer = void 0;
2858
+ if (this.onEvict) {
2859
+ this.onEvict(this.id);
2860
+ } else {
2722
2861
  evictPool(this.id);
2723
- });
2724
- }, Number(this.config.idleTimeoutMillis) ?? 3e4);
2862
+ }
2863
+ void this.shutdown();
2864
+ }, timeoutMs);
2865
+ this.timer.unref?.();
2725
2866
  }
2726
2867
  shutdown() {
2868
+ if (this.shutdownPromise) {
2869
+ return this.shutdownPromise;
2870
+ }
2871
+ this.isShuttingDown = true;
2727
2872
  const { debug } = this.logger;
2728
2873
  debug(`attempting to shut down ${this.id}`);
2729
- clearTimeout(this.timer);
2730
- this.pool.end(() => {
2874
+ if (this.timer) {
2875
+ clearTimeout(this.timer);
2876
+ this.timer = void 0;
2877
+ }
2878
+ this.shutdownPromise = Promise.resolve().then(() => this.pool.end()).then(() => {
2731
2879
  debug(`${this.id} has been shut down`);
2880
+ }).catch((err) => {
2881
+ debug(
2882
+ `error shutting down ${this.id}: ${err instanceof Error ? err.message : String(err)}`
2883
+ );
2732
2884
  });
2885
+ return this.shutdownPromise;
2733
2886
  }
2734
2887
  };
2735
2888
  var NileInstance_default = NileDatabase;
2736
2889
 
2737
2890
  // src/db/DBManager.ts
2891
+ var DEFAULT_MAX_POOLS = 100;
2738
2892
  var DBManager = class {
2739
2893
  connections;
2740
2894
  cleared;
2741
- poolWatcherFn;
2895
+ maxPools;
2742
2896
  makeId(tenantId, userId) {
2743
2897
  if (tenantId && userId) {
2744
2898
  return `${tenantId}:${userId}`;
@@ -2751,16 +2905,16 @@ var DBManager = class {
2751
2905
  constructor(config) {
2752
2906
  this.cleared = false;
2753
2907
  this.connections = /* @__PURE__ */ new Map();
2754
- this.poolWatcherFn = this.poolWatcher(config);
2755
- watchEvictPool(this.poolWatcherFn);
2908
+ const configuredMax = Number(config.db?.maxPools);
2909
+ this.maxPools = Number.isFinite(configuredMax) && configuredMax >= 1 ? Math.floor(configuredMax) : DEFAULT_MAX_POOLS;
2756
2910
  }
2757
- poolWatcher = (config) => (id) => {
2911
+ evict = (config, id) => {
2758
2912
  const { info, warn } = Logger(config)("[DBManager]");
2759
2913
  if (id && this.connections.has(id)) {
2760
2914
  info(`Removing ${id} from db connection pool.`);
2761
2915
  const connection = this.connections.get(id);
2762
- connection?.shutdown();
2763
2916
  this.connections.delete(id);
2917
+ void connection?.shutdown();
2764
2918
  } else {
2765
2919
  warn(`missed eviction of ${id}`);
2766
2920
  }
@@ -2780,18 +2934,47 @@ var DBManager = class {
2780
2934
  }
2781
2935
  const tenantId = assertValidUUID(rawContext.tenantId, "tenantId");
2782
2936
  const userId = assertValidUUID(rawContext.userId, "userId");
2937
+ if (userId && !tenantId) {
2938
+ throw new Error(
2939
+ "Cannot scope database connection with userId without a tenantId in context"
2940
+ );
2941
+ }
2783
2942
  const id = this.makeId(tenantId, userId);
2784
2943
  const existing = this.connections.get(id);
2785
2944
  info(`# of instances: ${this.connections.size}`);
2786
- if (existing) {
2945
+ if (existing && !existing.shuttingDown) {
2787
2946
  info(`returning existing ${id}`);
2947
+ this.connections.delete(id);
2948
+ this.connections.set(id, existing);
2788
2949
  existing.startTimeout();
2789
2950
  return existing.pool;
2790
2951
  }
2791
- const newOne = new NileInstance_default(config.db, config.logger, id, {
2792
- tenantId,
2793
- userId
2794
- });
2952
+ if (existing?.shuttingDown) {
2953
+ this.connections.delete(id);
2954
+ }
2955
+ while (this.connections.size >= this.maxPools) {
2956
+ const oldestId = this.connections.keys().next().value;
2957
+ if (!oldestId) {
2958
+ break;
2959
+ }
2960
+ const oldest = this.connections.get(oldestId);
2961
+ this.connections.delete(oldestId);
2962
+ void oldest?.shutdown();
2963
+ }
2964
+ const newOne = new NileInstance_default(
2965
+ config.db,
2966
+ config.logger,
2967
+ id,
2968
+ {
2969
+ tenantId,
2970
+ userId
2971
+ },
2972
+ (evictedId) => {
2973
+ if (this.connections.get(evictedId) === newOne) {
2974
+ this.connections.delete(evictedId);
2975
+ }
2976
+ }
2977
+ );
2795
2978
  this.connections.set(id, newOne);
2796
2979
  info(`created new ${id}`);
2797
2980
  info(`# of instances: ${this.connections.size}`);
@@ -2800,14 +2983,13 @@ var DBManager = class {
2800
2983
  }
2801
2984
  return newOne.pool;
2802
2985
  };
2803
- clear = (config) => {
2986
+ clear = async (config) => {
2804
2987
  const { info } = Logger(config)("[DBManager]");
2805
2988
  info(`Clearing all connections ${this.connections.size}`);
2806
2989
  this.cleared = true;
2807
- this.connections.forEach((connection) => {
2808
- connection.shutdown();
2809
- });
2990
+ const active = Array.from(this.connections.values());
2810
2991
  this.connections.clear();
2992
+ await Promise.allSettled(active.map((connection) => connection.shutdown()));
2811
2993
  };
2812
2994
  };
2813
2995
 
@@ -3019,7 +3201,15 @@ var Auth = class {
3019
3201
  password = body2.password;
3020
3202
  const cbFromHeaders = parseCallback(req.headers);
3021
3203
  if (cbFromHeaders) {
3022
- callbackUrl = cbFromHeaders;
3204
+ const eqIdx = cbFromHeaders.indexOf("=");
3205
+ const rawVal = eqIdx >= 0 ? cbFromHeaders.slice(eqIdx + 1) : "";
3206
+ if (rawVal) {
3207
+ try {
3208
+ callbackUrl = decodeURIComponent(rawVal);
3209
+ } catch {
3210
+ callbackUrl = rawVal;
3211
+ }
3212
+ }
3023
3213
  }
3024
3214
  if (body2.callbackUrl) {
3025
3215
  callbackUrl = body2.callbackUrl;
@@ -3051,9 +3241,8 @@ var Auth = class {
3051
3241
  let urlWithParams;
3052
3242
  try {
3053
3243
  const data = await fetchResetPassword(this.#config, "POST", body);
3054
- const cloned = data.clone();
3055
- if (data.status === 400) {
3056
- const text = await cloned.text();
3244
+ if (!data.ok) {
3245
+ const text = await data.clone().text();
3057
3246
  this.#logger.error(text);
3058
3247
  return data;
3059
3248
  }
@@ -3077,25 +3266,32 @@ var Auth = class {
3077
3266
  );
3078
3267
  }
3079
3268
  const { headers } = ctx.get();
3080
- const cookie = headers?.get("cookie")?.split("; ");
3269
+ const existingCookie = headers?.get("cookie");
3270
+ const cookie = existingCookie ? existingCookie.split(/;\s*/).filter(Boolean) : [];
3081
3271
  if (token) {
3082
- cookie?.push(token);
3272
+ cookie.push(token);
3083
3273
  } else {
3084
3274
  throw new Error(
3085
3275
  "Unable to reset password, reset token is missing from response"
3086
3276
  );
3087
3277
  }
3088
- if (cookie) {
3089
- headers?.set("cookie", cookie?.join("; "));
3090
- ctx.set({
3091
- headers
3092
- });
3093
- }
3278
+ headers?.set("cookie", cookie.join("; "));
3279
+ ctx.set({
3280
+ headers
3281
+ });
3094
3282
  const res = await fetchResetPassword(this.#config, "PUT", body);
3095
- cookie?.pop();
3096
- const cleaned = cookie?.filter((c) => !c.includes("nile.session")) ?? [];
3097
- cleaned.push(String(parseToken(res.headers)));
3098
- const updatedHeaders = new Headers({ cookie: cleaned.join("; ") });
3283
+ cookie.pop();
3284
+ const cleaned = cookie.filter(
3285
+ (c) => !c.includes("nile.session")
3286
+ );
3287
+ const nextSessionToken = parseToken(res.headers);
3288
+ if (nextSessionToken) {
3289
+ cleaned.push(nextSessionToken);
3290
+ }
3291
+ const updatedHeaders = new Headers();
3292
+ if (cleaned.length > 0) {
3293
+ updatedHeaders.set("cookie", cleaned.join("; "));
3294
+ }
3099
3295
  ctx.set({ headers: null });
3100
3296
  ctx.set({ headers: updatedHeaders });
3101
3297
  return res;
@@ -3108,19 +3304,21 @@ var Auth = class {
3108
3304
  * `/api/auth/callback/{provider}` via {@link fetchCallback}.
3109
3305
  */
3110
3306
  async callback(provider, body) {
3111
- if (body instanceof Request) {
3112
- ctx.set({
3113
- headers: body.headers
3114
- });
3115
- return await fetchCallback(
3116
- this.#config,
3117
- provider,
3118
- void 0,
3119
- body,
3120
- "GET"
3121
- );
3122
- }
3123
- return await fetchCallback(this.#config, provider, body);
3307
+ return withNileContext(this.#config, async () => {
3308
+ if (body instanceof Request) {
3309
+ ctx.set({
3310
+ headers: body.headers
3311
+ });
3312
+ return await fetchCallback(
3313
+ this.#config,
3314
+ provider,
3315
+ void 0,
3316
+ body,
3317
+ "GET"
3318
+ );
3319
+ }
3320
+ return await fetchCallback(this.#config, provider, body);
3321
+ });
3124
3322
  }
3125
3323
  async signIn(provider, payload, rawResponse) {
3126
3324
  return withNileContext(this.#config, async () => {
@@ -3165,7 +3363,7 @@ var Auth = class {
3165
3363
  );
3166
3364
  }
3167
3365
  const { email, password } = payload ?? {};
3168
- if (provider === "email" && (!email || !password)) {
3366
+ if (provider === "credentials" && (!email || !password)) {
3169
3367
  throw new Error(
3170
3368
  "Server side sign in requires a user email and password."
3171
3369
  );
@@ -3268,62 +3466,72 @@ var Auth = class {
3268
3466
  });
3269
3467
  }
3270
3468
  };
3271
- function parseCSRF(headers) {
3272
- let cookie = headers?.get("set-cookie");
3273
- if (!cookie) {
3274
- cookie = headers?.get("cookie");
3275
- }
3276
- if (!cookie) {
3469
+ function extractNamedCookie(headers, baseName) {
3470
+ if (!headers) {
3277
3471
  return void 0;
3278
3472
  }
3279
- const [, token] = /((__Secure-)?nile\.csrf-token=[^;]+)/.exec(cookie) ?? [];
3280
- return token;
3281
- }
3282
- function parseCallback(headers) {
3283
- let cookie = headers?.get("set-cookie");
3284
- if (!cookie) {
3285
- cookie = headers?.get("cookie");
3473
+ const allowedNames = /* @__PURE__ */ new Set([baseName, `__Secure-${baseName}`]);
3474
+ let setCookies = [];
3475
+ if (typeof headers.getSetCookie === "function") {
3476
+ setCookies = headers.getSetCookie();
3477
+ } else {
3478
+ const rawSetCookie = headers.get("set-cookie");
3479
+ if (rawSetCookie) {
3480
+ setCookies = rawSetCookie.split(/,\s*(?=[^;,\s]+=)/);
3481
+ }
3482
+ }
3483
+ for (const candidate of setCookies) {
3484
+ for (const segment of candidate.split(/;\s*/)) {
3485
+ const trimmed = segment.trim();
3486
+ if (!trimmed) continue;
3487
+ const eqIdx = trimmed.indexOf("=");
3488
+ if (eqIdx <= 0) continue;
3489
+ const name = trimmed.slice(0, eqIdx).trim();
3490
+ if (allowedNames.has(name)) {
3491
+ return trimmed;
3492
+ }
3493
+ }
3286
3494
  }
3287
- if (!cookie) {
3495
+ const cookieHeader = headers.get("cookie");
3496
+ if (!cookieHeader) {
3288
3497
  return void 0;
3289
3498
  }
3290
- const [, token] = /((__Secure-)?nile\.callback-url=[^;]+)/.exec(cookie) ?? [];
3291
- return token;
3499
+ for (const part of cookieHeader.split(/;\s*/)) {
3500
+ const trimmed = part.trim();
3501
+ if (!trimmed) continue;
3502
+ const eqIdx = trimmed.indexOf("=");
3503
+ if (eqIdx <= 0) continue;
3504
+ const name = trimmed.slice(0, eqIdx).trim();
3505
+ if (allowedNames.has(name)) {
3506
+ return trimmed;
3507
+ }
3508
+ }
3509
+ return void 0;
3510
+ }
3511
+ function parseCSRF(headers) {
3512
+ return extractNamedCookie(headers, "nile.csrf-token");
3513
+ }
3514
+ function parseCallback(headers) {
3515
+ return extractNamedCookie(headers, "nile.callback-url");
3292
3516
  }
3293
3517
  function parseToken(headers) {
3294
- let authCookie = headers?.get("set-cookie");
3295
- if (!authCookie) {
3296
- authCookie = headers?.get("cookie");
3297
- }
3298
- if (!authCookie) {
3299
- return void 0;
3300
- }
3301
- const [, token] = /((__Secure-)?nile\.session-token=[^;]+)/.exec(authCookie) ?? [];
3302
- return token;
3518
+ return extractNamedCookie(headers, "nile.session-token");
3303
3519
  }
3304
3520
  function parseResetToken(headers) {
3305
- let authCookie = headers?.get("set-cookie");
3306
- if (!authCookie) {
3307
- authCookie = headers?.get("cookie");
3308
- }
3309
- if (!authCookie) {
3310
- return void 0;
3311
- }
3312
- const [, token] = /((__Secure-)?nile\.reset=[^;]+)/.exec(authCookie) ?? [];
3313
- return token;
3521
+ return extractNamedCookie(headers, "nile.reset");
3314
3522
  }
3315
3523
  function parseTenantId(headers) {
3316
- let authCookie = headers?.get("set-cookie");
3317
- if (!authCookie) {
3318
- authCookie = headers?.get("cookie");
3524
+ if (!headers) {
3525
+ return void 0;
3319
3526
  }
3320
- if (!authCookie) {
3527
+ const hasCookieHeader = typeof headers.getSetCookie === "function" && headers.getSetCookie().length > 0 || Boolean(headers.get("set-cookie")) || Boolean(headers.get("cookie"));
3528
+ if (!hasCookieHeader) {
3321
3529
  return void 0;
3322
3530
  }
3323
- const [, token] = /((__Secure-)?nile\.tenant-id=[^;]+)/.exec(authCookie) ?? [];
3531
+ const token = extractNamedCookie(headers, "nile.tenant-id");
3324
3532
  if (token) {
3325
- const [, tenantId] = token.split("=");
3326
- return tenantId;
3533
+ const eqIdx = token.indexOf("=");
3534
+ return eqIdx >= 0 ? token.slice(eqIdx + 1) : "";
3327
3535
  }
3328
3536
  return null;
3329
3537
  }
@@ -3333,10 +3541,16 @@ function defaultCallbackUrl(config) {
3333
3541
  const { headers } = ctx.get();
3334
3542
  const fallbackCb = parseCallback(headers);
3335
3543
  if (fallbackCb) {
3336
- const [, value] = fallbackCb.split("=");
3337
- cb = decodeURIComponent(value);
3544
+ const eqIdx = fallbackCb.indexOf("=");
3545
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3338
3546
  if (value) {
3339
- redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
3547
+ try {
3548
+ cb = decodeURIComponent(value);
3549
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
3550
+ } catch {
3551
+ cb = null;
3552
+ redirect = null;
3553
+ }
3340
3554
  }
3341
3555
  }
3342
3556
  return { callbackUrl: cb, redirectUrl: redirect };
@@ -3344,9 +3558,13 @@ function defaultCallbackUrl(config) {
3344
3558
  function fQUrl(path, config) {
3345
3559
  if (path.startsWith("/")) {
3346
3560
  const { callbackUrl } = defaultCallbackUrl(config);
3347
- if (callbackUrl) {
3348
- const { origin } = new URL(callbackUrl);
3349
- return `${origin}${path}`;
3561
+ const base = callbackUrl || config.origin || config.serverOrigin;
3562
+ if (base) {
3563
+ try {
3564
+ const { origin } = new URL(base);
3565
+ return `${origin}${path}`;
3566
+ } catch {
3567
+ }
3350
3568
  }
3351
3569
  }
3352
3570
  try {
@@ -3369,40 +3587,58 @@ async function is2FA(signInRes) {
3369
3587
  }
3370
3588
 
3371
3589
  // src/auth/obtainCsrf.ts
3590
+ function extractCookiePairs(headers) {
3591
+ const map = /* @__PURE__ */ new Map();
3592
+ const cookieHeader = headers.get("cookie");
3593
+ if (cookieHeader) {
3594
+ for (const part of cookieHeader.split(/;\s*/)) {
3595
+ if (!part) continue;
3596
+ const eqIdx = part.indexOf("=");
3597
+ if (eqIdx <= 0) continue;
3598
+ const key18 = part.slice(0, eqIdx).trim();
3599
+ const val = part.slice(eqIdx + 1).trim();
3600
+ if (key18) {
3601
+ map.set(key18, val);
3602
+ }
3603
+ }
3604
+ }
3605
+ return map;
3606
+ }
3607
+ function extractSetCookies(headers) {
3608
+ if (typeof headers.getSetCookie === "function") {
3609
+ const list = headers.getSetCookie();
3610
+ if (list.length > 0) {
3611
+ return list;
3612
+ }
3613
+ }
3614
+ const single = headers.get("set-cookie");
3615
+ return single ? [single] : [];
3616
+ }
3372
3617
  async function obtainCsrf(config, rawResponse = false) {
3373
3618
  const { headers } = ctx.get();
3374
3619
  const res = await fetchCsrf(config);
3375
3620
  const csrfCook = parseCSRF(res.headers);
3376
- if (csrfCook) {
3377
- const [, value] = csrfCook.split("=");
3621
+ const mergedCookies = extractCookiePairs(headers);
3622
+ for (const setCookie of extractSetCookies(res.headers)) {
3623
+ const pair = setCookie.split(";")[0];
3624
+ const eqIdx = pair.indexOf("=");
3625
+ if (eqIdx <= 0) continue;
3626
+ const key18 = pair.slice(0, eqIdx).trim();
3627
+ const val = pair.slice(eqIdx + 1).trim();
3628
+ if (key18) {
3629
+ mergedCookies.set(key18, val);
3630
+ }
3631
+ }
3632
+ if (mergedCookies.size > 0) {
3633
+ const serialized = Array.from(mergedCookies.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
3634
+ const cookieUpdate = new Headers({ cookie: serialized });
3635
+ ctx.set({ headers: cookieUpdate });
3636
+ }
3637
+ if (csrfCook && !rawResponse) {
3638
+ const eqIdx = csrfCook.indexOf("=");
3639
+ const value = eqIdx >= 0 ? csrfCook.slice(eqIdx + 1) : "";
3378
3640
  const [token] = decodeURIComponent(value).split("|");
3379
- const setCookie = res.headers.get("set-cookie");
3380
- if (setCookie) {
3381
- const cookie = [
3382
- csrfCook,
3383
- parseCallback(res.headers) ?? parseCallback(headers),
3384
- parseToken(res.headers) ?? parseToken(headers)
3385
- ].filter(Boolean).join("; ");
3386
- headers.set("cookie", cookie);
3387
- ctx.set({ headers });
3388
- }
3389
- if (!rawResponse) {
3390
- return { csrfToken: token };
3391
- }
3392
- } else {
3393
- const existingCookie = headers.get("cookie");
3394
- const cookieParts = [];
3395
- if (existingCookie) {
3396
- cookieParts.push(parseToken(headers), parseCallback(headers));
3397
- }
3398
- if (csrfCook) {
3399
- cookieParts.push(csrfCook);
3400
- } else {
3401
- cookieParts.push(parseCSRF(headers));
3402
- }
3403
- const cookie = cookieParts.filter(Boolean).join("; ");
3404
- headers.set("cookie", cookie);
3405
- ctx.set({ headers });
3641
+ return { csrfToken: token };
3406
3642
  }
3407
3643
  if (rawResponse) {
3408
3644
  return res;
@@ -3415,11 +3651,15 @@ async function obtainCsrf(config, rawResponse = false) {
3415
3651
  }
3416
3652
 
3417
3653
  // src/utils/qualifyDomain.ts
3418
- function fQUrl2(callbackUrl, path) {
3654
+ function fQUrl2(callbackUrl, path, fallbackOrigin) {
3419
3655
  if (path.startsWith("/")) {
3420
- if (callbackUrl) {
3421
- const { origin } = new URL(callbackUrl);
3422
- return `${origin}${path}`;
3656
+ const base = callbackUrl || fallbackOrigin;
3657
+ if (base) {
3658
+ try {
3659
+ const { origin } = new URL(base);
3660
+ return `${origin}${path}`;
3661
+ } catch {
3662
+ }
3423
3663
  }
3424
3664
  }
3425
3665
  try {
@@ -3502,18 +3742,22 @@ var Users = class {
3502
3742
  }
3503
3743
  async verifySelf(options, rawResponse = false) {
3504
3744
  return withNileContext(this.#config, async () => {
3505
- const bypassEmail = typeof options === "object" && options?.bypassEmail === true;
3506
- const callbackUrl = fQUrl2(
3507
- defaultCallbackUrl2().callbackUrl,
3508
- typeof options === "object" ? String(options.callbackUrl) : "/"
3509
- );
3745
+ const isRaw = rawResponse || options === true;
3746
+ const bypassEmail = options !== null && typeof options === "object" && options.bypassEmail === true;
3747
+ const requestedPath = options !== null && typeof options === "object" && typeof options.callbackUrl === "string" ? options.callbackUrl : "/";
3748
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
3510
3749
  let res;
3511
3750
  try {
3512
3751
  const me = await this.getSelf();
3513
3752
  if (me instanceof Response) {
3514
3753
  return me;
3515
3754
  }
3516
- res = await verifyEmailAddress(this.#config, me, String(callbackUrl));
3755
+ const callbackUrl = fQUrl2(
3756
+ defaultCallbackUrl2().callbackUrl,
3757
+ requestedPath,
3758
+ fallbackOrigin
3759
+ );
3760
+ res = await verifyEmailAddress(this.#config, me, callbackUrl);
3517
3761
  return res;
3518
3762
  } catch (e) {
3519
3763
  if (!bypassEmail) {
@@ -3531,7 +3775,7 @@ var Users = class {
3531
3775
  this.#logger?.info(
3532
3776
  "bypassing email requirements for email verification"
3533
3777
  );
3534
- res = this.updateSelf({ emailVerified: true }, rawResponse);
3778
+ res = await this.updateSelf({ emailVerified: true }, isRaw);
3535
3779
  }
3536
3780
  return res;
3537
3781
  });
@@ -3563,8 +3807,15 @@ function defaultCallbackUrl2() {
3563
3807
  const { headers } = ctx.get();
3564
3808
  const fallbackCb = parseCallback(headers);
3565
3809
  if (fallbackCb) {
3566
- const [, value] = fallbackCb.split("=");
3567
- cb = decodeURIComponent(value);
3810
+ const eqIdx = fallbackCb.indexOf("=");
3811
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3812
+ if (value) {
3813
+ try {
3814
+ cb = decodeURIComponent(value);
3815
+ } catch {
3816
+ cb = value;
3817
+ }
3818
+ }
3568
3819
  }
3569
3820
  return { callbackUrl: cb };
3570
3821
  }
@@ -3589,7 +3840,7 @@ var Tenants = class {
3589
3840
  "POST",
3590
3841
  JSON.stringify({ name: req })
3591
3842
  );
3592
- } else if (typeof req === "object" && ("name" in req || "id" in req)) {
3843
+ } else if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
3593
3844
  res = await fetchTenants(this.#config, "POST", JSON.stringify(req));
3594
3845
  }
3595
3846
  if (rawResponse) {
@@ -3612,7 +3863,7 @@ var Tenants = class {
3612
3863
  if (typeof req === "string") {
3613
3864
  ctx.set({ tenantId: req });
3614
3865
  }
3615
- if (typeof req === "object" && "id" in req) {
3866
+ if (req != null && typeof req === "object" && "id" in req) {
3616
3867
  ctx.set({ tenantId: req.id });
3617
3868
  }
3618
3869
  const res = await fetchTenant(this.#config, "DELETE");
@@ -3629,7 +3880,7 @@ var Tenants = class {
3629
3880
  return withNileContext(this.#config, async () => {
3630
3881
  if (typeof req === "string") {
3631
3882
  ctx.set({ tenantId: req });
3632
- } else if (typeof req === "object" && "id" in req) {
3883
+ } else if (req != null && typeof req === "object" && "id" in req) {
3633
3884
  ctx.set({ tenantId: req.id });
3634
3885
  }
3635
3886
  const res = await fetchTenant(this.#config, "GET");
@@ -3646,7 +3897,7 @@ var Tenants = class {
3646
3897
  async update(req, rawResponse) {
3647
3898
  return withNileContext(this.#config, async () => {
3648
3899
  let res;
3649
- if (typeof req === "object" && ("name" in req || "id" in req)) {
3900
+ if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
3650
3901
  const { id, ...remaining } = req;
3651
3902
  if (id) {
3652
3903
  ctx.set({ tenantId: id });
@@ -3692,9 +3943,12 @@ var Tenants = class {
3692
3943
  async leaveTenant(req) {
3693
3944
  return withNileContext(this.#config, async () => {
3694
3945
  const me = await fetchMe(this.#config);
3946
+ if (me && "ok" in me && !me.ok) {
3947
+ return me;
3948
+ }
3695
3949
  try {
3696
3950
  const json = await me.json();
3697
- if ("id" in json) {
3951
+ if (json && typeof json === "object" && "id" in json) {
3698
3952
  ctx.set({ userId: json.id });
3699
3953
  }
3700
3954
  } catch {
@@ -3765,37 +4019,54 @@ var Tenants = class {
3765
4019
  return withNileContext(
3766
4020
  this.#config,
3767
4021
  async () => {
3768
- const { csrfToken } = await obtainCsrf(
4022
+ const csrfRes = await obtainCsrf(
3769
4023
  this.#config
3770
4024
  );
4025
+ const csrfToken = csrfRes && typeof csrfRes === "object" && "csrfToken" in csrfRes ? csrfRes.csrfToken : void 0;
4026
+ if (!csrfToken) {
4027
+ throw new Error("Unable to obtain CSRF token. Invite failed.");
4028
+ }
3771
4029
  const defaults = defaultCallbackUrl3(this.#config);
3772
- let identifier = req;
4030
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
4031
+ let identifier = typeof req === "string" ? req : "";
3773
4032
  let callbackUrl = defaults.callbackUrl;
3774
4033
  let redirectUrl = defaults.redirectUrl;
3775
- if (typeof req === "object") {
4034
+ if (req != null && typeof req === "object") {
3776
4035
  if ("email" in req) {
3777
4036
  identifier = req.email;
3778
4037
  }
3779
- const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
3780
4038
  if ("callbackUrl" in req) {
3781
- callbackUrl = fQUrl2(cbUrl, req.callbackUrl ?? "/");
4039
+ callbackUrl = fQUrl2(
4040
+ defaults.callbackUrl,
4041
+ req.callbackUrl ?? "/",
4042
+ fallbackOrigin
4043
+ );
3782
4044
  }
3783
4045
  if ("redirectUrl" in req) {
3784
- redirectUrl = fQUrl2(cbUrl, req.redirectUrl ?? "/");
4046
+ redirectUrl = fQUrl2(
4047
+ defaults.callbackUrl,
4048
+ req.redirectUrl ?? "/",
4049
+ fallbackOrigin
4050
+ );
3785
4051
  }
3786
4052
  }
3787
4053
  const { headers } = ctx.get();
3788
4054
  headers?.set("Content-Type", "application/x-www-form-urlencoded");
3789
4055
  ctx.set({ headers });
4056
+ const formParams = new URLSearchParams({
4057
+ identifier,
4058
+ csrfToken
4059
+ });
4060
+ if (callbackUrl) {
4061
+ formParams.set("callbackUrl", callbackUrl);
4062
+ }
4063
+ if (redirectUrl) {
4064
+ formParams.set("redirectUrl", redirectUrl);
4065
+ }
3790
4066
  const res = await fetchInvite(
3791
4067
  this.#config,
3792
4068
  "POST",
3793
- new URLSearchParams({
3794
- identifier,
3795
- csrfToken,
3796
- callbackUrl,
3797
- redirectUrl
3798
- }).toString()
4069
+ formParams.toString()
3799
4070
  );
3800
4071
  return responseHandler(res, rawResponse);
3801
4072
  },
@@ -3815,7 +4086,8 @@ var Tenants = class {
3815
4086
  }
3816
4087
  const { identifier, token } = req;
3817
4088
  const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
3818
- const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/");
4089
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
4090
+ const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/", fallbackOrigin);
3819
4091
  const res = await fetchInvite(
3820
4092
  this.#config,
3821
4093
  "PUT",
@@ -3836,9 +4108,9 @@ var Tenants = class {
3836
4108
  async deleteInvite(req) {
3837
4109
  return withNileContext(this.#config, async () => {
3838
4110
  let id = "";
3839
- if (typeof req === "object") {
4111
+ if (req != null && typeof req === "object") {
3840
4112
  id = req.id;
3841
- } else {
4113
+ } else if (typeof req === "string") {
3842
4114
  id = req;
3843
4115
  }
3844
4116
  if (!id) {
@@ -3849,12 +4121,14 @@ var Tenants = class {
3849
4121
  });
3850
4122
  }
3851
4123
  #handleContext(req) {
3852
- if (typeof req === "object") {
4124
+ if (req != null && typeof req === "object") {
3853
4125
  if ("tenantId" in req) {
3854
4126
  ctx.set({ tenantId: req.tenantId });
3855
4127
  }
3856
4128
  if ("userId" in req) {
3857
4129
  ctx.set({ userId: req.userId });
4130
+ } else if ("id" in req) {
4131
+ ctx.set({ userId: req.id });
3858
4132
  }
3859
4133
  }
3860
4134
  }
@@ -3875,72 +4149,177 @@ function defaultCallbackUrl3(config) {
3875
4149
  const { headers, tenantId } = ctx.get();
3876
4150
  const fallbackCb = parseCallback(headers);
3877
4151
  if (fallbackCb) {
3878
- const [, value] = fallbackCb.split("=");
3879
- cb = decodeURIComponent(value);
4152
+ const eqIdx = fallbackCb.indexOf("=");
4153
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3880
4154
  if (value) {
3881
- redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace("{tenantId}", String(tenantId))}`;
4155
+ try {
4156
+ cb = decodeURIComponent(value);
4157
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace(
4158
+ "{tenantId}",
4159
+ String(tenantId)
4160
+ )}`;
4161
+ } catch {
4162
+ cb = null;
4163
+ redirect = null;
4164
+ }
3882
4165
  }
3883
4166
  }
3884
4167
  return { callbackUrl: cb, redirectUrl: redirect };
3885
4168
  }
3886
4169
 
3887
4170
  // src/api/handlers/withContext/index.ts
3888
- function handlersWithContext(config) {
4171
+ function handlersWithContext(config, spawnScoped) {
3889
4172
  const GET7 = GETTER(config.routes, config);
3890
4173
  const POST6 = POSTER(config.routes, config);
3891
4174
  const DELETE5 = DELETER(config.routes, config);
3892
4175
  const PUT6 = PUTER(config.routes, config);
4176
+ const createRequestServer = (response, req) => {
4177
+ if (spawnScoped) {
4178
+ const { context, origin } = buildScopedContext(response, config, req);
4179
+ return spawnScoped(context, { origin });
4180
+ }
4181
+ const updatedConfig = updateConfig(response, config, req);
4182
+ return new Server(updatedConfig);
4183
+ };
3893
4184
  return {
3894
4185
  GET: async (req) => {
3895
4186
  const response = await GET7(req);
3896
- const updatedConfig = updateConfig(response, config);
3897
- return { response, nile: new Server(updatedConfig) };
4187
+ return {
4188
+ response,
4189
+ nile: createRequestServer(response, req)
4190
+ };
3898
4191
  },
3899
4192
  POST: async (req) => {
3900
4193
  const response = await POST6(req);
3901
- const updatedConfig = updateConfig(response, config);
3902
- return { response, nile: new Server(updatedConfig) };
4194
+ return {
4195
+ response,
4196
+ nile: createRequestServer(response, req)
4197
+ };
3903
4198
  },
3904
4199
  DELETE: async (req) => {
3905
4200
  const response = await DELETE5(req);
3906
- const updatedConfig = updateConfig(response, config);
3907
- return { response, nile: new Server(updatedConfig) };
4201
+ return {
4202
+ response,
4203
+ nile: createRequestServer(response, req)
4204
+ };
3908
4205
  },
3909
4206
  PUT: async (req) => {
3910
4207
  const response = await PUT6(req);
3911
- const updatedConfig = updateConfig(response, config);
3912
- return { response, nile: new Server(updatedConfig) };
4208
+ return {
4209
+ response,
4210
+ nile: createRequestServer(response, req)
4211
+ };
3913
4212
  }
3914
4213
  };
3915
4214
  }
3916
- function updateConfig(response, config) {
3917
- let origin = "http://localhost:3000";
3918
- let headers = null;
3919
- if (response instanceof Response) {
3920
- if (response?.status === 302) {
3921
- const location = response.headers.get("location");
3922
- if (location) {
3923
- const urlLocation = new URL(location);
3924
- origin = urlLocation.origin;
4215
+ function parseCookieString(cookieHeader) {
4216
+ const map = /* @__PURE__ */ new Map();
4217
+ if (!cookieHeader) {
4218
+ return map;
4219
+ }
4220
+ for (const part of cookieHeader.split(/;\s*/)) {
4221
+ if (!part) continue;
4222
+ const eqIdx = part.indexOf("=");
4223
+ if (eqIdx <= 0) continue;
4224
+ const name = part.slice(0, eqIdx).trim();
4225
+ const value = part.slice(eqIdx + 1).trim();
4226
+ if (name) {
4227
+ map.set(name, value);
4228
+ }
4229
+ }
4230
+ return map;
4231
+ }
4232
+ function getResponseSetCookies(response) {
4233
+ if (typeof response.headers?.getSetCookie === "function") {
4234
+ const cookies = response.headers.getSetCookie();
4235
+ if (cookies.length > 0) {
4236
+ return cookies;
4237
+ }
4238
+ }
4239
+ const collected = [];
4240
+ if (response.headers) {
4241
+ for (const [key18, value] of response.headers) {
4242
+ if (key18.toLowerCase() === "set-cookie") {
4243
+ collected.push(value);
3925
4244
  }
3926
4245
  }
3927
- const setCookies = [];
3928
- if (response?.headers) {
3929
- for (const [key18, value] of response.headers) {
3930
- if (key18.toLowerCase() === "set-cookie") {
3931
- setCookies.push(value);
4246
+ }
4247
+ return collected;
4248
+ }
4249
+ function resolveOrigin(response, config, req) {
4250
+ let origin = config.origin ?? config.serverOrigin ?? void 0;
4251
+ if (!origin && req?.url) {
4252
+ try {
4253
+ origin = new URL(req.url).origin;
4254
+ } catch {
4255
+ }
4256
+ }
4257
+ if (response instanceof Response && response.status === 302) {
4258
+ const location = response.headers.get("location");
4259
+ if (location) {
4260
+ try {
4261
+ const base = origin || req?.url || "http://localhost:3000";
4262
+ const urlLocation = new URL(location, base);
4263
+ if (urlLocation.protocol === "http:" || urlLocation.protocol === "https:") {
4264
+ origin = urlLocation.origin;
3932
4265
  }
4266
+ } catch {
3933
4267
  }
3934
4268
  }
3935
- if (setCookies.length > 0) {
3936
- const cookieHeader = setCookies.map((cookieStr) => cookieStr.split(";")[0]).join("; ");
3937
- headers = new Headers({ cookie: cookieHeader });
4269
+ }
4270
+ return origin;
4271
+ }
4272
+ function buildMergedHeaders(response, req, origin) {
4273
+ const cookieMap = parseCookieString(req?.headers?.get("cookie"));
4274
+ if (response instanceof Response) {
4275
+ const setCookies = getResponseSetCookies(response);
4276
+ for (const cookieStr of setCookies) {
4277
+ const [pair, ...attrs] = cookieStr.split(";");
4278
+ const eqIdx = pair.indexOf("=");
4279
+ if (eqIdx <= 0) continue;
4280
+ const name = pair.slice(0, eqIdx).trim();
4281
+ const value = pair.slice(eqIdx + 1).trim();
4282
+ const isClearing = value === "" || attrs.some((a) => /^max-age\s*=\s*0$/i.test(a.trim()));
4283
+ if (isClearing) {
4284
+ cookieMap.delete(name);
4285
+ } else if (name) {
4286
+ cookieMap.set(name, value);
4287
+ }
3938
4288
  }
3939
4289
  }
4290
+ const headers = new Headers();
4291
+ if (cookieMap.size > 0) {
4292
+ const serialized = Array.from(cookieMap.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
4293
+ headers.set("cookie", serialized);
4294
+ }
4295
+ if (origin) {
4296
+ headers.set(HEADER_ORIGIN, origin);
4297
+ }
4298
+ const tenantId = cookieMap.get(TENANT_COOKIE);
4299
+ return { headers, tenantId };
4300
+ }
4301
+ function buildScopedContext(response, config, req) {
4302
+ const origin = resolveOrigin(response, config, req);
4303
+ const { headers, tenantId } = buildMergedHeaders(response, req, origin);
4304
+ return {
4305
+ origin,
4306
+ context: {
4307
+ headers,
4308
+ tenantId: tenantId ?? config.context.tenantId,
4309
+ userId: config.context.userId
4310
+ }
4311
+ };
4312
+ }
4313
+ function updateConfig(response, config, req) {
4314
+ const { context, origin } = buildScopedContext(response, config, req);
4315
+ const hasCookies = Boolean(context.headers.get("cookie"));
3940
4316
  return {
3941
4317
  ...config,
4318
+ user: config.db?.user,
4319
+ password: typeof config.db?.password === "string" ? config.db.password : void 0,
4320
+ databaseName: config.db?.database,
3942
4321
  origin,
3943
- headers: headers ?? void 0,
4322
+ headers: hasCookies ? context.headers : void 0,
3944
4323
  useLastContext: true
3945
4324
  };
3946
4325
  }
@@ -3969,9 +4348,10 @@ var Server = class _Server {
3969
4348
  ...config,
3970
4349
  extensionCtx: buildExtensionConfig(this)
3971
4350
  });
4351
+ const spawnFromHandler = (scopedContext, options) => this.#spawnScoped(scopedContext, void 0, options);
3972
4352
  this.#handlers = {
3973
4353
  ...this.#config.handlers,
3974
- withContext: handlersWithContext(this.#config)
4354
+ withContext: handlersWithContext(this.#config, spawnFromHandler)
3975
4355
  };
3976
4356
  if (this.#config.context.tenantId === void 0) {
3977
4357
  this.#config.context.tenantId = getTenantId({
@@ -3983,33 +4363,33 @@ var Server = class _Server {
3983
4363
  this.users = new Users(this.#config);
3984
4364
  this.tenants = new Tenants(this.#config);
3985
4365
  this.auth = new Auth(this.#config);
3986
- if (config?.extensions) {
3987
- for (const create2 of config.extensions) {
3988
- if (typeof create2 !== "function") {
3989
- continue;
3990
- }
3991
- const ext = create2();
3992
- if (typeof ext.onConfigure === "function") {
3993
- this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
3994
- ext.onConfigure(this);
3995
- }
3996
- if (ext?.replace?.handlers) {
3997
- this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
3998
- this.#handlers = ext.replace.handlers({
3999
- ...this.#config.handlers,
4000
- withContext: handlersWithContext(this.#config)
4001
- });
4002
- }
4366
+ if (this.#config.extensions) {
4367
+ for (const create2 of this.#config.extensions) {
4368
+ this.#applyExtension(create2);
4003
4369
  }
4004
4370
  }
4005
4371
  }
4372
+ #applyExtension(create2) {
4373
+ if (typeof create2 !== "function") {
4374
+ return;
4375
+ }
4376
+ const ext = resolveExtension(create2, this);
4377
+ if (typeof ext.onConfigure === "function") {
4378
+ this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
4379
+ ext.onConfigure(this);
4380
+ }
4381
+ if (ext?.replace?.handlers) {
4382
+ this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
4383
+ this.#handlers = ext.replace.handlers(this.#handlers);
4384
+ }
4385
+ }
4006
4386
  /**
4007
4387
  * Query the database with the current context
4008
4388
  */
4009
4389
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
4010
- query = (queryStream, values) => {
4390
+ query = (...args) => {
4011
4391
  const pool = this.#manager.getConnection(this.#config);
4012
- return pool.query(queryStream, values);
4392
+ return pool.query(...args);
4013
4393
  };
4014
4394
  /**
4015
4395
  * Return a db object that can be used to talk to the database
@@ -4018,9 +4398,7 @@ var Server = class _Server {
4018
4398
  get db() {
4019
4399
  const pool = this.#manager.getConnection(this.#config, true);
4020
4400
  return Object.assign(pool, {
4021
- clearConnections: () => {
4022
- this.#manager.clear(this.#config);
4023
- }
4401
+ clearConnections: () => this.#manager.clear(this.#config)
4024
4402
  });
4025
4403
  }
4026
4404
  get logger() {
@@ -4030,7 +4408,9 @@ var Server = class _Server {
4030
4408
  return {
4031
4409
  remove: async (id) => {
4032
4410
  if (!this.#config.extensions) return;
4033
- const resolved = this.#config.extensions.map((ext) => ext());
4411
+ const resolved = this.#config.extensions.map(
4412
+ (ext) => resolveExtension(ext, this)
4413
+ );
4034
4414
  const index = resolved.findIndex((ext) => ext.id === id);
4035
4415
  if (index !== -1) {
4036
4416
  this.#config.extensions.splice(index, 1);
@@ -4042,6 +4422,7 @@ var Server = class _Server {
4042
4422
  this.#config.extensions = [];
4043
4423
  }
4044
4424
  this.#config.extensions.push(extension);
4425
+ this.#applyExtension(extension);
4045
4426
  }
4046
4427
  };
4047
4428
  }
@@ -4122,10 +4503,12 @@ var Server = class _Server {
4122
4503
  }
4123
4504
  return cloneContext(this.#config.context);
4124
4505
  }
4125
- #spawnScoped(scopedContext, boundStore) {
4506
+ #spawnScoped(scopedContext, boundStore, options) {
4507
+ const originPatch = options?.origin ? { origin: options.origin, serverOrigin: options.origin } : {};
4126
4508
  const clonedConfig = Object.assign(
4127
4509
  Object.create(Config.prototype),
4128
4510
  this.#config,
4511
+ originPatch,
4129
4512
  {
4130
4513
  context: cloneContext(scopedContext),
4131
4514
  isScoped: true,
@@ -4149,12 +4532,12 @@ var Server = class _Server {
4149
4532
  this.#config.context.headers = new Headers();
4150
4533
  if (config instanceof Headers) {
4151
4534
  headers = config;
4152
- } else if (config?.headers) {
4153
- headers = config?.headers;
4154
- if (config && config.origin) {
4535
+ } else if (config) {
4536
+ headers = config.headers;
4537
+ if (config.origin) {
4155
4538
  this.#config.context.headers.set(HEADER_ORIGIN, config.origin);
4156
4539
  }
4157
- if (config && config.secureCookies != null) {
4540
+ if (config.secureCookies != null) {
4158
4541
  this.#config.context.headers.set(
4159
4542
  HEADER_SECURE_COOKIES,
4160
4543
  String(config.secureCookies)