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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/express.js DELETED
@@ -1,1433 +0,0 @@
1
- 'use strict';
2
-
3
- require('dotenv/config');
4
-
5
- // src/api/utils/routes/index.ts
6
- var NILEDB_API_URL = process.env.NILEDB_API_URL;
7
- var DEFAULT_PREFIX = "/api";
8
- var appRoutes = (prefix = DEFAULT_PREFIX) => ({
9
- SIGNIN: `${prefix}${"/auth/signin" /* SIGNIN */}`,
10
- PROVIDERS: `${prefix}${"/auth/providers" /* PROVIDERS */}`,
11
- SESSION: `${prefix}${"/auth/session" /* SESSION */}`,
12
- CSRF: `${prefix}${"/auth/csrf" /* CSRF */}`,
13
- CALLBACK: `${prefix}${"/auth/callback" /* CALLBACK */}`,
14
- SIGNOUT: `${prefix}${"/auth/signout" /* SIGNOUT */}`,
15
- ERROR: `${prefix}/auth/error`,
16
- VERIFY_REQUEST: `${prefix}/auth/verify-request`,
17
- VERIFY_EMAIL: `${prefix}${"/auth/verify-email" /* VERIFY_EMAIL */}`,
18
- PASSWORD_RESET: `${prefix}${"/auth/reset-password" /* PASSWORD_RESET */}`,
19
- ME: `${prefix}${"/me" /* ME */}`,
20
- USERS: `${prefix}${"/users" /* USERS */}`,
21
- USER_TENANTS: `${prefix}${"/users/{userId}/tenants" /* USER_TENANTS */}`,
22
- TENANTS: `${prefix}${"/tenants" /* TENANTS */}`,
23
- TENANT: `${prefix}${"/tenants/{tenantId}" /* TENANT */}`,
24
- TENANT_USER: `${prefix}${"/tenants/{tenantId}/users/{userId}" /* TENANT_USER */}`,
25
- TENANT_USERS: `${prefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */}`,
26
- SIGNUP: `${prefix}${"/signup" /* SIGNUP */}`,
27
- LOG: `${prefix}/_log`
28
- });
29
- var apiRoutes = (config) => ({
30
- ME: makeRestUrl(config, "/me"),
31
- USERS: (qp) => makeRestUrl(config, "/users", qp),
32
- USER: (userId) => makeRestUrl(config, `/users/${userId}`),
33
- TENANTS: makeRestUrl(config, "/tenants"),
34
- TENANT: (tenantId) => makeRestUrl(config, `/tenants/${tenantId}`),
35
- SIGNUP: makeRestUrl(config, "/signup"),
36
- TENANT_USERS: (tenantId) => makeRestUrl(config, `/tenants/${tenantId}/users`),
37
- TENANT_USER: makeRestUrl(
38
- config,
39
- `/tenants/${config.tenantId}/users/${config.userId}`
40
- ),
41
- USER_TENANTS: (userId) => makeRestUrl(config, `/users/${userId}/tenants`)
42
- });
43
- var proxyRoutes = (config) => ({
44
- SIGNIN: makeRestUrl(config, "/auth/signin" /* SIGNIN */),
45
- PROVIDERS: makeRestUrl(config, "/auth/providers" /* PROVIDERS */),
46
- SESSION: makeRestUrl(config, "/auth/session" /* SESSION */),
47
- CSRF: makeRestUrl(config, "/auth/csrf" /* CSRF */),
48
- CALLBACK: makeRestUrl(config, "/auth/callback" /* CALLBACK */),
49
- SIGNOUT: makeRestUrl(config, "/auth/signout" /* SIGNOUT */),
50
- ERROR: makeRestUrl(config, "/auth/error"),
51
- VERIFY_REQUEST: makeRestUrl(config, "/auth/verify-request"),
52
- PASSWORD_RESET: makeRestUrl(config, "/auth/reset-password" /* PASSWORD_RESET */),
53
- VERIFY_EMAIL: makeRestUrl(config, "/auth/verify-email" /* VERIFY_EMAIL */)
54
- });
55
- function filterNullUndefined(obj) {
56
- if (!obj) {
57
- return void 0;
58
- }
59
- return Object.fromEntries(
60
- Object.entries(obj).filter(
61
- ([, value]) => value !== null && value !== void 0
62
- )
63
- );
64
- }
65
- function makeRestUrl(config, path, qp) {
66
- const url = config.apiUrl || NILEDB_API_URL;
67
- if (!url) {
68
- throw new Error(
69
- "An API url is required. Set it via NILEDB_API_URL. Was auto configuration run?"
70
- );
71
- }
72
- const params = new URLSearchParams(
73
- filterNullUndefined(qp)
74
- );
75
- const strParams = params.toString();
76
- return `${[url, path.substring(1, path.length)].join("/")}${strParams ? `?${strParams}` : ""}`;
77
- }
78
- function urlMatches(requestUrl, route17) {
79
- const url = new URL(requestUrl);
80
- return url.pathname.startsWith(route17);
81
- }
82
- function isUUID(value) {
83
- if (!value) {
84
- return false;
85
- }
86
- const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5|7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
87
- return regex.test(value);
88
- }
89
-
90
- // src/utils/Logger.ts
91
- var red = "\x1B[31m";
92
- var yellow = "\x1B[38;2;255;255;0m";
93
- var purple = "\x1B[38;2;200;160;255m";
94
- var orange = "\x1B[38;2;255;165;0m";
95
- var reset = "\x1B[0m";
96
- var baseLogger = (config, ...params) => ({
97
- info(message, meta) {
98
- if (config?.debug) {
99
- console.info(
100
- `${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
101
- ""
102
- )}${reset} ${message}`,
103
- meta ? `${JSON.stringify(meta)}` : ""
104
- );
105
- }
106
- },
107
- debug(message, meta) {
108
- if (config?.debug) {
109
- console.debug(
110
- `${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
111
- ""
112
- )}${reset} ${message}`,
113
- meta ? `${JSON.stringify(meta)}` : ""
114
- );
115
- }
116
- },
117
- warn(message, meta) {
118
- if (config?.debug) {
119
- console.warn(
120
- `${orange}[niledb]${reset}${yellow}[WARN]${reset}${params.join(
121
- ""
122
- )}${reset} ${message}`,
123
- meta ? JSON.stringify(meta) : ""
124
- );
125
- }
126
- },
127
- error(message, meta) {
128
- console.error(
129
- `${orange}[niledb]${reset}${red}[ERROR]${reset}${params.join(
130
- ""
131
- )}${red} ${message}`,
132
- meta ? meta : "",
133
- `${reset}`
134
- );
135
- }
136
- });
137
- function Logger(config, ...params) {
138
- const base = baseLogger(config, params);
139
- const info = config?.logger?.info ?? base.info;
140
- const debug = config?.logger?.debug ?? base.debug;
141
- const warn = config?.logger?.warn ?? base.warn;
142
- const error = config?.logger?.error ?? base.error;
143
- return { info, warn, error, debug };
144
- }
145
- function matchesLog(configRoutes, request2) {
146
- return urlMatches(request2.url, configRoutes.LOG);
147
- }
148
-
149
- // src/utils/constants.ts
150
- var X_NILE_TENANT = "nile-tenant-id";
151
- var X_NILE_ORIGIN = "nile-origin";
152
- var X_NILE_SECURECOOKIES = "nile-secure-cookies";
153
-
154
- // src/api/utils/request.ts
155
- async function request(url, _init, config) {
156
- const { debug, info, error } = Logger(config, "[REQUEST]");
157
- const { request: request2, ...init } = _init;
158
- const requestUrl = new URL(request2.url);
159
- const updatedHeaders = new Headers({});
160
- if (request2.headers.get("cookie")) {
161
- updatedHeaders.set("cookie", String(request2.headers.get("cookie")));
162
- }
163
- if (request2.headers.get(X_NILE_TENANT)) {
164
- updatedHeaders.set(
165
- X_NILE_TENANT,
166
- String(request2.headers.get(X_NILE_TENANT))
167
- );
168
- }
169
- if (config.secureCookies != null) {
170
- updatedHeaders.set(X_NILE_SECURECOOKIES, String(config.secureCookies));
171
- } else {
172
- updatedHeaders.set(
173
- X_NILE_SECURECOOKIES,
174
- process.env.NODE_ENV === "production" ? "true" : "false"
175
- );
176
- }
177
- updatedHeaders.set("host", requestUrl.host);
178
- if (config.callbackUrl) {
179
- const cbUrl = new URL(config.callbackUrl);
180
- debug(`Obtained origin from config.callbackUrl ${config.callbackUrl}`);
181
- updatedHeaders.set(X_NILE_ORIGIN, cbUrl.origin);
182
- } else if (config.origin) {
183
- debug(`Obtained origin from config.origin ${config.origin}`);
184
- updatedHeaders.set(X_NILE_ORIGIN, config.origin);
185
- } else {
186
- const passedOrigin = request2.headers.get(X_NILE_ORIGIN);
187
- if (passedOrigin) {
188
- updatedHeaders.set(X_NILE_ORIGIN, passedOrigin);
189
- } else {
190
- const reqOrigin = config.routePrefix !== DEFAULT_PREFIX ? `${requestUrl.origin}${config.routePrefix}` : requestUrl.origin;
191
- updatedHeaders.set(X_NILE_ORIGIN, reqOrigin);
192
- debug(`Obtained origin from request ${reqOrigin}`);
193
- }
194
- }
195
- const params = { ...init };
196
- if (params.method?.toLowerCase() === "post" || params.method?.toLowerCase() === "put") {
197
- try {
198
- updatedHeaders.set("content-type", "application/json");
199
- const initBody = await new Response(_init.request.clone().body).json();
200
- const requestBody = await new Response(request2.clone().body).json();
201
- params.body = JSON.stringify(initBody ?? requestBody);
202
- } catch (e) {
203
- updatedHeaders.set("content-type", "application/x-www-form-urlencoded");
204
- const initBody = await new Response(_init.request.clone().body).text();
205
- const requestBody = await new Response(request2.clone().body).text();
206
- params.body = initBody ?? requestBody;
207
- }
208
- }
209
- params.headers = updatedHeaders;
210
- const fullUrl = `${url}${requestUrl.search}`;
211
- if (config.debug) {
212
- params.headers.set("request-id", crypto.randomUUID());
213
- params.cache = "no-store";
214
- }
215
- try {
216
- const res = await fetch(fullUrl, {
217
- ...params
218
- }).catch((e) => {
219
- error("An error has occurred in the fetch", {
220
- message: e.message,
221
- stack: e.stack
222
- });
223
- return new Response(
224
- "An unexpected (most likely configuration) problem has occurred",
225
- { status: 500 }
226
- );
227
- });
228
- const loggingRes = typeof res?.clone === "function" ? res?.clone() : null;
229
- info(`[${params.method ?? "GET"}] ${fullUrl}`, {
230
- status: res?.status,
231
- statusText: res?.statusText,
232
- text: await loggingRes?.text()
233
- });
234
- return res;
235
- } catch (e) {
236
- if (e instanceof Error) {
237
- error("An error has occurred in the fetch", {
238
- message: e.message,
239
- stack: e.stack
240
- });
241
- }
242
- return new Response(
243
- "An unexpected (most likely configuration) problem has occurred",
244
- { status: 500 }
245
- );
246
- }
247
- }
248
-
249
- // src/api/utils/auth.ts
250
- async function auth(req, config) {
251
- const { info, error } = Logger(config, "[nileauth]");
252
- info("checking auth");
253
- const sessionUrl = `${config.apiUrl}/auth/session`;
254
- info(`using session ${sessionUrl}`);
255
- req.headers.delete("content-length");
256
- const res = await request(sessionUrl, { request: req }, config);
257
- if (!res) {
258
- info("no session found");
259
- return void 0;
260
- }
261
- info("session active");
262
- try {
263
- const session = await new Response(res.body).json();
264
- if (Object.keys(session).length === 0) {
265
- return void 0;
266
- }
267
- return session;
268
- } catch (e) {
269
- error(e);
270
- return void 0;
271
- }
272
- }
273
-
274
- // src/api/routes/me/index.ts
275
- var key = "ME";
276
- async function route(request2, config) {
277
- const url = apiRoutes(config)[key];
278
- if (request2.method === "GET") {
279
- return await GET(url, { request: request2 }, config);
280
- }
281
- if (request2.method === "PUT") {
282
- return await PUT(url, { request: request2 }, config);
283
- }
284
- if (request2.method === "DELETE") {
285
- const session = await auth(request2, config);
286
- if (!session) {
287
- return new Response(null, { status: 401 });
288
- }
289
- return await DELETE(url, { request: request2 }, config);
290
- }
291
- return new Response("method not allowed", { status: 405 });
292
- }
293
- function matches(configRoutes, request2) {
294
- return urlMatches(request2.url, configRoutes[key]);
295
- }
296
- async function DELETE(url, init, config) {
297
- init.method = "DELETE";
298
- return await request(url, init, config);
299
- }
300
- async function PUT(url, init, config) {
301
- init.method = "PUT";
302
- return await request(url, init, config);
303
- }
304
- async function GET(url, init, config) {
305
- const res = await request(url, init, config);
306
- return res;
307
- }
308
-
309
- // src/utils/fetch.ts
310
- function getTokenFromCookie(headers, cookieKey) {
311
- const cookie = headers.get("cookie")?.split("; ");
312
- const _cookies = {};
313
- if (cookie) {
314
- for (const parts of cookie) {
315
- const cookieParts = parts.split("=");
316
- const _cookie = cookieParts.slice(1).join("=");
317
- const name = cookieParts[0];
318
- _cookies[name] = _cookie;
319
- }
320
- }
321
- if (cookie) {
322
- for (const parts of cookie) {
323
- const cookieParts = parts.split("=");
324
- const _cookie = cookieParts.slice(1).join("=");
325
- const name = cookieParts[0];
326
- _cookies[name] = _cookie;
327
- }
328
- }
329
- {
330
- return _cookies[cookieKey];
331
- }
332
- }
333
- function getTenantFromHttp(headers, config) {
334
- const cookieTenant = getTokenFromCookie(headers, X_NILE_TENANT);
335
- return cookieTenant ?? headers?.get(X_NILE_TENANT) ?? config?.tenantId;
336
- }
337
-
338
- // src/api/routes/users/POST.ts
339
- async function POST(config, init) {
340
- init.body = init.request.body;
341
- init.method = "POST";
342
- const yurl = new URL(init.request.url);
343
- const tenantId = yurl.searchParams.get("tenantId");
344
- const newTenantName = yurl.searchParams.get("newTenantName");
345
- const tenant = tenantId ?? getTenantFromHttp(init.request.headers);
346
- const url = apiRoutes(config).USERS({ tenantId: tenant, newTenantName });
347
- return await request(url, init, config);
348
- }
349
-
350
- // src/api/routes/users/GET.ts
351
- async function GET2(config, init, log) {
352
- const yurl = new URL(init.request.url);
353
- const tenantId = yurl.searchParams.get("tenantId");
354
- const tenant = tenantId ?? getTenantFromHttp(init.request.headers);
355
- if (!tenant) {
356
- log("[GET] No tenant id provided.");
357
- return new Response(null, { status: 404 });
358
- }
359
- const url = apiRoutes(config).TENANT_USERS(tenant);
360
- init.method = "GET";
361
- return await request(url, init, config);
362
- }
363
-
364
- // src/api/routes/users/[userId]/PUT.ts
365
- async function PUT2(config, session, init) {
366
- if (!session) {
367
- return new Response(null, { status: 401 });
368
- }
369
- init.body = init.request.body;
370
- init.method = "PUT";
371
- const [userId] = new URL(init.request.url).pathname.split("/").reverse();
372
- const url = apiRoutes(config).USER(userId);
373
- return await request(url, init, config);
374
- }
375
-
376
- // src/api/routes/users/index.ts
377
- var key2 = "USERS";
378
- async function route2(request2, config) {
379
- const { info } = Logger(
380
- { ...config, debug: config.debug },
381
- `[ROUTES][${key2}]`
382
- );
383
- const session = await auth(request2, config);
384
- switch (request2.method) {
385
- case "GET":
386
- return await GET2(config, { request: request2 }, info);
387
- case "POST":
388
- return await POST(config, { request: request2 });
389
- case "PUT":
390
- return await PUT2(config, session, { request: request2 });
391
- default:
392
- return new Response("method not allowed", { status: 405 });
393
- }
394
- }
395
- function matches2(configRoutes, request2) {
396
- return urlMatches(request2.url, configRoutes[key2]);
397
- }
398
-
399
- // src/api/routes/tenants/[tenantId]/users/GET.ts
400
- async function GET3(config, init) {
401
- const yurl = new URL(init.request.url);
402
- const [, tenantId] = yurl.pathname.split("/").reverse();
403
- const url = `${apiRoutes(config).TENANT_USERS(tenantId)}`;
404
- return await request(url, init, config);
405
- }
406
-
407
- // src/api/routes/tenants/[tenantId]/users/POST.ts
408
- async function POST2(config, session, init) {
409
- const yurl = new URL(init.request.url);
410
- const [, tenantId] = yurl.pathname.split("/").reverse();
411
- init.body = JSON.stringify({ email: session.email });
412
- init.method = "POST";
413
- const url = apiRoutes(config).TENANT_USERS(tenantId);
414
- return await request(url, init, config);
415
- }
416
-
417
- // src/api/routes/tenants/[tenantId]/users/index.ts
418
- var key3 = "TENANT_USERS";
419
- async function route3(request2, config) {
420
- const { info } = Logger(
421
- { ...config, debug: config.debug },
422
- `[ROUTES][${key3}]`
423
- );
424
- const session = await auth(request2, config);
425
- if (!session) {
426
- info("401");
427
- return new Response(null, { status: 401 });
428
- }
429
- const yurl = new URL(request2.url);
430
- const [, tenantId] = yurl.pathname.split("/").reverse();
431
- if (!tenantId) {
432
- info("No tenant id found in path");
433
- return new Response(null, { status: 404 });
434
- }
435
- switch (request2.method) {
436
- case "GET":
437
- return await GET3(config, { request: request2 });
438
- case "POST":
439
- return await POST2(config, session, { request: request2 });
440
- default:
441
- return new Response("method not allowed", { status: 405 });
442
- }
443
- }
444
- function matches3(configRoutes, request2) {
445
- const url = new URL(request2.url);
446
- const [userId, possibleTenantId, tenantId] = url.pathname.split("/").reverse();
447
- let route17 = configRoutes[key3].replace("{tenantId}", tenantId).replace("{userId}", userId);
448
- if (userId === "users") {
449
- route17 = configRoutes[key3].replace("{tenantId}", possibleTenantId);
450
- }
451
- return urlMatches(request2.url, route17);
452
- }
453
-
454
- // src/api/routes/tenants/GET.ts
455
- async function GET4(config, session, init) {
456
- let url = `${apiRoutes(config).USER_TENANTS(session.id)}`;
457
- if (typeof session === "object" && "user" in session && session.user) {
458
- url = `${apiRoutes(config).USER_TENANTS(session.user.id)}`;
459
- }
460
- const res = await request(url, init, config);
461
- return res;
462
- }
463
-
464
- // src/api/routes/tenants/[tenantId]/GET.ts
465
- async function GET5(config, init, log) {
466
- const yurl = new URL(init.request.url);
467
- const [tenantId] = yurl.pathname.split("/").reverse();
468
- if (!tenantId) {
469
- log("[GET] No tenant id provided.");
470
- return new Response(null, { status: 404 });
471
- }
472
- init.method = "GET";
473
- const url = `${apiRoutes(config).TENANT(tenantId)}`;
474
- return await request(url, init, config);
475
- }
476
-
477
- // src/api/routes/tenants/[tenantId]/DELETE.ts
478
- async function DELETE2(config, init) {
479
- const yurl = new URL(init.request.url);
480
- const [tenantId] = yurl.pathname.split("/").reverse();
481
- if (!tenantId) {
482
- return new Response(null, { status: 404 });
483
- }
484
- init.method = "DELETE";
485
- const url = `${apiRoutes(config).TENANT(tenantId)}`;
486
- return await request(url, init, config);
487
- }
488
-
489
- // src/api/routes/tenants/[tenantId]/PUT.ts
490
- async function PUT3(config, init) {
491
- const yurl = new URL(init.request.url);
492
- const [tenantId] = yurl.pathname.split("/").reverse();
493
- if (!tenantId) {
494
- return new Response(null, { status: 404 });
495
- }
496
- init.body = init.request.body;
497
- init.method = "PUT";
498
- const url = `${apiRoutes(config).TENANT(tenantId)}`;
499
- return await request(url, init, config);
500
- }
501
-
502
- // src/api/routes/tenants/POST.ts
503
- async function POST3(config, init) {
504
- init.body = init.request.body;
505
- init.method = "POST";
506
- const url = `${apiRoutes(config).TENANTS}`;
507
- return await request(url, init, config);
508
- }
509
-
510
- // src/api/routes/tenants/index.ts
511
- var key4 = "TENANTS";
512
- async function route4(request2, config) {
513
- const { info } = Logger(
514
- { ...config, debug: config.debug },
515
- `[ROUTES][${key4}]`
516
- );
517
- const session = await auth(request2, config);
518
- if (!session) {
519
- info("401");
520
- return new Response(null, { status: 401 });
521
- }
522
- const [possibleTenantId] = request2.url.split("/").reverse();
523
- switch (request2.method) {
524
- case "GET":
525
- if (isUUID(possibleTenantId)) {
526
- return await GET5(config, { request: request2 }, info);
527
- }
528
- return await GET4(config, session, { request: request2 });
529
- case "POST":
530
- return await POST3(config, { request: request2 });
531
- case "DELETE":
532
- return await DELETE2(config, { request: request2 });
533
- case "PUT":
534
- return await PUT3(config, { request: request2 });
535
- default:
536
- return new Response("method not allowed", { status: 405 });
537
- }
538
- }
539
- function matches4(configRoutes, request2) {
540
- return urlMatches(request2.url, configRoutes[key4]);
541
- }
542
-
543
- // src/api/routes/auth/signin.ts
544
- var key5 = "SIGNIN";
545
- async function route5(req, config) {
546
- let url = proxyRoutes(config)[key5];
547
- const init = {
548
- method: req.method,
549
- headers: req.headers
550
- };
551
- if (req.method === "POST") {
552
- const [provider] = new URL(req.url).pathname.split("/").reverse();
553
- url = `${proxyRoutes(config)[key5]}/${provider}`;
554
- }
555
- const passThroughUrl = new URL(req.url);
556
- const params = new URLSearchParams(passThroughUrl.search);
557
- url = `${url}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
558
- const res = await request(url, { ...init, request: req }, config);
559
- return res;
560
- }
561
- function matches5(configRoutes, request2) {
562
- return urlMatches(request2.url, configRoutes[key5]);
563
- }
564
-
565
- // src/api/routes/auth/session.ts
566
- async function route6(req, config) {
567
- return request(
568
- proxyRoutes(config).SESSION,
569
- {
570
- method: req.method,
571
- request: req
572
- },
573
- config
574
- );
575
- }
576
- function matches6(configRoutes, request2) {
577
- return urlMatches(request2.url, configRoutes.SESSION);
578
- }
579
-
580
- // src/api/routes/auth/providers.ts
581
- async function route7(req, config) {
582
- return request(
583
- proxyRoutes(config).PROVIDERS,
584
- {
585
- method: req.method,
586
- request: req
587
- },
588
- config
589
- );
590
- }
591
- function matches7(configRoutes, request2) {
592
- return urlMatches(request2.url, configRoutes.PROVIDERS);
593
- }
594
-
595
- // src/api/routes/auth/csrf.ts
596
- async function route8(req, config) {
597
- return request(
598
- proxyRoutes(config).CSRF,
599
- {
600
- method: req.method,
601
- request: req
602
- },
603
- config
604
- );
605
- }
606
- function matches8(configRoutes, request2) {
607
- return urlMatches(request2.url, configRoutes.CSRF);
608
- }
609
-
610
- // src/api/routes/auth/callback.ts
611
- var key6 = "CALLBACK";
612
- async function route9(req, config) {
613
- const { error } = Logger(
614
- { ...config, debug: config.debug },
615
- `[ROUTES][${key6}]`
616
- );
617
- const [provider] = new URL(req.url).pathname.split("/").reverse();
618
- try {
619
- const passThroughUrl = new URL(req.url);
620
- const params = new URLSearchParams(passThroughUrl.search);
621
- const url = `${proxyRoutes(config)[key6]}/${provider}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
622
- const res = await request(
623
- url,
624
- {
625
- request: req,
626
- method: req.method
627
- },
628
- config
629
- ).catch((e) => {
630
- error("an error as occurred", e);
631
- });
632
- const location = res?.headers.get("location");
633
- if (location) {
634
- return new Response(res?.body, {
635
- status: 302,
636
- headers: res?.headers
637
- });
638
- }
639
- return new Response(res?.body, {
640
- status: res?.status,
641
- headers: res?.headers
642
- });
643
- } catch (e) {
644
- error(e);
645
- }
646
- return new Response("An unexpected error has occurred.", { status: 400 });
647
- }
648
- function matches9(configRoutes, request2) {
649
- return urlMatches(request2.url, configRoutes.CALLBACK);
650
- }
651
-
652
- // src/api/routes/auth/signout.ts
653
- var key7 = "SIGNOUT";
654
- async function route10(request2, config) {
655
- let url = proxyRoutes(config)[key7];
656
- const init = {
657
- method: request2.method
658
- };
659
- if (request2.method === "POST") {
660
- init.body = request2.body;
661
- const [provider] = new URL(request2.url).pathname.split("/").reverse();
662
- url = `${proxyRoutes(config)[key7]}${provider !== "signout" ? `/${provider}` : ""}`;
663
- }
664
- const res = await request(url, { ...init, request: request2 }, config);
665
- return res;
666
- }
667
- function matches10(configRoutes, request2) {
668
- return urlMatches(request2.url, configRoutes[key7]);
669
- }
670
-
671
- // src/api/routes/auth/error.ts
672
- var key8 = "ERROR";
673
- async function route11(req, config) {
674
- return request(
675
- proxyRoutes(config)[key8],
676
- {
677
- method: req.method,
678
- request: req
679
- },
680
- config
681
- );
682
- }
683
- function matches11(configRoutes, request2) {
684
- return urlMatches(request2.url, configRoutes[key8]);
685
- }
686
-
687
- // src/api/routes/auth/verify-request.ts
688
- var key9 = "VERIFY_REQUEST";
689
- async function route12(req, config) {
690
- return request(
691
- proxyRoutes(config)[key9],
692
- {
693
- method: req.method,
694
- request: req
695
- },
696
- config
697
- );
698
- }
699
- function matches12(configRoutes, request2) {
700
- return urlMatches(request2.url, configRoutes[key9]);
701
- }
702
-
703
- // src/api/routes/auth/password-reset.ts
704
- var key10 = "PASSWORD_RESET";
705
- async function route13(req, config) {
706
- const url = proxyRoutes(config)[key10];
707
- const res = await request(
708
- url,
709
- {
710
- method: req.method,
711
- request: req
712
- },
713
- config
714
- );
715
- const location = res?.headers.get("location");
716
- if (location) {
717
- return new Response(res?.body, {
718
- status: 302,
719
- headers: res?.headers
720
- });
721
- }
722
- return new Response(res?.body, {
723
- status: res?.status,
724
- headers: res?.headers
725
- });
726
- }
727
- function matches13(configRoutes, request2) {
728
- return urlMatches(request2.url, configRoutes.PASSWORD_RESET);
729
- }
730
-
731
- // src/api/routes/auth/verify-email.ts
732
- var key11 = "VERIFY_EMAIL";
733
- async function route14(req, config) {
734
- const url = proxyRoutes(config)[key11];
735
- const res = await request(
736
- url,
737
- {
738
- method: req.method,
739
- request: req
740
- },
741
- config
742
- );
743
- const location = res?.headers.get("location");
744
- if (location) {
745
- return new Response(res?.body, {
746
- status: 302,
747
- headers: res?.headers
748
- });
749
- }
750
- return new Response(res?.body, {
751
- status: res?.status,
752
- headers: res?.headers
753
- });
754
- }
755
- function matches14(configRoutes, request2) {
756
- return urlMatches(request2.url, configRoutes[key11]);
757
- }
758
-
759
- // src/api/handlers/GET.ts
760
- function GETTER(configRoutes, config) {
761
- const { info, warn } = Logger(config, "[GET MATCHER]");
762
- return async function GET6(req) {
763
- if (matches(configRoutes, req)) {
764
- info("matches me");
765
- return route(req, config);
766
- }
767
- if (matches3(configRoutes, req)) {
768
- info("matches tenant users");
769
- return route3(req, config);
770
- }
771
- if (matches2(configRoutes, req)) {
772
- info("matches users");
773
- return route2(req, config);
774
- }
775
- if (matches4(configRoutes, req)) {
776
- info("matches tenants");
777
- return route4(req, config);
778
- }
779
- if (matches6(configRoutes, req)) {
780
- info("matches session");
781
- return route6(req, config);
782
- }
783
- if (matches5(configRoutes, req)) {
784
- info("matches signin");
785
- return route5(req, config);
786
- }
787
- if (matches7(configRoutes, req)) {
788
- info("matches providers");
789
- return route7(req, config);
790
- }
791
- if (matches8(configRoutes, req)) {
792
- info("matches csrf");
793
- return route8(req, config);
794
- }
795
- if (matches13(configRoutes, req)) {
796
- info("matches password reset");
797
- return route13(req, config);
798
- }
799
- if (matches9(configRoutes, req)) {
800
- info("matches callback");
801
- return route9(req, config);
802
- }
803
- if (matches10(configRoutes, req)) {
804
- info("matches signout");
805
- return route10(req, config);
806
- }
807
- if (matches12(configRoutes, req)) {
808
- info("matches verify-request");
809
- return route12(req, config);
810
- }
811
- if (matches14(configRoutes, req)) {
812
- info("matches verify-email");
813
- return route14(req, config);
814
- }
815
- if (matches11(configRoutes, req)) {
816
- info("matches error");
817
- return route11(req, config);
818
- }
819
- warn(`No GET routes matched ${req.url}`);
820
- return new Response(null, { status: 404 });
821
- };
822
- }
823
-
824
- // src/api/routes/signup/POST.ts
825
- async function POST4(config, init) {
826
- init.body = init.request.body;
827
- init.method = "POST";
828
- const url = `${apiRoutes(config).SIGNUP}`;
829
- return await request(url, init, config);
830
- }
831
-
832
- // src/api/routes/signup/index.tsx
833
- var key12 = "SIGNUP";
834
- async function route15(request2, config) {
835
- switch (request2.method) {
836
- case "POST":
837
- return await POST4(config, { request: request2 });
838
- default:
839
- return new Response("method not allowed", { status: 405 });
840
- }
841
- }
842
- function matches15(configRoutes, request2) {
843
- return urlMatches(request2.url, configRoutes[key12]);
844
- }
845
-
846
- // src/api/handlers/POST.ts
847
- function POSTER(configRoutes, config) {
848
- const { info, warn, error } = Logger(config, "[POST MATCHER]");
849
- return async function POST5(req) {
850
- if (matchesLog(configRoutes, req)) {
851
- try {
852
- const json = await req.clone().json();
853
- error(req.body && json);
854
- } catch {
855
- error(await req.text());
856
- }
857
- return new Response(null, { status: 200 });
858
- }
859
- if (matches3(configRoutes, req)) {
860
- info("matches tenant users");
861
- return route3(req, config);
862
- }
863
- if (matches15(configRoutes, req)) {
864
- info("matches signup");
865
- return route15(req, config);
866
- }
867
- if (matches2(configRoutes, req)) {
868
- info("matches users");
869
- return route2(req, config);
870
- }
871
- if (matches4(configRoutes, req)) {
872
- info("matches tenants");
873
- return route4(req, config);
874
- }
875
- if (matches6(configRoutes, req)) {
876
- info("matches session");
877
- return route6(req, config);
878
- }
879
- if (matches5(configRoutes, req)) {
880
- info("matches signin");
881
- return route5(req, config);
882
- }
883
- if (matches13(configRoutes, req)) {
884
- info("matches password reset");
885
- return route13(req, config);
886
- }
887
- if (matches7(configRoutes, req)) {
888
- info("matches providers");
889
- return route7(req, config);
890
- }
891
- if (matches8(configRoutes, req)) {
892
- info("matches csrf");
893
- return route8(req, config);
894
- }
895
- if (matches9(configRoutes, req)) {
896
- info("matches callback");
897
- return route9(req, config);
898
- }
899
- if (matches10(configRoutes, req)) {
900
- info("matches signout");
901
- return route10(req, config);
902
- }
903
- if (matches14(configRoutes, req)) {
904
- info("matches verify-email");
905
- return route14(req, config);
906
- }
907
- warn(`No POST routes matched ${req.url}`);
908
- return new Response(null, { status: 404 });
909
- };
910
- }
911
-
912
- // src/api/routes/tenants/[tenantId]/users/[userId]/DELETE.ts
913
- async function DELETE3(config, init) {
914
- const yurl = new URL(init.request.url);
915
- const [, userId, , tenantId] = yurl.pathname.split("/").reverse();
916
- config.tenantId = tenantId;
917
- config.userId = userId;
918
- init.method = "DELETE";
919
- const url = `${apiRoutes(config).TENANT_USER}/link`;
920
- return await request(url, init, config);
921
- }
922
-
923
- // src/api/routes/tenants/[tenantId]/users/[userId]/PUT.ts
924
- async function PUT4(config, init) {
925
- const yurl = new URL(init.request.url);
926
- const [, userId, , tenantId] = yurl.pathname.split("/").reverse();
927
- config.tenantId = tenantId;
928
- config.userId = userId;
929
- init.method = "PUT";
930
- const url = `${apiRoutes(config).TENANT_USER}/link`;
931
- return await request(url, init, config);
932
- }
933
-
934
- // src/api/routes/tenants/[tenantId]/users/[userId]/index.ts
935
- var key13 = "TENANT_USER";
936
- async function route16(request2, config) {
937
- const { info } = Logger(
938
- { ...config, debug: config.debug },
939
- `[ROUTES][${key13}]`
940
- );
941
- const session = await auth(request2, config);
942
- if (!session) {
943
- info("401");
944
- return new Response(null, { status: 401 });
945
- }
946
- const yurl = new URL(request2.url);
947
- const [, userId] = yurl.pathname.split("/").reverse();
948
- if (!userId) {
949
- info("No tenant id found in path");
950
- return new Response(null, { status: 404 });
951
- }
952
- switch (request2.method) {
953
- case "PUT":
954
- return await PUT4(config, { request: request2 });
955
- case "DELETE":
956
- return await DELETE3(config, { request: request2 });
957
- default:
958
- return new Response("method not allowed", { status: 405 });
959
- }
960
- }
961
- function matches16(configRoutes, request2) {
962
- const url = new URL(request2.url);
963
- const [, userId, possibleTenantId, tenantId] = url.pathname.split("/").reverse();
964
- let route17 = configRoutes[key13].replace("{tenantId}", tenantId).replace("{userId}", userId);
965
- if (userId === "users") {
966
- route17 = configRoutes[key13].replace("{tenantId}", possibleTenantId);
967
- }
968
- return urlMatches(request2.url, route17);
969
- }
970
-
971
- // src/api/handlers/DELETE.ts
972
- function DELETER(configRoutes, config) {
973
- const { info, warn } = Logger(config, "[DELETE MATCHER]");
974
- return async function DELETE4(req) {
975
- if (matches16(configRoutes, req)) {
976
- info("matches tenant user");
977
- return route16(req, config);
978
- }
979
- if (matches3(configRoutes, req)) {
980
- info("matches tenant users");
981
- return route3(req, config);
982
- }
983
- if (matches4(configRoutes, req)) {
984
- info("matches tenants");
985
- return route4(req, config);
986
- }
987
- if (matches(configRoutes, req)) {
988
- info("matches me");
989
- return route(req, config);
990
- }
991
- warn("No DELETE routes matched");
992
- return new Response(null, { status: 404 });
993
- };
994
- }
995
-
996
- // src/api/handlers/PUT.ts
997
- function PUTER(configRoutes, config) {
998
- const { info, warn } = Logger(config, "[PUT MATCHER]");
999
- return async function PUT5(req) {
1000
- if (matches16(configRoutes, req)) {
1001
- info("matches tenant user");
1002
- return route16(req, config);
1003
- }
1004
- if (matches3(configRoutes, req)) {
1005
- info("matches tenant users");
1006
- return route3(req, config);
1007
- }
1008
- if (matches2(configRoutes, req)) {
1009
- info("matches users");
1010
- return route2(req, config);
1011
- }
1012
- if (matches(configRoutes, req)) {
1013
- info("matches me");
1014
- return route(req, config);
1015
- }
1016
- if (matches4(configRoutes, req)) {
1017
- info("matches tenants");
1018
- return route4(req, config);
1019
- }
1020
- if (matches13(configRoutes, req)) {
1021
- info("matches reset password");
1022
- return route13(req, config);
1023
- }
1024
- warn("No PUT routes matched");
1025
- return new Response(null, { status: 404 });
1026
- };
1027
- }
1028
-
1029
- // src/api/handlers/index.ts
1030
- function Handlers(configRoutes, config) {
1031
- const GET6 = GETTER(configRoutes, config);
1032
- const POST5 = POSTER(configRoutes, config);
1033
- const DELETE4 = DELETER(configRoutes, config);
1034
- const PUT5 = PUTER(configRoutes, config);
1035
- return {
1036
- GET: GET6,
1037
- POST: POST5,
1038
- DELETE: DELETE4,
1039
- PUT: PUT5
1040
- };
1041
- }
1042
- var getApiUrl = (cfg) => {
1043
- const { config } = cfg;
1044
- if (config?.apiUrl != null) {
1045
- return config?.apiUrl;
1046
- }
1047
- if (stringCheck(process.env.NILEDB_API_URL)) {
1048
- return process.env.NILEDB_API_URL;
1049
- }
1050
- throw new Error(
1051
- "A connection to nile-auth is required. Set NILEDB_API_URL as an environment variable."
1052
- );
1053
- };
1054
- var getCallbackUrl = (cfg) => {
1055
- const { config } = cfg;
1056
- if (stringCheck(config?.callbackUrl)) {
1057
- return config?.callbackUrl;
1058
- }
1059
- return process.env.NILEDB_CALLBACK_URL;
1060
- };
1061
- var getSecureCookies = (cfg) => {
1062
- const { config } = cfg;
1063
- if (config?.secureCookies != null) {
1064
- return config?.secureCookies;
1065
- }
1066
- if (stringCheck(process.env.NILEDB_SECURECOOKIES)) {
1067
- return Boolean(process.env.NILEDB_SECURECOOKIES);
1068
- }
1069
- return void 0;
1070
- };
1071
- var getUsername = (cfg) => {
1072
- const { config, logger } = cfg;
1073
- const { info } = Logger(config, "[username]");
1074
- if (config?.user) {
1075
- logger && info(`${logger}[config] ${config.user}`);
1076
- return String(config?.user);
1077
- }
1078
- const user = stringCheck(process.env.NILEDB_USER);
1079
- if (user) {
1080
- logger && info(`${logger}[NILEDB_USER] ${user}`);
1081
- return user;
1082
- }
1083
- const pg = stringCheck(process.env.NILEDB_POSTGRES_URL);
1084
- if (pg) {
1085
- try {
1086
- const url = new URL(pg);
1087
- if (url.username) {
1088
- return url.username;
1089
- }
1090
- } catch (e) {
1091
- }
1092
- }
1093
- throw new Error(
1094
- "A database user is required. Set NILEDB_USER as an environment variable."
1095
- );
1096
- };
1097
- var getPassword = (cfg) => {
1098
- const { config, logger } = cfg;
1099
- const log = logProtector(logger);
1100
- const { info } = Logger(config, "[password]");
1101
- if (stringCheck(config?.password)) {
1102
- log && info(`${logger}[config] ***`);
1103
- return String(config?.password);
1104
- }
1105
- const pass = stringCheck(process.env.NILEDB_PASSWORD);
1106
- if (pass) {
1107
- logger && info(`${logger}[NILEDB_PASSWORD] ***`);
1108
- return pass;
1109
- }
1110
- const pg = stringCheck(process.env.NILEDB_POSTGRES_URL);
1111
- if (pg) {
1112
- try {
1113
- const url = new URL(pg);
1114
- if (url.password) {
1115
- return url.password;
1116
- }
1117
- } catch (e) {
1118
- }
1119
- }
1120
- throw new Error(
1121
- "A database password is required. Set NILEDB_PASSWORD as an environment variable."
1122
- );
1123
- };
1124
- var getDatabaseName = (cfg) => {
1125
- const { config, logger } = cfg;
1126
- const { info } = Logger(config, "[databaseName]");
1127
- if (stringCheck(config?.databaseName)) {
1128
- logger && info(`${logger}[config] ${config?.databaseName}`);
1129
- return String(config?.databaseName);
1130
- }
1131
- const name = stringCheck(process.env.NILEDB_NAME);
1132
- if (name) {
1133
- logger && info(`${logger}[NILEDB_NAME] ${name}`);
1134
- return name;
1135
- }
1136
- if (process.env.NILEDB_POSTGRES_URL) {
1137
- try {
1138
- const pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
1139
- return pgUrl.pathname.substring(1);
1140
- } catch (e) {
1141
- }
1142
- }
1143
- throw new Error(
1144
- "A database name is required. Set NILEDB_PASSWORD as an environment variable."
1145
- );
1146
- };
1147
- function getDbHost(cfg) {
1148
- const { config, logger } = cfg;
1149
- const { info } = Logger(config, "[db.host]");
1150
- if (stringCheck(config?.db && config.db.host)) {
1151
- logger && info(`${logger}[config] ${config?.db?.host}`);
1152
- return String(config?.db?.host);
1153
- }
1154
- if (stringCheck(process.env.NILEDB_HOST)) {
1155
- logger && info(`${logger}[NILEDB_HOST] ${process.env.NILEDB_HOST}`);
1156
- return process.env.NILEDB_HOST;
1157
- }
1158
- const pg = stringCheck(process.env.NILEDB_POSTGRES_URL);
1159
- if (pg) {
1160
- try {
1161
- const pgUrl = new URL(pg);
1162
- logger && info(`${logger}[NILEDB_POSTGRES_URL] ${pgUrl.hostname}`);
1163
- return pgUrl.hostname;
1164
- } catch (e) {
1165
- }
1166
- }
1167
- logger && info(`${logger}[default] db.thenile.dev`);
1168
- return "db.thenile.dev";
1169
- }
1170
- function getDbPort(cfg) {
1171
- const { config, logger } = cfg;
1172
- const { info } = Logger(config, "[db.port]");
1173
- if (config?.db?.port && config.db.port != null) {
1174
- logger && info(`${logger}[config] ${config?.db.port}`);
1175
- return Number(config.db?.port);
1176
- }
1177
- if (stringCheck(process.env.NILEDB_PORT)) {
1178
- logger && info(`${logger}[NILEDB_PORT] ${process.env.NILEDB_PORT}`);
1179
- return Number(process.env.NILEDB_PORT);
1180
- }
1181
- const pg = stringCheck(process.env.NILEDB_POSTGRES_URL);
1182
- if (pg) {
1183
- try {
1184
- const pgUrl = new URL(pg);
1185
- if (pgUrl.port) {
1186
- return Number(pgUrl.port);
1187
- }
1188
- } catch (e) {
1189
- }
1190
- }
1191
- logger && info(`${logger}[default] 5432`);
1192
- return 5432;
1193
- }
1194
- var logProtector = (logger) => {
1195
- return process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test" ? logger : null;
1196
- };
1197
- var stringCheck = (str) => {
1198
- if (str && str !== "") {
1199
- return str;
1200
- }
1201
- return;
1202
- };
1203
-
1204
- // src/utils/Config/index.ts
1205
- var Config = class {
1206
- routes;
1207
- handlers;
1208
- paths;
1209
- logger;
1210
- /**
1211
- * Stores the set tenant id from Server for use in sub classes
1212
- */
1213
- tenantId;
1214
- /**
1215
- * Stores the set user id from Server for use in sub classes
1216
- */
1217
- userId;
1218
- /**
1219
- * Stores the headers to be used in `fetch` calls
1220
- */
1221
- headers;
1222
- /**
1223
- * The nile-auth url
1224
- */
1225
- apiUrl;
1226
- origin;
1227
- /**
1228
- * important for separating the `origin` config value from a default in order to make requests
1229
- */
1230
- serverOrigin;
1231
- debug;
1232
- /**
1233
- * To use secure cookies or not in the fetch
1234
- */
1235
- secureCookies;
1236
- callbackUrl;
1237
- /**
1238
- * change the starting route
1239
- */
1240
- routePrefix;
1241
- db;
1242
- // api: ApiConfig;
1243
- constructor(config, logger) {
1244
- const envVarConfig = { config, logger };
1245
- this.routePrefix = config?.routePrefix ?? "/api";
1246
- this.secureCookies = getSecureCookies(envVarConfig);
1247
- this.callbackUrl = getCallbackUrl(envVarConfig);
1248
- this.debug = config?.debug;
1249
- this.origin = config?.origin;
1250
- this.serverOrigin = config?.origin ?? "http://localhost:3000";
1251
- this.apiUrl = getApiUrl(envVarConfig);
1252
- const user = getUsername(envVarConfig);
1253
- const password = getPassword(envVarConfig);
1254
- const databaseName = getDatabaseName(envVarConfig);
1255
- const { host, port, ...dbConfig } = config?.db ?? {};
1256
- const configuredHost = host ?? getDbHost(envVarConfig);
1257
- const configuredPort = port ?? getDbPort(envVarConfig);
1258
- this.db = {
1259
- user,
1260
- password,
1261
- host: configuredHost,
1262
- port: configuredPort,
1263
- ...dbConfig
1264
- };
1265
- if (databaseName) {
1266
- this.db.database = databaseName;
1267
- }
1268
- if (config?.headers) {
1269
- this.headers = config?.headers;
1270
- } else {
1271
- this.headers = new Headers();
1272
- }
1273
- this.routes = {
1274
- ...appRoutes(config?.routePrefix),
1275
- ...config?.routes
1276
- };
1277
- this.handlers = Handlers(this.routes, this);
1278
- this.paths = {
1279
- get: [
1280
- this.routes.ME,
1281
- this.routes.TENANT_USERS,
1282
- this.routes.TENANTS,
1283
- this.routes.TENANT,
1284
- this.routes.SESSION,
1285
- this.routes.SIGNIN,
1286
- this.routes.PROVIDERS,
1287
- this.routes.CSRF,
1288
- this.routes.PASSWORD_RESET,
1289
- this.routes.CALLBACK,
1290
- this.routes.SIGNOUT,
1291
- this.routes.VERIFY_REQUEST,
1292
- this.routes.ERROR
1293
- ],
1294
- post: [
1295
- this.routes.TENANT_USERS,
1296
- this.routes.SIGNUP,
1297
- this.routes.USERS,
1298
- this.routes.TENANTS,
1299
- this.routes.SESSION,
1300
- `${this.routes.SIGNIN}/{provider}`,
1301
- this.routes.PASSWORD_RESET,
1302
- this.routes.PROVIDERS,
1303
- this.routes.CSRF,
1304
- `${this.routes.CALLBACK}/{provider}`,
1305
- this.routes.SIGNOUT
1306
- ],
1307
- put: [
1308
- this.routes.TENANT_USERS,
1309
- this.routes.USERS,
1310
- this.routes.TENANT,
1311
- this.routes.PASSWORD_RESET
1312
- ],
1313
- delete: [this.routes.TENANT_USER, this.routes.TENANT]
1314
- };
1315
- this.tenantId = config?.tenantId;
1316
- this.userId = config?.userId;
1317
- this.logger = config?.logger;
1318
- }
1319
- };
1320
-
1321
- // src/lib/express.ts
1322
- function cleaner(val) {
1323
- return val.replaceAll(/\{([^}]+)\}/g, ":$1");
1324
- }
1325
- function expressPaths(nile) {
1326
- const nilePaths = nile.getPaths();
1327
- const paths = {
1328
- get: nilePaths.get.map(cleaner),
1329
- post: nilePaths.post.map(cleaner),
1330
- put: nilePaths.put.map(cleaner),
1331
- delete: nilePaths.delete.map(cleaner)
1332
- };
1333
- return {
1334
- paths
1335
- };
1336
- }
1337
- async function NileExpressHandler(nile, config) {
1338
- const { error } = Logger(
1339
- config ? new Config(config) : void 0,
1340
- "nile-express"
1341
- );
1342
- async function handler(req, res) {
1343
- const headers = new Headers();
1344
- if (!req || typeof req !== "object") {
1345
- return null;
1346
- }
1347
- if (!("url" in req) || typeof req?.url !== "string") {
1348
- error("A url is necessary for the nile express handler");
1349
- return null;
1350
- }
1351
- const method = "method" in req && typeof req.method === "string" ? req.method : "GET";
1352
- if ("headers" in req && typeof req.headers === "object" && req.headers && "cookie" in req.headers && typeof req.headers.cookie === "string") {
1353
- headers.set("cookie", req.headers.cookie);
1354
- }
1355
- const _init = { method, ...config?.init };
1356
- if ("body" in req) {
1357
- if (method === "POST" || method === "PUT") {
1358
- headers.set("content-type", "application/json");
1359
- _init.body = JSON.stringify(req.body);
1360
- }
1361
- }
1362
- _init.headers = headers;
1363
- const reqUrl = req.protocol + "://" + req.get("host") + req.originalUrl;
1364
- try {
1365
- new URL(reqUrl);
1366
- } catch (e) {
1367
- error("Invalid URL", {
1368
- url: reqUrl,
1369
- error: e
1370
- });
1371
- return null;
1372
- }
1373
- const proxyRequest = new Request(reqUrl, _init);
1374
- let response;
1375
- try {
1376
- response = await nile.handlers[method](proxyRequest);
1377
- } catch (e) {
1378
- error(e);
1379
- }
1380
- let body;
1381
- if (response instanceof Response) {
1382
- try {
1383
- const tryJson = await response.clone();
1384
- body = await tryJson.json();
1385
- } catch (e) {
1386
- body = await response.text();
1387
- }
1388
- const newHeaders = {};
1389
- response.headers.forEach((value, key14) => {
1390
- if (!["content-length", "transfer-encoding"].includes(key14.toLowerCase())) {
1391
- if (newHeaders[key14]) {
1392
- const prev = newHeaders[key14];
1393
- if (Array.isArray(prev)) {
1394
- newHeaders[key14] = [...prev, value];
1395
- } else {
1396
- newHeaders[key14] = [prev, value];
1397
- }
1398
- } else {
1399
- newHeaders[key14] = value;
1400
- }
1401
- }
1402
- });
1403
- if (config?.muteResponse !== true) {
1404
- if (res) {
1405
- res.status(response.status).set(newHeaders);
1406
- if (typeof body === "string") {
1407
- res.send(body);
1408
- } else {
1409
- res.json(body ?? {});
1410
- }
1411
- }
1412
- return;
1413
- }
1414
- return {
1415
- body,
1416
- status: response.status,
1417
- headers: newHeaders,
1418
- response
1419
- };
1420
- } else {
1421
- error("Bad response", { response });
1422
- return;
1423
- }
1424
- }
1425
- const { paths } = expressPaths(nile);
1426
- return { handler, paths };
1427
- }
1428
-
1429
- exports.NileExpressHandler = NileExpressHandler;
1430
- exports.cleaner = cleaner;
1431
- exports.expressPaths = expressPaths;
1432
- //# sourceMappingURL=express.js.map
1433
- //# sourceMappingURL=express.js.map