@niledatabase/server 5.0.0-alpha.9 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import pg, { PoolConfig, PoolClient } from 'pg';
1
+ import pg, { Pool, PoolConfig, PoolClient } from 'pg';
2
2
 
3
3
  type LogFunction = (message: string | unknown, meta?: Record<string, unknown>) => void;
4
4
  type Loggable = {
@@ -6,46 +6,33 @@ type Loggable = {
6
6
  debug: LogFunction;
7
7
  warn: LogFunction;
8
8
  error: LogFunction;
9
+ silly: LogFunction;
9
10
  };
10
11
  type LogReturn = (prefixes?: string | string[]) => Loggable;
11
12
 
13
+ type ConfigurablePaths = {
14
+ get: string[];
15
+ post: string[];
16
+ delete: string[];
17
+ put: string[];
18
+ };
19
+ type ExtensionReturns = void | Response | Request | ExtensionState;
12
20
  type ExtensionCtx = {
13
- handleOnRequest: (config: Config, _init: RequestInit & {
21
+ runExtensions: <T = ExtensionReturns>(toRun: ExtensionState, config: Config, params?: any, _init?: RequestInit & {
14
22
  request: Request;
15
- }, params: RequestInit) => Promise<void>;
23
+ }) => Promise<T>;
16
24
  };
17
25
  type ConfigConstructor = NileConfig & {
18
26
  extensionCtx?: ExtensionCtx;
19
27
  };
20
28
  declare class Config {
21
29
  routes: Routes;
22
- handlers: {
23
- GET: (req: Request) => Promise<void | Response>;
24
- POST: (req: Request) => Promise<void | Response>;
25
- DELETE: (req: Request) => Promise<void | Response>;
26
- PUT: (req: Request) => Promise<void | Response>;
27
- };
28
- paths: {
29
- get: string[];
30
- post: string[];
31
- delete: string[];
32
- put: string[];
33
- };
30
+ handlers: RouteFunctions;
31
+ paths: ConfigurablePaths;
34
32
  extensionCtx: ExtensionCtx;
35
33
  extensions?: Extension[];
36
34
  logger: LogReturn;
37
- /**
38
- * Stores the set tenant id from Server for use in sub classes
39
- */
40
- tenantId: string | null | undefined;
41
- /**
42
- * Stores the set user id from Server for use in sub classes
43
- */
44
- userId: string | null | undefined;
45
- /**
46
- * Stores the headers to be used in `fetch` calls
47
- */
48
- headers: Headers;
35
+ context: PartialContext;
49
36
  /**
50
37
  * The nile-auth url
51
38
  */
@@ -140,15 +127,62 @@ interface User {
140
127
  tenants: string[];
141
128
  }
142
129
 
130
+ /**
131
+ * Convenience wrapper around the user endpoints.
132
+ *
133
+ * Requests are issued via {@link fetchMe} against `/api/me`. The Swagger
134
+ * definitions for these APIs live in
135
+ * `packages/server/src/api/routes/me/index.ts`.
136
+ */
143
137
  declare class Users {
144
138
  #private;
139
+ /**
140
+ * Create a new Users helper.
141
+ * @param config - The configuration used for requests.
142
+ */
145
143
  constructor(config: Config);
144
+ /**
145
+ * Update the current user via `PUT /api/me`.
146
+ *
147
+ * The OpenAPI description for this endpoint can be found in
148
+ * `packages/server/src/api/routes/me/index.ts` under `updateSelf`.
149
+ *
150
+ * @param req - Partial user fields to send.
151
+ * @param [rawResponse] - When `true`, return the raw {@link Response}.
152
+ */
146
153
  updateSelf<T = User[] | Response>(req: Partial<Omit<User, 'email' | 'tenants' | 'created' | 'updated' | 'emailVerified'> & {
147
154
  emailVerified: boolean;
148
155
  }>, rawResponse?: boolean): Promise<T>;
156
+ /**
157
+ * Remove the current user using `DELETE /api/me`.
158
+ *
159
+ * After the request the authentication headers are cleared with
160
+ * {@link updateHeaders}. The OpenAPI docs for this route are in
161
+ * `packages/server/src/api/routes/me/index.ts` under `removeSelf`.
162
+ */
149
163
  removeSelf(): Promise<Response>;
150
- getSelf<T = User | Response>(): Promise<T>;
151
- getSelf(rawResponse?: true): Promise<Response>;
164
+ /**
165
+ * Retrieve the current user with `GET /api/me`.
166
+ *
167
+ * OpenAPI for this endpoint resides in
168
+ * `packages/server/src/api/routes/me/index.ts` (`getSelf`).
169
+ *
170
+ * @param [rawResponse] - When `true` return the raw {@link Response}.
171
+ */
172
+ getSelf<T = User | Response>(rawResponse?: false): Promise<T>;
173
+ getSelf(rawResponse: true): Promise<Response>;
174
+ /**
175
+ * Initiate an email verification flow.
176
+ *
177
+ * The current user is fetched and then `/auth/verify-email` is called.
178
+ * In development or when `bypassEmail` is set, the user's
179
+ * `emailVerified` field is updated instead of sending an email.
180
+ * See `packages/server/src/api/routes/auth/verify-email.ts` for the
181
+ * underlying request.
182
+ *
183
+ * @param [options] - Flags controlling bypass behaviour and callback URL.
184
+ * @param [rawResponse] - When `true` return the raw {@link Response}.
185
+ */
152
186
  verifySelf<T = void>(): Promise<T>;
153
187
  verifySelf(rawResponse: true): Promise<Response>;
154
188
  verifySelf<T = Response | User>(options: {
@@ -171,6 +205,12 @@ type Invite = {
171
205
  expires: Date;
172
206
  };
173
207
 
208
+ /**
209
+ * Convenience wrapper around the tenant endpoints. These methods call
210
+ * the `fetch*` helpers in `packages/server/src/api/routes/tenants` which
211
+ * in turn hit routes such as `/api/tenants` and `/api/tenants/{tenantId}`.
212
+ * See those files for the Swagger definitions.
213
+ */
174
214
  type ReqContext = {
175
215
  userId?: string;
176
216
  tenantId?: string;
@@ -187,7 +227,16 @@ declare class Tenants {
187
227
  name: string;
188
228
  id?: string;
189
229
  }, rawResponse?: boolean): Promise<T>;
230
+ /**
231
+ * Delete a tenant using `DELETE /api/tenants/{tenantId}`.
232
+ * The OpenAPI operation is defined in
233
+ * `packages/server/src/api/routes/tenants/[tenantId]/DELETE.ts`.
234
+ */
190
235
  delete<T = Response>(id?: string): Promise<T>;
236
+ /**
237
+ * Delete a tenant using `DELETE /api/tenants/{tenantId}`.
238
+ * See `packages/server/src/api/routes/tenants/[tenantId]/DELETE.ts`.
239
+ */
191
240
  delete<T = Response>(payload: {
192
241
  id: string;
193
242
  }): Promise<T>;
@@ -198,20 +247,58 @@ declare class Tenants {
198
247
  id: string;
199
248
  }, rawResponse?: boolean): Promise<T>;
200
249
  update(req: Partial<Tenant>, rawResponse: true): Promise<Response>;
250
+ /**
251
+ * Modify a tenant using `PUT /api/tenants/{tenantId}`.
252
+ *
253
+ * @param req - Tenant data to update. Can include an id.
254
+ * @param [rawResponse] - When true, return the raw {@link Response}.
255
+ */
201
256
  update<T = Tenant | Response | undefined>(req: Partial<Tenant>, rawResponse?: boolean): Promise<T>;
202
257
  list<T = Tenant[] | Response>(): Promise<T>;
203
258
  list(rawResponse: true): Promise<Response>;
259
+ /**
260
+ * Leave the current tenant using `DELETE /api/tenants/{tenantId}/users/{userId}`.
261
+ *
262
+ * @param [req] - Optionally specify the tenant id to leave.
263
+ */
204
264
  leaveTenant<T = Response>(req?: string | {
205
265
  tenantId: string;
206
266
  }): Promise<T>;
207
267
  addMember(req: JoinTenantRequest, rawResponse: true): Promise<Response>;
268
+ /**
269
+ * Add a user to a tenant via `PUT /api/tenants/{tenantId}/users/{userId}`.
270
+ *
271
+ * @param req - User and tenant identifiers or context.
272
+ * @param [rawResponse] - When true, return the raw {@link Response}.
273
+ */
208
274
  addMember<T = User | Response>(req: JoinTenantRequest, rawResponse?: boolean): Promise<T>;
275
+ /**
276
+ * Remove a user from a tenant with `DELETE /api/tenants/{tenantId}/users/{userId}`.
277
+ *
278
+ * @param req - User and tenant identifiers or context.
279
+ * @param [rawResponse] - When true, return the raw {@link Response}.
280
+ */
209
281
  removeMember(req: JoinTenantRequest, rawResponse?: boolean): Promise<Response>;
282
+ /**
283
+ * List users for a tenant via `GET /api/tenants/{tenantId}/users`.
284
+ *
285
+ * @param [req] - Tenant identifier or context.
286
+ * @param [rawResponse] - When true, return the raw {@link Response}.
287
+ */
210
288
  users<T = User[] | Response>(req?: boolean | {
211
289
  tenantId?: string;
212
290
  }, rawResponse?: boolean): Promise<T>;
213
291
  users(req: true): Promise<Response>;
292
+ /**
293
+ * List invites for the current tenant via `GET /api/tenants/{tenantId}/invites`.
294
+ */
214
295
  invites<T = Invite[] | Response>(): Promise<T>;
296
+ /**
297
+ * Send an invitation via `POST /api/tenants/{tenantId}/invite`.
298
+ *
299
+ * @param req - Email and optional callback/redirect URLs.
300
+ * @param [rawResponse] - When true, return the raw {@link Response}.
301
+ */
215
302
  invite<T = Response | Invite>(req: string | {
216
303
  email: string;
217
304
  callbackUrl?: string;
@@ -222,11 +309,22 @@ declare class Tenants {
222
309
  callbackUrl?: string;
223
310
  redirectUrl?: string;
224
311
  }, rawResponse: true): Promise<Response>;
312
+ /**
313
+ * Accept an invite using `PUT /api/tenants/{tenantId}/invite`.
314
+ *
315
+ * @param req - Identifier and token from the invite email.
316
+ * @param [rawResponse] - When true, return the raw {@link Response}.
317
+ */
225
318
  acceptInvite<T = Response>(req?: {
226
319
  identifier: string;
227
320
  token: string;
228
- redirectUrl?: string;
321
+ callbackUrl?: string;
229
322
  }, rawResponse?: boolean): Promise<T>;
323
+ /**
324
+ * Delete a pending invite using `DELETE /api/tenants/{tenantId}/invite/{inviteId}`.
325
+ *
326
+ * @param req - Identifier of the invite to remove.
327
+ */
230
328
  deleteInvite<T = Response>(req: string | {
231
329
  id: string;
232
330
  }): Promise<T>;
@@ -270,70 +368,154 @@ type SignUpPayload = {
270
368
  tenantId?: string;
271
369
  newTenantName?: string;
272
370
  };
371
+ /**
372
+ * Utility class that wraps the server side authentication endpoints.
373
+ *
374
+ * The methods in this class call the `fetch*` helpers which are generated
375
+ * from the OpenAPI specification. Those helpers interact with routes under
376
+ * the `/api/auth` prefix such as `/session`, `/signin`, `/signout` and others.
377
+ * By reusing them here we provide a higher level interface for frameworks to
378
+ * manage user authentication.
379
+ */
273
380
  declare class Auth {
274
381
  #private;
382
+ /**
383
+ * Create an Auth helper.
384
+ *
385
+ * @param config - runtime configuration used by the underlying fetch helpers
386
+ * such as `serverOrigin`, `routePrefix` and default headers.
387
+ */
275
388
  constructor(config: Config);
389
+ /**
390
+ * Retrieve the currently active session from the API.
391
+ *
392
+ * Internally this issues a `GET` request to `/api/auth/session` via
393
+ * {@link fetchSession}. If `rawResponse` is `true` the raw {@link Response}
394
+ * object is returned instead of the parsed JSON.
395
+ *
396
+ * @template T Return type for the parsed session.
397
+ * @param rawResponse - set to `true` to get the raw {@link Response} object.
398
+ */
276
399
  getSession<T = JWT | ActiveSession | undefined>(rawResponse?: false): Promise<T>;
277
400
  getSession(rawResponse: true): Promise<Response>;
401
+ /**
402
+ * Acquire a CSRF token for subsequent authenticated requests.
403
+ *
404
+ * Issues a `GET` to `/api/auth/csrf` via {@link obtainCsrf}. When the call
405
+ * succeeds the returned headers are merged into the current configuration so
406
+ * future requests include the appropriate cookies.
407
+ *
408
+ * @param rawResponse - when `true`, skip JSON parsing and return the raw
409
+ * {@link Response}.
410
+ */
278
411
  getCsrf<T = Response | JSON>(rawResponse?: false): Promise<T>;
279
412
  getCsrf(rawResponse: true): Promise<Response>;
413
+ /**
414
+ * List all configured authentication providers.
415
+ *
416
+ * This calls `/api/auth/providers` using {@link fetchProviders} to retrieve
417
+ * the available provider configuration. Providers are returned as an object
418
+ * keyed by provider name.
419
+ *
420
+ * @param rawResponse - when true, return the {@link Response} instead of the
421
+ * parsed JSON.
422
+ */
280
423
  listProviders(rawResponse: true): Promise<Response>;
281
424
  listProviders<T = {
282
425
  [key: string]: Provider;
283
426
  }>(rawResponse?: false): Promise<T>;
427
+ /**
428
+ * Sign the current user out by calling `/api/auth/signout`.
429
+ *
430
+ * The CSRF token is fetched automatically and the stored cookies are cleared
431
+ * from the internal configuration once the request completes.
432
+ */
284
433
  signOut(): Promise<Response>;
285
434
  /**
286
- * signUp only works with email + password
287
- * @param payload
288
- * @param rawResponse
435
+ * Create a new user account and start a session.
436
+ *
437
+ * This method posts to the `/api/signup` endpoint using
438
+ * {@link fetchSignUp}. Only the credential provider is supported; a valid
439
+ * email and password must be supplied. On success the returned session token
440
+ * is stored in the headers used for subsequent requests.
441
+ *
442
+ * @param payload - email and password along with optional tenant
443
+ * information.
444
+ * @param rawResponse - when `true` return the raw {@link Response} rather
445
+ * than the parsed {@link User} object.
289
446
  */
290
447
  signUp(payload: SignUpPayload, rawResponse: true): Promise<Response>;
291
448
  signUp<T = User | Response>(payload: SignUpPayload): Promise<T>;
449
+ /**
450
+ * Request a password reset email.
451
+ *
452
+ * Sends a `POST` to `/api/auth/password-reset` with the provided email and
453
+ * optional callback information. The endpoint responds with a redirect URL
454
+ * which is returned as a {@link Response} object.
455
+ */
292
456
  forgotPassword(req: {
293
457
  email: string;
294
458
  callbackUrl?: string;
295
459
  redirectUrl?: string;
296
460
  }): Promise<Response>;
461
+ /**
462
+ * Complete a password reset.
463
+ *
464
+ * This workflow expects a token obtained from {@link forgotPassword}. The
465
+ * function performs a POST/GET/PUT sequence against
466
+ * `/api/auth/password-reset` as described in the OpenAPI specification.
467
+ *
468
+ * @param req - either a {@link Request} with a JSON body or an object
469
+ * containing the necessary fields.
470
+ */
297
471
  resetPassword(req: Request | {
298
472
  email: string;
299
473
  password: string;
300
474
  callbackUrl?: string;
301
475
  redirectUrl?: string;
302
476
  }): Promise<Response>;
477
+ /**
478
+ * Low level helper used by {@link signIn} to complete provider flows.
479
+ *
480
+ * Depending on the provider this issues either a GET or POST request to
481
+ * `/api/auth/callback/{provider}` via {@link fetchCallback}.
482
+ */
303
483
  callback(provider: ProviderName, body?: string | Request): Promise<Response>;
304
484
  /**
305
- * The return value from this will be a redirect for the client
306
- * In most cases, you should forward the response directly to the client
307
- * @param payload
308
- * @param rawResponse
485
+ * Sign a user in with one of the configured providers.
486
+ *
487
+ * Internally this posts to `/api/auth/signin/{provider}` and follows the
488
+ * provider callback flow as documented in the OpenAPI spec. When using the
489
+ * credential provider an email and password must be supplied.
490
+ *
491
+ * @param payload - request body or credential object
492
+ * @param rawResponse - return the raw {@link Response} instead of parsed JSON
309
493
  */
310
494
  signIn<T = Response>(provider: ProviderName, payload?: Request | {
311
495
  email: string;
312
496
  password: string;
313
497
  }, rawResponse?: true): Promise<T>;
314
498
  }
499
+ /**
500
+ * Extract the CSRF cookie from a set of headers.
501
+ */
315
502
  declare function parseCSRF(headers?: Headers): string | undefined;
503
+ /**
504
+ * Extract the callback cookie from a set of headers.
505
+ */
316
506
  declare function parseCallback(headers?: Headers): string | undefined;
507
+ /**
508
+ * Extract the session token cookie from a set of headers.
509
+ */
317
510
  declare function parseToken(headers?: Headers): string | undefined;
318
-
319
- type CTXHandlerType = {
320
- GET: (req: Request) => Promise<{
321
- response: void | Response;
322
- nile: Server;
323
- }>;
324
- POST: (req: Request) => Promise<{
325
- response: void | Response;
326
- nile: Server;
327
- }>;
328
- DELETE: (req: Request) => Promise<{
329
- response: void | Response;
330
- nile: Server;
331
- }>;
332
- PUT: (req: Request) => Promise<{
333
- response: void | Response;
334
- nile: Server;
335
- }>;
336
- };
511
+ /**
512
+ * Internal helper for the password reset flow.
513
+ */
514
+ declare function parseResetToken(headers: Headers | void): string | void;
515
+ /**
516
+ * Extract the tenantId cookie from a set of headers.
517
+ */
518
+ declare function parseTenantId(headers?: Headers): string | null | undefined;
337
519
 
338
520
  declare class Server {
339
521
  #private;
@@ -341,57 +523,94 @@ declare class Server {
341
523
  tenants: Tenants;
342
524
  auth: Auth;
343
525
  constructor(config?: NileConfig);
526
+ /**
527
+ * Query the database with the current context
528
+ */
529
+ query: Pool['query'];
530
+ /**
531
+ * Return a db object that can be used to talk to the database
532
+ * Does not have a context by default
533
+ */
344
534
  get db(): pg.Pool & {
345
535
  clearConnections: () => void;
346
536
  };
537
+ get logger(): LogReturn;
538
+ get extensions(): {
539
+ remove: (id: string) => Promise<ExtensionResult<any>[] | undefined>;
540
+ add: (extension: Extension) => void;
541
+ };
542
+ get handlers(): NileHandlers;
543
+ get paths(): ConfigurablePaths;
544
+ set paths(paths: ConfigurablePaths);
347
545
  /**
348
- * A convenience function that applies a config and ensures whatever was passed is set properly
546
+ * Sets the context for a particular set of requests or db calls to be sure the context is fully managed for the entire lifecycle
349
547
  */
350
- getInstance<T = Request | Headers | Record<string, string>>(config: NileConfig, req?: T): Server;
351
- getPaths(): {
352
- get: string[];
353
- post: string[];
354
- delete: string[];
355
- put: string[];
356
- };
357
- get handlers(): {
358
- GET: (req: Request) => Promise<void | Response>;
359
- POST: (req: Request) => Promise<void | Response>;
360
- DELETE: (req: Request) => Promise<void | Response>;
361
- PUT: (req: Request) => Promise<void | Response>;
362
- withContext: CTXHandlerType;
363
- };
548
+ withContext(): Promise<this>;
549
+ withContext<T>(context: PartialContext, fn: AsyncCallback<this, T>): Promise<T>;
550
+ withContext(context: PartialContext): Promise<this>;
551
+ withContext<T>(fn: AsyncCallback<this, T>): Promise<T>;
364
552
  /**
365
- * Allow the setting of headers from a req or header object.
366
- * Makes it possible to handle REST requests easily
367
- * Also makes it easy to set user + tenant in some way
368
- * @param req
369
- * @returns undefined
553
+ * Creates a context without a user id and a tenant id, but keeps the headers around for auth at least.
554
+ * This is useful for DDL/DML, since most extensions will set the context by default
370
555
  */
371
- setContext(req: Request | Headers | Record<string, string> | unknown | {
372
- tenantId?: string;
373
- userId?: string;
374
- }): void;
375
- getContext(): {
376
- headers: Headers | undefined;
377
- userId: string | null | undefined;
378
- tenantId: string | null | undefined;
379
- preserveHeaders: boolean;
380
- };
556
+ noContext(): Promise<this>;
557
+ noContext<T>(fn: (sdk: this) => Promise<T>): Promise<T>;
558
+ /**
559
+ *
560
+ * @returns the last used (basically global) context object, useful for debugging or making your own context
561
+ */
562
+ getContext(): Context;
381
563
  }
382
- declare function create(config?: NileConfig): Server;
564
+ declare function create<T = Server>(config?: NileConfig): T;
565
+ type AsyncCallback<TInstance, TResult> = (sdk: TInstance) => Promise<TResult>;
383
566
 
384
567
  type Opts = {
385
568
  basePath?: string;
386
569
  fetch?: typeof fetch;
387
570
  };
388
- interface ExtensionResult {
389
- id?: string;
390
- [key: string]: unknown;
391
- onRequest?: (req: Request) => void | Promise<void | RequestInit>;
392
- onResponse?: (res: Response) => void | Promise<void>;
571
+ type Context = {
572
+ headers: Headers;
573
+ tenantId: string | undefined | null;
574
+ userId: string | undefined | null;
575
+ };
576
+ type PartialContext = {
577
+ headers?: null | Headers;
578
+ tenantId?: string | undefined | null;
579
+ userId?: string | undefined | null;
580
+ useLastContext?: boolean;
581
+ };
582
+ type CTX = {
583
+ run: <T>(ctx: Partial<Context>, fn: () => T) => T;
584
+ get: () => Context;
585
+ set: (partial: Partial<PartialContext>) => void;
586
+ getLastUsed: () => Context;
587
+ };
588
+ type Any = any;
589
+ type ExtensionResult<TParams> = {
590
+ id: string;
591
+ withContext?: (ctx: CTX) => Promise<void>;
592
+ onRequest?: (params: TParams, ctx: CTX) => void | Promise<void | RequestInit>;
593
+ onResponse?: (params: TParams, ctx: CTX) => void | Promise<void>;
594
+ onHandleRequest?: (params?: TParams) => RouteReturn | Promise<RouteReturn>;
595
+ onConfigure?: (params?: TParams) => void;
596
+ withUserId?: () => string;
597
+ withTenantId?: () => string;
598
+ replace?: {
599
+ handlers: (handlers: NileHandlers) => Any;
600
+ };
601
+ };
602
+ type NileHandlers = RouteFunctions & {
603
+ withContext: CTXHandlerType;
604
+ };
605
+ type Extension<TParams = Any> = (instance: Server) => ExtensionResult<TParams>;
606
+ declare enum ExtensionState {
607
+ onHandleRequest = "onHandleRequest",
608
+ onRequest = "onRequest",
609
+ onResponse = "onResponse",
610
+ withContext = "withContext",
611
+ withTenantId = "withTenantId",
612
+ withUserId = "withUserId"
393
613
  }
394
- type Extension = (instance: Server) => ExtensionResult | Promise<ExtensionResult>;
395
614
  type NilePoolConfig = PoolConfig & {
396
615
  afterCreate?: AfterCreate;
397
616
  };
@@ -401,94 +620,95 @@ type LoggerType = {
401
620
  error: (args: unknown | unknown[]) => void;
402
621
  debug: (args: unknown | unknown[]) => void;
403
622
  };
623
+ /**
624
+ * Configuration options used by the {@link Server} class.
625
+ * Most values can be provided via environment variables if not set here.
626
+ */
404
627
  type NileConfig = {
405
628
  /**
406
- * The specific database id. Either passed in or figured out by NILEDB_API_URL
407
- * process.env.NILEDB_ID
629
+ * Unique ID of the database.
630
+ * If omitted, the value is derived from `NILEDB_API_URL`.
631
+ * Environment variable: `NILEDB_ID`.
408
632
  */
409
633
  databaseId?: string;
410
634
  /**
411
- * The user UUID to the database
412
- * process.env.NILEDB_USER
635
+ * Database user used for authentication.
636
+ * Environment variable: `NILEDB_USER`.
413
637
  */
414
638
  user?: string;
415
639
  /**
416
- * The password UUID to the database
417
- * process.env.NILEDB_PASSWORD
640
+ * Password for the configured user.
641
+ * Environment variable: `NILEDB_PASSWORD`.
418
642
  */
419
643
  password?: string;
420
644
  /**
421
- * The name of the database. Automatically obtained from NILEDB_POSTGRES_URL
422
- * process.env.NILEDB_NAME
645
+ * Database name. Defaults to the name parsed from
646
+ * `NILEDB_POSTGRES_URL` when not provided.
647
+ * Environment variable: `NILEDB_NAME`.
423
648
  */
424
649
  databaseName?: string;
425
650
  /**
426
- * A tenant id. Scopes requests to a specific tenant, both API and DB
427
- * process.env.NILEDB_TENANT
651
+ * Tenant context used for scoping API and DB calls.
652
+ * Environment variable: `NILEDB_TENANT`.
428
653
  */
429
654
  tenantId?: string | null | undefined;
430
655
  /**
431
- * A user id. Possibly not the logged in user, used for setting database context (nile.user_id)
432
- * Generally speaking, this wouldn't be used for authentication, and in some cases simply won't do anything on some endpoints
656
+ * Optional user identifier to apply when interacting with the database.
657
+ * In most cases nile-auth injects the logged in user automatically so this
658
+ * value rarely needs to be specified directly. It can be useful when
659
+ * performing administrative actions on behalf of another user.
433
660
  */
434
661
  userId?: string | null | undefined;
435
- /**
436
- * Shows a bunch of logging on the server side to see what's being done between the sdk and nile-auth
437
- */
662
+ /** Enable verbose logging of SDK behaviour. */
438
663
  debug?: boolean;
439
664
  /**
440
- * DB configuration overrides. Environment variables are the way to go, but maybe you need something more
665
+ * Optional Postgres connection configuration.
666
+ * Environment variables will be used for any values not set here.
441
667
  */
442
668
  db?: NilePoolConfig;
443
- /**
444
- * Some kind of logger if you want to send to an external service
445
- */
669
+ /** Custom logger implementation. */
446
670
  logger?: LogReturn;
447
671
  /**
448
- * The configuration value that maps to `NILEDB_API_URL` - its going to be nile-auth (or similar service)
672
+ * Base URL for nile-auth requests.
673
+ * Environment variable: `NILEDB_API_URL`.
449
674
  */
450
675
  apiUrl?: string | undefined;
451
676
  /**
452
- * Ignore client callbackUrls by setting this.
453
- * You can force the callback URL server side to be sure nile-auth redirects to whatever location.
677
+ * Override the client provided callback URL during authentication.
678
+ * Environment variable: `NILEDB_CALLBACK_URL`.
454
679
  */
455
680
  callbackUrl?: string | undefined;
456
- /**
457
- * Need to override some routes? Change it here
458
- */
681
+ /** Override default API routes. */
459
682
  routes?: Partial<Routes>;
460
- /**
461
- * don't like the default `/api`? change it here
462
- */
683
+ /** Prefix applied to all generated routes. */
463
684
  routePrefix?: string | undefined;
464
685
  /**
465
- * In some cases, you may want to force secure cookies.
466
- * The SDK handles this for you, but might be necessary in some firewall / internal cases
467
- * Defaults to true if you're in production
686
+ * Force usage of secure cookies when communicating with nile-auth.
687
+ * Defaults to `true` when `NODE_ENV` is `production`.
688
+ * Environment variable: `NILEDB_SECURECOOKIES`.
468
689
  */
469
690
  secureCookies?: boolean;
470
691
  /**
471
- * The origin for the requests.
472
- * Allows the setting of the callback origin to a random FE
473
- * eg FE localhost:3001 -> BE: localhost:5432 would set to localhost:3001 to be sure nile-auth uses that.
474
- * In full stack cases, will just be the `host` header of the incoming request, which is used by default
475
- * It is also important to set this when dealing with secure cookies. Calling via server side needs to know if TLS is being used so that nile-auth knows which cookies to be sent.
692
+ * Origin for requests made to nile-auth. This controls where users are
693
+ * redirected after authentication. For single-page apps running on a
694
+ * different port than the API, set this to the front-end origin
695
+ * (e.g. `http://localhost:3001`). In a full-stack setup the value defaults
696
+ * to the `host` header of the incoming request. When using secure cookies on
697
+ * server-to-server calls, explicitly setting the origin ensures nile-auth
698
+ * knows whether TLS is being used and which cookies to send.
476
699
  */
477
700
  origin?: null | undefined | string;
478
701
  /**
479
- * Set the headers to use in API requests.
480
- * The `cookie` would be expected if you are setting this, else most calls will be unauthorized
702
+ * Additional headers sent with every API request.
703
+ * Include a `cookie` header to forward session information.
481
704
  */
482
705
  headers?: null | Headers | Record<string, string>;
483
- /**
484
- * Functions to run at various points to make life easier
485
- */
706
+ /** Hooks executed before and after each request. */
486
707
  extensions?: Extension[];
487
708
  /**
488
- * In some cases, like when using REST context, we want to preserve the headers from the request,
489
- * regardless of what an extension might do
709
+ * Re-use the last set context
490
710
  */
491
- preserveHeaders?: boolean;
711
+ useLastContext?: boolean;
492
712
  };
493
713
  type NileDb = NilePoolConfig & {
494
714
  tenantId?: string;
@@ -581,10 +801,31 @@ interface APIError {
581
801
  statusCode: number;
582
802
  }
583
803
  type NileResponse<T> = Promise<T | NResponse<T & APIError>>;
804
+ type ExtensionConfig = {
805
+ disableExtensions: string[];
806
+ };
807
+ type DefaultRouteReturn = Request | Response | ExtensionState;
808
+ type RouteReturn<T = unknown> = void | T | Promise<void | T>;
809
+ type RouteFunctions<T = DefaultRouteReturn> = {
810
+ GET: (req: Request, config?: ExtensionConfig, ...args: unknown[]) => RouteReturn<T>;
811
+ POST: (req: Request, config?: ExtensionConfig, ...args: unknown[]) => RouteReturn<T>;
812
+ DELETE: (req: Request, config?: ExtensionConfig, ...args: unknown[]) => RouteReturn<T>;
813
+ PUT: (req: Request, config?: ExtensionConfig, ...args: unknown[]) => RouteReturn<T>;
814
+ };
815
+ type ContextReturn<T = Response> = {
816
+ response: T;
817
+ nile: Server;
818
+ };
819
+ type CTXHandlerType = {
820
+ GET: <T = Response>(req: Request) => Promise<ContextReturn<T>>;
821
+ POST: <T = Response>(req: Request) => Promise<ContextReturn<T>>;
822
+ DELETE: <T = Response>(req: Request) => Promise<ContextReturn<T>>;
823
+ PUT: <T = Response>(req: Request) => Promise<ContextReturn<T>>;
824
+ };
584
825
 
585
826
  declare const TENANT_COOKIE = "nile.tenant-id";
586
827
  declare const USER_COOKIE = "nile.user-id";
587
828
  declare const HEADER_ORIGIN = "nile-origin";
588
829
  declare const HEADER_SECURE_COOKIES = "nile-secure-cookies";
589
830
 
590
- export { type APIError, APIErrorErrorCodeEnum, type ActiveSession, type AfterCreate, type CreateBasicUserRequest, type CreateTenantUserRequest, type Extension, type ExtensionResult, HEADER_ORIGIN, HEADER_SECURE_COOKIES, type Invite, type JWT, type LoggerType, type LoginUserResponse, type LoginUserResponseToken, LoginUserResponseTokenTypeEnum, create as Nile, type NileConfig, type NileDb, type NilePoolConfig, type NileRequest, type NileResponse, type Opts, type Providers, Server, TENANT_COOKIE, type Tenant, USER_COOKIE, type User, parseCSRF, parseCallback, parseToken };
831
+ export { type APIError, APIErrorErrorCodeEnum, type ActiveSession, type AfterCreate, type CTX, type CTXHandlerType, type Context, type ContextReturn, type CreateBasicUserRequest, type CreateTenantUserRequest, type Extension, type ExtensionResult, ExtensionState, HEADER_ORIGIN, HEADER_SECURE_COOKIES, type Invite, type JWT, type LoggerType, type LoginUserResponse, type LoginUserResponseToken, LoginUserResponseTokenTypeEnum, create as Nile, type NileConfig, type NileDb, type NileHandlers, type NilePoolConfig, type NileRequest, type NileResponse, type Opts, type PartialContext, type Providers, type RouteFunctions, type RouteReturn, Server, TENANT_COOKIE, type Tenant, USER_COOKIE, type User, parseCSRF, parseCallback, parseResetToken, parseTenantId, parseToken };