frontend-hamroun 1.2.13 → 1.2.14
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/backend/auth.js +3 -4
- package/dist/frontend-hamroun.es.js +232 -234
- package/dist/frontend-hamroun.umd.js +9 -9
- package/package.json +1 -1
- package/src/backend/auth.ts +4 -4
package/dist/backend/auth.js
CHANGED
@@ -1,7 +1,6 @@
|
|
1
|
-
|
2
|
-
|
3
|
-
const
|
4
|
-
import crypto from 'crypto';
|
1
|
+
const jwt = require('jsonwebtoken');
|
2
|
+
const bcrypt = require('bcrypt');
|
3
|
+
const crypto = require('crypto');
|
5
4
|
/**
|
6
5
|
* Authentication service
|
7
6
|
*/
|
@@ -1,18 +1,16 @@
|
|
1
|
-
import O, { Router as
|
1
|
+
import O, { Router as me } from "express";
|
2
2
|
import de from "path";
|
3
|
-
import
|
4
|
-
import
|
5
|
-
import
|
3
|
+
import Ne from "compression";
|
4
|
+
import Oe from "helmet";
|
5
|
+
import De from "morgan";
|
6
6
|
import j from "mongoose";
|
7
|
-
import
|
8
|
-
import
|
9
|
-
|
10
|
-
|
11
|
-
const he = globalThis || void 0 || self;
|
12
|
-
function Le(r) {
|
7
|
+
import Pe from "fs";
|
8
|
+
import "bcrypt";
|
9
|
+
const fe = globalThis || void 0 || self;
|
10
|
+
function Me(r) {
|
13
11
|
return r && r.__esModule && Object.prototype.hasOwnProperty.call(r, "default") ? r.default : r;
|
14
12
|
}
|
15
|
-
var
|
13
|
+
var ye = { exports: {} }, m = ye.exports = {}, k, v;
|
16
14
|
function re() {
|
17
15
|
throw new Error("setTimeout has not been defined");
|
18
16
|
}
|
@@ -31,7 +29,7 @@ function se() {
|
|
31
29
|
v = se;
|
32
30
|
}
|
33
31
|
})();
|
34
|
-
function
|
32
|
+
function ge(r) {
|
35
33
|
if (k === setTimeout)
|
36
34
|
return setTimeout(r, 0);
|
37
35
|
if ((k === re || !k) && setTimeout)
|
@@ -46,7 +44,7 @@ function we(r) {
|
|
46
44
|
}
|
47
45
|
}
|
48
46
|
}
|
49
|
-
function
|
47
|
+
function Fe(r) {
|
50
48
|
if (v === clearTimeout)
|
51
49
|
return clearTimeout(r);
|
52
50
|
if ((v === se || !v) && clearTimeout)
|
@@ -62,19 +60,19 @@ function Ve(r) {
|
|
62
60
|
}
|
63
61
|
}
|
64
62
|
var x = [], P = !1, _, B = -1;
|
65
|
-
function
|
66
|
-
!P || !_ || (P = !1, _.length ? x = _.concat(x) : B = -1, x.length &&
|
63
|
+
function Le() {
|
64
|
+
!P || !_ || (P = !1, _.length ? x = _.concat(x) : B = -1, x.length && we());
|
67
65
|
}
|
68
|
-
function
|
66
|
+
function we() {
|
69
67
|
if (!P) {
|
70
|
-
var r =
|
68
|
+
var r = ge(Le);
|
71
69
|
P = !0;
|
72
70
|
for (var t = x.length; t; ) {
|
73
71
|
for (_ = x, x = []; ++B < t; )
|
74
72
|
_ && _[B].run();
|
75
73
|
B = -1, t = x.length;
|
76
74
|
}
|
77
|
-
_ = null, P = !1,
|
75
|
+
_ = null, P = !1, Fe(r);
|
78
76
|
}
|
79
77
|
}
|
80
78
|
m.nextTick = function(r) {
|
@@ -82,12 +80,12 @@ m.nextTick = function(r) {
|
|
82
80
|
if (arguments.length > 1)
|
83
81
|
for (var e = 1; e < arguments.length; e++)
|
84
82
|
t[e - 1] = arguments[e];
|
85
|
-
x.push(new
|
83
|
+
x.push(new Ee(r, t)), x.length === 1 && !P && ge(we);
|
86
84
|
};
|
87
|
-
function
|
85
|
+
function Ee(r, t) {
|
88
86
|
this.fun = r, this.array = t;
|
89
87
|
}
|
90
|
-
|
88
|
+
Ee.prototype.run = function() {
|
91
89
|
this.fun.apply(null, this.array);
|
92
90
|
};
|
93
91
|
m.title = "browser";
|
@@ -122,8 +120,8 @@ m.chdir = function(r) {
|
|
122
120
|
m.umask = function() {
|
123
121
|
return 0;
|
124
122
|
};
|
125
|
-
var
|
126
|
-
const w = /* @__PURE__ */
|
123
|
+
var Ve = ye.exports;
|
124
|
+
const w = /* @__PURE__ */ Me(Ve), $ = typeof window < "u" ? window : typeof fe < "u" ? fe : {};
|
127
125
|
function J(r, t, e) {
|
128
126
|
return {
|
129
127
|
type: r,
|
@@ -131,7 +129,7 @@ function J(r, t, e) {
|
|
131
129
|
key: e
|
132
130
|
};
|
133
131
|
}
|
134
|
-
function
|
132
|
+
function be(r, t, e) {
|
135
133
|
return J(r, t, e);
|
136
134
|
}
|
137
135
|
function ne(r) {
|
@@ -154,10 +152,10 @@ function ne(r) {
|
|
154
152
|
renderTime: 0
|
155
153
|
}, typeof afterAll == "function" && afterAll(() => {
|
156
154
|
try {
|
157
|
-
const
|
158
|
-
|
159
|
-
} catch (
|
160
|
-
console.error("Failed to write stats file:",
|
155
|
+
const c = require("fs"), d = require("path").resolve(w.cwd(), "jsx-runtime-stats.json");
|
156
|
+
c.writeFileSync(d, JSON.stringify($.__renderStats, null, 2)), console.log(`JSX runtime stats written to ${d}`);
|
157
|
+
} catch (c) {
|
158
|
+
console.error("Failed to write stats file:", c);
|
161
159
|
}
|
162
160
|
})), o instanceof Text ? $.__renderStats.textNodesCreated++ : $.__renderStats.elementsCreated++), t.appendChild(o);
|
163
161
|
}
|
@@ -170,12 +168,12 @@ function ne(r) {
|
|
170
168
|
}) : t.setAttribute(e, s);
|
171
169
|
}), t;
|
172
170
|
}
|
173
|
-
const
|
174
|
-
typeof window < "u" && (window.jsx = J, window.jsxs =
|
175
|
-
const
|
171
|
+
const Te = Symbol("Fragment"), ke = J;
|
172
|
+
typeof window < "u" && (window.jsx = J, window.jsxs = be, window.jsxDEV = ke, window.Fragment = Te);
|
173
|
+
const Be = typeof window < "u" && typeof document < "u";
|
176
174
|
async function C(r) {
|
177
175
|
var t;
|
178
|
-
if (console.log("Creating element from:", r), !
|
176
|
+
if (console.log("Creating element from:", r), !Be) {
|
179
177
|
if (r == null)
|
180
178
|
return { nodeType: 3, textContent: "" };
|
181
179
|
if (typeof r == "boolean")
|
@@ -205,25 +203,25 @@ async function C(r) {
|
|
205
203
|
attributes: {},
|
206
204
|
style: {},
|
207
205
|
childNodes: [],
|
208
|
-
setAttribute: function(o,
|
209
|
-
this.attributes[o] =
|
206
|
+
setAttribute: function(o, c) {
|
207
|
+
this.attributes[o] = c;
|
210
208
|
},
|
211
209
|
appendChild: function(o) {
|
212
210
|
this.childNodes.push(o);
|
213
211
|
}
|
214
212
|
};
|
215
|
-
for (const [o,
|
213
|
+
for (const [o, c] of Object.entries(s || {}))
|
216
214
|
if (o !== "children")
|
217
|
-
if (o.startsWith("on") && typeof
|
218
|
-
const
|
219
|
-
n.__events || (n.__events = {}), n.__events[
|
220
|
-
} else o === "style" && typeof
|
215
|
+
if (o.startsWith("on") && typeof c == "function") {
|
216
|
+
const a = o.toLowerCase().slice(2);
|
217
|
+
n.__events || (n.__events = {}), n.__events[a] = c;
|
218
|
+
} else o === "style" && typeof c == "object" ? Object.assign(n.style, c) : o === "className" ? n.setAttribute("class", String(c)) : o !== "key" && o !== "ref" && n.setAttribute(o, String(c));
|
221
219
|
const i = s == null ? void 0 : s.children;
|
222
220
|
if (i != null) {
|
223
221
|
const o = Array.isArray(i) ? i.flat() : [i];
|
224
|
-
for (const
|
225
|
-
const
|
226
|
-
n.appendChild(
|
222
|
+
for (const c of o) {
|
223
|
+
const a = await C(c);
|
224
|
+
n.appendChild(a);
|
227
225
|
}
|
228
226
|
}
|
229
227
|
return n;
|
@@ -246,31 +244,31 @@ async function C(r) {
|
|
246
244
|
const { type: e, props: s } = r;
|
247
245
|
if (typeof e == "function")
|
248
246
|
try {
|
249
|
-
const o = await e(s || {}),
|
250
|
-
return
|
247
|
+
const o = await e(s || {}), c = await C(o);
|
248
|
+
return c instanceof Element && c.setAttribute("data-component-id", e.name || e.toString()), c;
|
251
249
|
} catch (o) {
|
252
250
|
return console.error("Error rendering component:", o), document.createTextNode("");
|
253
251
|
}
|
254
252
|
const n = document.createElement(e);
|
255
|
-
for (const [o,
|
253
|
+
for (const [o, c] of Object.entries(s || {}))
|
256
254
|
if (o !== "children")
|
257
|
-
if (o.startsWith("on") && typeof
|
258
|
-
const
|
259
|
-
d && n.removeEventListener(
|
260
|
-
} else o === "style" && typeof
|
255
|
+
if (o.startsWith("on") && typeof c == "function") {
|
256
|
+
const a = o.toLowerCase().slice(2), d = (t = n.__events) == null ? void 0 : t[a];
|
257
|
+
d && n.removeEventListener(a, d), n.addEventListener(a, c), n.__events || (n.__events = {}), n.__events[a] = c;
|
258
|
+
} else o === "style" && typeof c == "object" ? Object.assign(n.style, c) : o === "className" ? n.setAttribute("class", String(c)) : o !== "key" && o !== "ref" && n.setAttribute(o, String(c));
|
261
259
|
const i = s == null ? void 0 : s.children;
|
262
260
|
if (i != null) {
|
263
261
|
const o = Array.isArray(i) ? i.flat() : [i];
|
264
|
-
for (const
|
265
|
-
const
|
266
|
-
n.appendChild(
|
262
|
+
for (const c of o) {
|
263
|
+
const a = await C(c);
|
264
|
+
n.appendChild(a);
|
267
265
|
}
|
268
266
|
}
|
269
267
|
return n;
|
270
268
|
}
|
271
269
|
return document.createTextNode(String(r));
|
272
270
|
}
|
273
|
-
class
|
271
|
+
class He {
|
274
272
|
constructor(t = {}) {
|
275
273
|
this.state = {}, this.element = null, this._mounted = !1, this.props = t;
|
276
274
|
}
|
@@ -315,16 +313,16 @@ class Ue {
|
|
315
313
|
}
|
316
314
|
}
|
317
315
|
let H = !1;
|
318
|
-
const
|
319
|
-
function
|
316
|
+
const X = [];
|
317
|
+
function ae(r) {
|
320
318
|
if (H) {
|
321
|
-
|
319
|
+
X.push(r);
|
322
320
|
return;
|
323
321
|
}
|
324
322
|
H = !0;
|
325
323
|
try {
|
326
|
-
for (r();
|
327
|
-
const t =
|
324
|
+
for (r(); X.length > 0; ) {
|
325
|
+
const t = X.shift();
|
328
326
|
t == null || t();
|
329
327
|
}
|
330
328
|
} finally {
|
@@ -332,39 +330,39 @@ function ce(r) {
|
|
332
330
|
}
|
333
331
|
}
|
334
332
|
let u = 0;
|
335
|
-
const
|
336
|
-
let oe = null, ie = null,
|
337
|
-
const
|
338
|
-
function
|
339
|
-
oe = r, ie = e,
|
333
|
+
const Z = /* @__PURE__ */ new Map(), b = /* @__PURE__ */ new Map(), L = /* @__PURE__ */ new Map(), K = /* @__PURE__ */ new Map(), ee = /* @__PURE__ */ new Map();
|
334
|
+
let oe = null, ie = null, ce = null;
|
335
|
+
const ve = typeof window > "u", W = /* @__PURE__ */ new Map();
|
336
|
+
function Se(r, t, e) {
|
337
|
+
oe = r, ie = e, ce = t;
|
340
338
|
}
|
341
339
|
function U() {
|
342
340
|
return u++, b.set(u, 0), u;
|
343
341
|
}
|
344
342
|
function q() {
|
345
|
-
|
343
|
+
ve && W.delete(u), u = 0;
|
346
344
|
}
|
347
|
-
function
|
345
|
+
function xe(r) {
|
348
346
|
if (!u)
|
349
347
|
throw new Error("useState must be called within a render");
|
350
|
-
if (
|
348
|
+
if (ve) {
|
351
349
|
W.has(u) || W.set(u, /* @__PURE__ */ new Map());
|
352
350
|
const i = W.get(u), o = b.get(u) || 0;
|
353
351
|
i.has(o) || i.set(o, r);
|
354
|
-
const
|
352
|
+
const c = i.get(o), a = (d) => {
|
355
353
|
};
|
356
|
-
return b.set(u, o + 1), [
|
354
|
+
return b.set(u, o + 1), [c, a];
|
357
355
|
}
|
358
|
-
|
359
|
-
const t =
|
356
|
+
Z.has(u) || Z.set(u, []);
|
357
|
+
const t = Z.get(u), e = b.get(u);
|
360
358
|
e >= t.length && t.push(r);
|
361
359
|
const s = t[e], n = (i) => {
|
362
360
|
const o = typeof i == "function" ? i(t[e]) : i;
|
363
|
-
t[e] !== o && (t[e] = o, H ?
|
361
|
+
t[e] !== o && (t[e] = o, H ? ae(() => he(u)) : he(u));
|
364
362
|
};
|
365
363
|
return b.set(u, e + 1), [s, n];
|
366
364
|
}
|
367
|
-
function
|
365
|
+
function We(r, t) {
|
368
366
|
if (!u) throw new Error("useEffect must be called within a render");
|
369
367
|
const e = b.get(u);
|
370
368
|
L.has(u) || L.set(u, []);
|
@@ -374,22 +372,22 @@ function qe(r, t) {
|
|
374
372
|
s[e] = { cleanup: i, deps: t };
|
375
373
|
})), b.set(u, e + 1);
|
376
374
|
}
|
377
|
-
function
|
375
|
+
function Ue(r, t) {
|
378
376
|
if (!u) throw new Error("useMemo must be called within a render");
|
379
377
|
const e = b.get(u);
|
380
|
-
|
381
|
-
const s =
|
378
|
+
K.has(u) || K.set(u, []);
|
379
|
+
const s = K.get(u), n = s[e];
|
382
380
|
if (!n || t && t.some((i, o) => !Object.is(i, n.deps[o]))) {
|
383
381
|
const i = r();
|
384
382
|
return s[e] = { value: i, deps: t }, b.set(u, e + 1), i;
|
385
383
|
}
|
386
384
|
return b.set(u, e + 1), n.value;
|
387
385
|
}
|
388
|
-
function
|
386
|
+
function qe(r) {
|
389
387
|
if (!u) throw new Error("useRef must be called within a render");
|
390
388
|
const t = b.get(u);
|
391
|
-
|
392
|
-
const e =
|
389
|
+
ee.has(u) || ee.set(u, []);
|
390
|
+
const e = ee.get(u);
|
393
391
|
if (t >= e.length) {
|
394
392
|
const n = { current: r };
|
395
393
|
return e.push(n), b.set(u, t + 1), n;
|
@@ -397,22 +395,22 @@ function Je(r) {
|
|
397
395
|
const s = e[t];
|
398
396
|
return b.set(u, t + 1), s;
|
399
397
|
}
|
400
|
-
async function
|
398
|
+
async function he(r) {
|
401
399
|
try {
|
402
400
|
const t = L.get(r);
|
403
401
|
t && (t.forEach((e) => {
|
404
402
|
e.cleanup && e.cleanup();
|
405
|
-
}), L.set(r, [])), oe && ie &&
|
403
|
+
}), L.set(r, [])), oe && ie && ce && await oe(ce, ie);
|
406
404
|
} catch (t) {
|
407
405
|
console.error("Error during rerender:", t);
|
408
406
|
}
|
409
407
|
}
|
410
|
-
function
|
411
|
-
const [r, t] =
|
408
|
+
function Ge() {
|
409
|
+
const [r, t] = xe(null);
|
412
410
|
return [r, () => t(null)];
|
413
411
|
}
|
414
412
|
let G = !1;
|
415
|
-
async function
|
413
|
+
async function Je(r, t) {
|
416
414
|
G = !0;
|
417
415
|
try {
|
418
416
|
await ue(r, t);
|
@@ -421,10 +419,10 @@ async function Ye(r, t) {
|
|
421
419
|
}
|
422
420
|
}
|
423
421
|
async function ue(r, t) {
|
424
|
-
console.log("Rendering to:", t.id || "unnamed-container"),
|
422
|
+
console.log("Rendering to:", t.id || "unnamed-container"), ae(async () => {
|
425
423
|
const e = U();
|
426
424
|
try {
|
427
|
-
|
425
|
+
Se(ue, r, t);
|
428
426
|
const s = await C(r);
|
429
427
|
G || (t.innerHTML = ""), G && t.firstChild ? console.log("Hydrating existing DOM") : t.appendChild(s);
|
430
428
|
} finally {
|
@@ -433,7 +431,7 @@ async function ue(r, t) {
|
|
433
431
|
});
|
434
432
|
}
|
435
433
|
async function D(r) {
|
436
|
-
U(),
|
434
|
+
U(), Se(() => {
|
437
435
|
}, r, null);
|
438
436
|
try {
|
439
437
|
if (r == null || typeof r == "boolean") return "";
|
@@ -460,7 +458,7 @@ async function D(r) {
|
|
460
458
|
}
|
461
459
|
let s = `<${t}`;
|
462
460
|
for (const [i, o] of Object.entries(e || {}))
|
463
|
-
i === "children" || i === "key" || (i === "className" ? s += ` class="${V(String(o))}"` : i === "style" && typeof o == "object" ? s += ` style="${
|
461
|
+
i === "children" || i === "key" || (i === "className" ? s += ` class="${V(String(o))}"` : i === "style" && typeof o == "object" ? s += ` style="${Qe(o || {})}"` : i.startsWith("on") || (s += ` ${i}="${V(String(o))}"`));
|
464
462
|
if ((/* @__PURE__ */ new Set([
|
465
463
|
"area",
|
466
464
|
"base",
|
@@ -493,13 +491,13 @@ async function D(r) {
|
|
493
491
|
function V(r) {
|
494
492
|
return r.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
495
493
|
}
|
496
|
-
function
|
497
|
-
return Object.entries(r).map(([t, e]) => `${
|
494
|
+
function Qe(r) {
|
495
|
+
return Object.entries(r).map(([t, e]) => `${Ye(t)}:${e}`).join(";");
|
498
496
|
}
|
499
|
-
function
|
497
|
+
function Ye(r) {
|
500
498
|
return r.replace(/[A-Z]/g, (t) => "-" + t.toLowerCase());
|
501
499
|
}
|
502
|
-
function
|
500
|
+
function ze(r) {
|
503
501
|
const t = {
|
504
502
|
_currentValue: r,
|
505
503
|
Provider: function({ value: s, children: n }) {
|
@@ -511,10 +509,10 @@ function Ze(r) {
|
|
511
509
|
};
|
512
510
|
return t;
|
513
511
|
}
|
514
|
-
function
|
512
|
+
function Xe(r) {
|
515
513
|
return r._currentValue;
|
516
514
|
}
|
517
|
-
class
|
515
|
+
class Ae {
|
518
516
|
// Renamed from isConnected to _connected
|
519
517
|
constructor(t) {
|
520
518
|
this.connection = null, this._connected = !1, this.options = {
|
@@ -576,29 +574,29 @@ class Ce {
|
|
576
574
|
return this.connection;
|
577
575
|
}
|
578
576
|
}
|
579
|
-
function
|
577
|
+
function Ze(r = {}) {
|
580
578
|
const t = O(), {
|
581
579
|
port: e = 3e3,
|
582
580
|
staticDir: s = "public",
|
583
581
|
enableCors: n = !0,
|
584
582
|
apiPrefix: i = "/api",
|
585
583
|
ssrEnabled: o = !0,
|
586
|
-
middlewares:
|
587
|
-
enableCompression:
|
584
|
+
middlewares: c = [],
|
585
|
+
enableCompression: a = !0,
|
588
586
|
enableHelmet: d = !0,
|
589
587
|
logFormat: h = "dev",
|
590
588
|
trustProxy: E = !1,
|
591
589
|
showErrorDetails: S = w.env.NODE_ENV !== "production"
|
592
590
|
} = r;
|
593
|
-
if (E && t.set("trust proxy", E), t.use(O.json()), t.use(O.urlencoded({ extended: !0 })),
|
591
|
+
if (E && t.set("trust proxy", E), t.use(O.json()), t.use(O.urlencoded({ extended: !0 })), a && t.use(Ne()), d && t.use(Oe({
|
594
592
|
contentSecurityPolicy: r.disableCSP ? !1 : void 0
|
595
|
-
})), h && t.use(
|
593
|
+
})), h && t.use(De(h)), n && t.use((l, p, f) => {
|
596
594
|
if (p.header("Access-Control-Allow-Origin", "*"), p.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"), p.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"), l.method === "OPTIONS")
|
597
595
|
return p.sendStatus(200);
|
598
596
|
f();
|
599
|
-
}),
|
597
|
+
}), c.forEach((l) => t.use(l)), s) {
|
600
598
|
const l = de.resolve(w.cwd(), s);
|
601
|
-
|
599
|
+
Pe.existsSync(l) ? (t.use(O.static(l, {
|
602
600
|
maxAge: r.staticCacheAge || "1d",
|
603
601
|
etag: !0
|
604
602
|
})), console.log(`📂 Serving static files from: ${l}`)) : console.warn(`⚠️ Static directory not found: ${l}`);
|
@@ -606,7 +604,7 @@ function et(r = {}) {
|
|
606
604
|
let y = null;
|
607
605
|
t.connectToDatabase = async (l) => {
|
608
606
|
try {
|
609
|
-
return y && y.isConnected() ? (console.log("✅ Using existing database connection"), y) : (y = new
|
607
|
+
return y && y.isConnected() ? (console.log("✅ Using existing database connection"), y) : (y = new Ae(l), await y.connect(), console.log("✅ Database connected successfully"), w.on("SIGTERM", async () => {
|
610
608
|
y && y.isConnected() && (await y.disconnect(), console.log("Database connection closed"));
|
611
609
|
}), y);
|
612
610
|
} catch (p) {
|
@@ -633,7 +631,7 @@ function et(r = {}) {
|
|
633
631
|
query: g.query,
|
634
632
|
user: g.user,
|
635
633
|
...f.props
|
636
|
-
},
|
634
|
+
}, _e = await D(p(z));
|
637
635
|
T.send(`
|
638
636
|
<!DOCTYPE html>
|
639
637
|
<html lang="${f.lang || "en"}">
|
@@ -641,7 +639,7 @@ function et(r = {}) {
|
|
641
639
|
<meta charset="UTF-8">
|
642
640
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
643
641
|
<title>${f.title || "Frontend Hamroun App"}</title>
|
644
|
-
${f.meta ? f.meta.map((F) => `<meta ${Object.entries(F).map(([
|
642
|
+
${f.meta ? f.meta.map((F) => `<meta ${Object.entries(F).map(([Ie, Re]) => `${Ie}="${Re}"`).join(" ")}>`).join(`
|
645
643
|
`) : ""}
|
646
644
|
${f.head || ""}
|
647
645
|
${f.styles ? `<style>${f.styles}</style>` : ""}
|
@@ -649,7 +647,7 @@ function et(r = {}) {
|
|
649
647
|
`) : ""}
|
650
648
|
</head>
|
651
649
|
<body ${f.bodyAttributes || ""}>
|
652
|
-
<div id="${f.rootId || "root"}">${
|
650
|
+
<div id="${f.rootId || "root"}">${_e}</div>
|
653
651
|
<script>
|
654
652
|
window.__INITIAL_DATA__ = ${JSON.stringify(f.initialData || {})};
|
655
653
|
<\/script>
|
@@ -728,8 +726,8 @@ ${Object.keys(Q).map((g) => ` ${g}`).join(`
|
|
728
726
|
return w.on("SIGTERM", () => f("SIGTERM")), w.on("SIGINT", () => f("SIGINT")), p;
|
729
727
|
}, t;
|
730
728
|
}
|
731
|
-
const
|
732
|
-
class
|
729
|
+
const te = require("jsonwebtoken"), pe = require("bcrypt"), Ke = require("crypto");
|
730
|
+
class et {
|
733
731
|
constructor(t) {
|
734
732
|
if (this.loginAttempts = /* @__PURE__ */ new Map(), this.login = async (e, s) => {
|
735
733
|
try {
|
@@ -755,8 +753,8 @@ class tt {
|
|
755
753
|
});
|
756
754
|
return;
|
757
755
|
}
|
758
|
-
const
|
759
|
-
if (!
|
756
|
+
const c = await this.options.findUser(n);
|
757
|
+
if (!c) {
|
760
758
|
s.status(401).json({
|
761
759
|
success: !1,
|
762
760
|
message: "Invalid credentials"
|
@@ -765,7 +763,7 @@ class tt {
|
|
765
763
|
}
|
766
764
|
if (!await this.options.verifyPassword(
|
767
765
|
i,
|
768
|
-
|
766
|
+
c.password
|
769
767
|
)) {
|
770
768
|
s.status(401).json({
|
771
769
|
success: !1,
|
@@ -773,17 +771,17 @@ class tt {
|
|
773
771
|
});
|
774
772
|
return;
|
775
773
|
}
|
776
|
-
const d = { ...
|
774
|
+
const d = { ...c };
|
777
775
|
delete d.password;
|
778
776
|
const h = this.generateTokenPair({
|
779
|
-
id:
|
780
|
-
username:
|
781
|
-
role:
|
777
|
+
id: c.id || c._id,
|
778
|
+
username: c.username,
|
779
|
+
role: c.role || "user"
|
782
780
|
});
|
783
781
|
if (this.options.saveRefreshToken) {
|
784
782
|
const E = /* @__PURE__ */ new Date();
|
785
783
|
E.setSeconds(E.getSeconds() + this.getExpirationSeconds(this.options.refreshExpiration || "7d")), await this.options.saveRefreshToken(
|
786
|
-
|
784
|
+
c.id || c._id,
|
787
785
|
h.refreshToken,
|
788
786
|
E
|
789
787
|
);
|
@@ -812,31 +810,31 @@ class tt {
|
|
812
810
|
});
|
813
811
|
return;
|
814
812
|
}
|
815
|
-
const
|
816
|
-
if (this.options.verifyRefreshToken && !await this.options.verifyRefreshToken(
|
813
|
+
const c = this.verifyToken(o, "refresh");
|
814
|
+
if (this.options.verifyRefreshToken && !await this.options.verifyRefreshToken(c.id, o)) {
|
817
815
|
this.clearAuthCookies(s), s.status(401).json({
|
818
816
|
success: !1,
|
819
817
|
message: "Invalid refresh token"
|
820
818
|
});
|
821
819
|
return;
|
822
820
|
}
|
823
|
-
const
|
824
|
-
id:
|
821
|
+
const a = this.generateTokenPair({
|
822
|
+
id: c.id,
|
825
823
|
// We need to fetch the user data again for complete payload
|
826
|
-
...this.options.findUser ? await this.options.findUser(
|
824
|
+
...this.options.findUser ? await this.options.findUser(c.id) : {}
|
827
825
|
});
|
828
826
|
if (this.options.saveRefreshToken) {
|
829
827
|
const h = /* @__PURE__ */ new Date();
|
830
828
|
h.setSeconds(h.getSeconds() + this.getExpirationSeconds(this.options.refreshExpiration || "7d")), await this.options.saveRefreshToken(
|
831
|
-
|
832
|
-
|
829
|
+
c.id,
|
830
|
+
a.refreshToken,
|
833
831
|
h
|
834
832
|
);
|
835
833
|
}
|
836
|
-
(((i = e.cookies) == null ? void 0 : i.accessToken) || e.body.useCookies) && this.setAuthCookies(s,
|
834
|
+
(((i = e.cookies) == null ? void 0 : i.accessToken) || e.body.useCookies) && this.setAuthCookies(s, a), s.json({
|
837
835
|
success: !0,
|
838
836
|
message: "Token refreshed successfully",
|
839
|
-
tokens:
|
837
|
+
tokens: a
|
840
838
|
});
|
841
839
|
} catch (o) {
|
842
840
|
this.clearAuthCookies(s), s.status(401).json({
|
@@ -865,8 +863,8 @@ class tt {
|
|
865
863
|
try {
|
866
864
|
let o = (i = e.cookies) == null ? void 0 : i.accessToken;
|
867
865
|
if (!o) {
|
868
|
-
const
|
869
|
-
|
866
|
+
const a = e.headers.authorization;
|
867
|
+
a && a.startsWith("Bearer ") && (o = a.split(" ")[1]);
|
870
868
|
}
|
871
869
|
if (!o) {
|
872
870
|
s.status(401).json({
|
@@ -875,8 +873,8 @@ class tt {
|
|
875
873
|
});
|
876
874
|
return;
|
877
875
|
}
|
878
|
-
const
|
879
|
-
e.user =
|
876
|
+
const c = this.verifyToken(o, "access");
|
877
|
+
e.user = c, n();
|
880
878
|
} catch (o) {
|
881
879
|
s.status(401).json({
|
882
880
|
success: !1,
|
@@ -914,29 +912,29 @@ class tt {
|
|
914
912
|
* Hash a password using bcrypt
|
915
913
|
*/
|
916
914
|
async hashPassword(t) {
|
917
|
-
return await
|
915
|
+
return await pe.hash(t, this.options.saltRounds || 10);
|
918
916
|
}
|
919
917
|
/**
|
920
918
|
* Verify a password against a hash using bcrypt
|
921
919
|
*/
|
922
920
|
async verifyPasswordWithBcrypt(t, e) {
|
923
|
-
return await
|
921
|
+
return await pe.compare(t, e);
|
924
922
|
}
|
925
923
|
/**
|
926
924
|
* Generate a cryptographically secure random token
|
927
925
|
*/
|
928
926
|
generateSecureToken(t = 32) {
|
929
|
-
return
|
927
|
+
return Ke.randomBytes(t).toString("hex");
|
930
928
|
}
|
931
929
|
/**
|
932
930
|
* Generate token pair (access token + refresh token)
|
933
931
|
*/
|
934
932
|
generateTokenPair(t) {
|
935
|
-
const e = this.getExpirationSeconds(this.options.tokenExpiration || "15m"), s =
|
933
|
+
const e = this.getExpirationSeconds(this.options.tokenExpiration || "15m"), s = te.sign(
|
936
934
|
{ ...t, type: "access" },
|
937
935
|
this.options.jwtSecret,
|
938
936
|
{ expiresIn: this.options.tokenExpiration }
|
939
|
-
), n =
|
937
|
+
), n = te.sign(
|
940
938
|
{ id: t.id, type: "refresh" },
|
941
939
|
this.options.refreshSecret,
|
942
940
|
{ expiresIn: this.options.refreshExpiration }
|
@@ -970,7 +968,7 @@ class tt {
|
|
970
968
|
*/
|
971
969
|
verifyToken(t, e = "access") {
|
972
970
|
try {
|
973
|
-
const s = e === "access" ? this.options.jwtSecret : this.options.refreshSecret, n =
|
971
|
+
const s = e === "access" ? this.options.jwtSecret : this.options.refreshSecret, n = te.verify(t, s);
|
974
972
|
if (typeof n == "object" && n.type !== e)
|
975
973
|
throw new Error("Invalid token type");
|
976
974
|
return n;
|
@@ -1017,16 +1015,16 @@ class tt {
|
|
1017
1015
|
return s ? e > s.resetTime ? (this.loginAttempts.set(t, { count: 1, resetTime: e + 36e5 }), !0) : s.count >= 5 ? !1 : (s.count++, this.loginAttempts.set(t, s), !0) : (this.loginAttempts.set(t, { count: 1, resetTime: e + 36e5 }), !0);
|
1018
1016
|
}
|
1019
1017
|
}
|
1020
|
-
function
|
1021
|
-
return new
|
1018
|
+
function tt(r) {
|
1019
|
+
return new et(r);
|
1022
1020
|
}
|
1023
|
-
function
|
1021
|
+
function rt(r, t) {
|
1024
1022
|
const e = j.model(r, t);
|
1025
1023
|
return {
|
1026
1024
|
getAll: async (s) => {
|
1027
1025
|
try {
|
1028
|
-
const { page: n = 1, limit: i = 10, sort: o = "_id", order:
|
1029
|
-
e.find().sort(h).skip(
|
1026
|
+
const { page: n = 1, limit: i = 10, sort: o = "_id", order: c = "desc" } = s || {}, a = (n - 1) * i, d = c === "asc" ? 1 : -1, h = { [o]: d }, [E, S] = await Promise.all([
|
1027
|
+
e.find().sort(h).skip(a).limit(i).exec(),
|
1030
1028
|
e.countDocuments().exec()
|
1031
1029
|
]), y = Math.ceil(S / i);
|
1032
1030
|
return {
|
@@ -1085,7 +1083,7 @@ function st(r, t) {
|
|
1085
1083
|
},
|
1086
1084
|
find: async (s, n) => {
|
1087
1085
|
try {
|
1088
|
-
const { page: i = 1, limit: o = 10, sort:
|
1086
|
+
const { page: i = 1, limit: o = 10, sort: c = "_id", order: a = "desc" } = n || {}, d = (i - 1) * o, h = a === "asc" ? 1 : -1, E = { [c]: h }, [S, y] = await Promise.all([
|
1089
1087
|
e.find(s).sort(E).skip(d).limit(o).exec(),
|
1090
1088
|
e.countDocuments(s).exec()
|
1091
1089
|
]), I = Math.ceil(y / o);
|
@@ -1120,7 +1118,7 @@ function st(r, t) {
|
|
1120
1118
|
}
|
1121
1119
|
};
|
1122
1120
|
}
|
1123
|
-
const
|
1121
|
+
const st = {
|
1124
1122
|
String: { type: String },
|
1125
1123
|
Number: { type: Number },
|
1126
1124
|
Boolean: { type: Boolean },
|
@@ -1139,7 +1137,7 @@ const nt = {
|
|
1139
1137
|
Default: (r, t) => ({ ...r, default: t }),
|
1140
1138
|
// Array field type
|
1141
1139
|
Array: (r) => ({ type: [r] })
|
1142
|
-
},
|
1140
|
+
}, Ce = (r, { res: t }) => {
|
1143
1141
|
console.error("API Error:", r);
|
1144
1142
|
const e = r.status || r.statusCode || 500, s = r.message || "Internal server error";
|
1145
1143
|
t.status(e).json({
|
@@ -1148,91 +1146,91 @@ const nt = {
|
|
1148
1146
|
stack: w.env.NODE_ENV !== "production" ? r.stack : void 0
|
1149
1147
|
});
|
1150
1148
|
};
|
1151
|
-
function
|
1152
|
-
const e = O.Router(), { middleware: s = [], errorHandler: n =
|
1149
|
+
function nt(r, t = {}) {
|
1150
|
+
const e = O.Router(), { middleware: s = [], errorHandler: n = Ce } = t;
|
1153
1151
|
s.forEach((o) => e.use(o));
|
1154
|
-
const i = (o) => async (
|
1152
|
+
const i = (o) => async (c, a, d) => {
|
1155
1153
|
try {
|
1156
|
-
const h = { req:
|
1154
|
+
const h = { req: c, res: a, next: d, params: c.params, query: c.query, body: c.body };
|
1157
1155
|
return await o(h);
|
1158
1156
|
} catch (h) {
|
1159
|
-
const E = { req:
|
1157
|
+
const E = { req: c, res: a, next: d, params: c.params, query: c.query, body: c.body };
|
1160
1158
|
return n(h, E);
|
1161
1159
|
}
|
1162
1160
|
};
|
1163
|
-
return e.get("/", i(async ({ req: o, res:
|
1164
|
-
const
|
1165
|
-
|
1161
|
+
return e.get("/", i(async ({ req: o, res: c }) => {
|
1162
|
+
const a = o.pagination || { page: 1, limit: 10 }, d = await r.getAll(a);
|
1163
|
+
c.json({
|
1166
1164
|
success: !0,
|
1167
1165
|
...d
|
1168
1166
|
});
|
1169
|
-
})), e.get("/:id", i(async ({ params: o, res:
|
1170
|
-
const
|
1171
|
-
if (!
|
1172
|
-
|
1167
|
+
})), e.get("/:id", i(async ({ params: o, res: c }) => {
|
1168
|
+
const a = await r.getById(o.id);
|
1169
|
+
if (!a) {
|
1170
|
+
c.status(404).json({
|
1173
1171
|
success: !1,
|
1174
1172
|
error: "Item not found"
|
1175
1173
|
});
|
1176
1174
|
return;
|
1177
1175
|
}
|
1178
|
-
|
1176
|
+
c.json({
|
1179
1177
|
success: !0,
|
1180
|
-
data:
|
1178
|
+
data: a
|
1181
1179
|
});
|
1182
|
-
})), e.post("/", i(async ({ body: o, res:
|
1183
|
-
const
|
1184
|
-
|
1180
|
+
})), e.post("/", i(async ({ body: o, res: c }) => {
|
1181
|
+
const a = await r.create(o);
|
1182
|
+
c.status(201).json({
|
1185
1183
|
success: !0,
|
1186
|
-
data:
|
1184
|
+
data: a,
|
1187
1185
|
message: "Item created successfully"
|
1188
1186
|
});
|
1189
|
-
})), e.put("/:id", i(async ({ params: o, body:
|
1190
|
-
const d = await r.update(o.id,
|
1187
|
+
})), e.put("/:id", i(async ({ params: o, body: c, res: a }) => {
|
1188
|
+
const d = await r.update(o.id, c);
|
1191
1189
|
if (!d) {
|
1192
|
-
|
1190
|
+
a.status(404).json({
|
1193
1191
|
success: !1,
|
1194
1192
|
error: "Item not found"
|
1195
1193
|
});
|
1196
1194
|
return;
|
1197
1195
|
}
|
1198
|
-
|
1196
|
+
a.json({
|
1199
1197
|
success: !0,
|
1200
1198
|
data: d,
|
1201
1199
|
message: "Item updated successfully"
|
1202
1200
|
});
|
1203
|
-
})), e.delete("/:id", i(async ({ params: o, res:
|
1201
|
+
})), e.delete("/:id", i(async ({ params: o, res: c }) => {
|
1204
1202
|
if (!await r.delete(o.id)) {
|
1205
|
-
|
1203
|
+
c.status(404).json({
|
1206
1204
|
success: !1,
|
1207
1205
|
error: "Item not found"
|
1208
1206
|
});
|
1209
1207
|
return;
|
1210
1208
|
}
|
1211
|
-
|
1209
|
+
c.json({
|
1212
1210
|
success: !0,
|
1213
1211
|
message: "Item deleted successfully"
|
1214
1212
|
});
|
1215
1213
|
})), e;
|
1216
1214
|
}
|
1217
|
-
function
|
1218
|
-
const e = O.Router(), { middleware: s = [], errorHandler: n =
|
1215
|
+
function ot(r, t = {}) {
|
1216
|
+
const e = O.Router(), { middleware: s = [], errorHandler: n = Ce } = t;
|
1219
1217
|
s.forEach((o) => e.use(o));
|
1220
|
-
const i = (o) => async (
|
1218
|
+
const i = (o) => async (c, a, d) => {
|
1221
1219
|
try {
|
1222
|
-
const h = { req:
|
1223
|
-
return
|
1220
|
+
const h = { req: c, res: a, next: d, params: c.params, query: c.query, body: c.body };
|
1221
|
+
return a.headersSent ? void 0 : await o(h);
|
1224
1222
|
} catch (h) {
|
1225
|
-
if (
|
1223
|
+
if (a.headersSent) {
|
1226
1224
|
console.error("Error occurred after response was sent:", h);
|
1227
1225
|
return;
|
1228
1226
|
}
|
1229
|
-
const E = { req:
|
1227
|
+
const E = { req: c, res: a, next: d, params: c.params, query: c.query, body: c.body };
|
1230
1228
|
return n(h, E);
|
1231
1229
|
}
|
1232
1230
|
};
|
1233
|
-
return Object.entries(r).forEach(([o,
|
1234
|
-
const { method:
|
1235
|
-
e[
|
1231
|
+
return Object.entries(r).forEach(([o, c]) => {
|
1232
|
+
const { method: a, handler: d } = c;
|
1233
|
+
e[a](o, i(d));
|
1236
1234
|
}), e;
|
1237
1235
|
}
|
1238
1236
|
function le(r, t, e, s, n) {
|
@@ -1246,14 +1244,14 @@ function M(r, t, e = 400, s) {
|
|
1246
1244
|
const n = t instanceof Error ? t.message : t;
|
1247
1245
|
r.status(e).json(le(!1, void 0, void 0, n, s));
|
1248
1246
|
}
|
1249
|
-
function
|
1247
|
+
function je(r) {
|
1250
1248
|
const t = parseInt(r.query.page) || 1, e = parseInt(r.query.limit) || 10, s = r.query.sort || "createdAt", n = r.query.order === "asc" ? "asc" : "desc";
|
1251
1249
|
return { page: t, limit: e, sort: s, order: n };
|
1252
1250
|
}
|
1253
|
-
function
|
1254
|
-
r.pagination =
|
1251
|
+
function $e(r, t, e) {
|
1252
|
+
r.pagination = je(r), e();
|
1255
1253
|
}
|
1256
|
-
function
|
1254
|
+
function it(r) {
|
1257
1255
|
return (t, e, s) => {
|
1258
1256
|
try {
|
1259
1257
|
const { error: n, value: i } = r.validate(t.body);
|
@@ -1268,7 +1266,7 @@ function at(r) {
|
|
1268
1266
|
};
|
1269
1267
|
}
|
1270
1268
|
function ct(r = {}, t) {
|
1271
|
-
const e =
|
1269
|
+
const e = me();
|
1272
1270
|
return r.requireAuth && t && (e.use(t.authenticate), r.requiredRole && e.use(t.hasRole(r.requiredRole))), r.rateLimit && console.warn("Rate limiting is disabled: express-rate-limit dependency is not installed"), e;
|
1273
1271
|
}
|
1274
1272
|
function N(r) {
|
@@ -1276,9 +1274,9 @@ function N(r) {
|
|
1276
1274
|
r(t, e, s).catch(s);
|
1277
1275
|
};
|
1278
1276
|
}
|
1279
|
-
function
|
1280
|
-
const t =
|
1281
|
-
return t.get("/",
|
1277
|
+
function at(r) {
|
1278
|
+
const t = me();
|
1279
|
+
return t.get("/", $e, N(async (e, s) => {
|
1282
1280
|
const n = await r.getAll(e.pagination);
|
1283
1281
|
R(s, n);
|
1284
1282
|
})), t.get("/:id", N(async (e, s) => {
|
@@ -1300,81 +1298,81 @@ function ut(r) {
|
|
1300
1298
|
R(s, null, "Item deleted successfully");
|
1301
1299
|
})), t;
|
1302
1300
|
}
|
1303
|
-
const
|
1301
|
+
const gt = {
|
1304
1302
|
// Frontend
|
1305
1303
|
jsx: J,
|
1306
|
-
jsxs:
|
1307
|
-
jsxDEV:
|
1304
|
+
jsxs: be,
|
1305
|
+
jsxDEV: ke,
|
1308
1306
|
// Add to default export
|
1309
1307
|
createElement: ne,
|
1310
|
-
Fragment:
|
1311
|
-
Component:
|
1312
|
-
useState:
|
1313
|
-
useEffect:
|
1314
|
-
useRef:
|
1315
|
-
useMemo:
|
1316
|
-
useErrorBoundary:
|
1308
|
+
Fragment: Te,
|
1309
|
+
Component: He,
|
1310
|
+
useState: xe,
|
1311
|
+
useEffect: We,
|
1312
|
+
useRef: qe,
|
1313
|
+
useMemo: Ue,
|
1314
|
+
useErrorBoundary: Ge,
|
1317
1315
|
render: ue,
|
1318
|
-
hydrate:
|
1316
|
+
hydrate: Je,
|
1319
1317
|
renderToString: D,
|
1320
1318
|
prepareRender: U,
|
1321
1319
|
finishRender: q,
|
1322
|
-
batchUpdates:
|
1323
|
-
createContext:
|
1324
|
-
useContext:
|
1320
|
+
batchUpdates: ae,
|
1321
|
+
createContext: ze,
|
1322
|
+
useContext: Xe,
|
1325
1323
|
// Backend
|
1326
|
-
createServer:
|
1327
|
-
createAuth:
|
1328
|
-
createModel:
|
1329
|
-
FieldTypes:
|
1330
|
-
createModelRouter:
|
1331
|
-
createCustomRouter:
|
1324
|
+
createServer: Ze,
|
1325
|
+
createAuth: tt,
|
1326
|
+
createModel: rt,
|
1327
|
+
FieldTypes: st,
|
1328
|
+
createModelRouter: nt,
|
1329
|
+
createCustomRouter: ot,
|
1332
1330
|
createApiRouter: ct,
|
1333
1331
|
sendSuccess: R,
|
1334
1332
|
sendError: M,
|
1335
1333
|
apiResponse: le,
|
1336
|
-
getPaginationParams:
|
1337
|
-
paginationMiddleware:
|
1338
|
-
validateRequest:
|
1334
|
+
getPaginationParams: je,
|
1335
|
+
paginationMiddleware: $e,
|
1336
|
+
validateRequest: it,
|
1339
1337
|
asyncHandler: N,
|
1340
|
-
createRestEndpoints:
|
1341
|
-
DatabaseConnector:
|
1338
|
+
createRestEndpoints: at,
|
1339
|
+
DatabaseConnector: Ae
|
1342
1340
|
};
|
1343
1341
|
export {
|
1344
|
-
|
1345
|
-
|
1346
|
-
|
1347
|
-
|
1342
|
+
He as Component,
|
1343
|
+
Ae as DatabaseConnector,
|
1344
|
+
st as FieldTypes,
|
1345
|
+
Te as Fragment,
|
1348
1346
|
le as apiResponse,
|
1349
1347
|
N as asyncHandler,
|
1350
|
-
|
1348
|
+
ae as batchUpdates,
|
1351
1349
|
ct as createApiRouter,
|
1352
|
-
|
1353
|
-
|
1354
|
-
|
1350
|
+
tt as createAuth,
|
1351
|
+
ze as createContext,
|
1352
|
+
ot as createCustomRouter,
|
1355
1353
|
ne as createElement,
|
1356
|
-
|
1357
|
-
|
1358
|
-
|
1359
|
-
|
1360
|
-
|
1354
|
+
rt as createModel,
|
1355
|
+
nt as createModelRouter,
|
1356
|
+
at as createRestEndpoints,
|
1357
|
+
Ze as createServer,
|
1358
|
+
gt as default,
|
1361
1359
|
q as finishRender,
|
1362
|
-
|
1363
|
-
|
1360
|
+
je as getPaginationParams,
|
1361
|
+
Je as hydrate,
|
1364
1362
|
J as jsx,
|
1365
|
-
|
1366
|
-
|
1367
|
-
|
1363
|
+
ke as jsxDEV,
|
1364
|
+
be as jsxs,
|
1365
|
+
$e as paginationMiddleware,
|
1368
1366
|
U as prepareRender,
|
1369
1367
|
ue as render,
|
1370
1368
|
D as renderToString,
|
1371
1369
|
M as sendError,
|
1372
1370
|
R as sendSuccess,
|
1373
|
-
|
1374
|
-
|
1375
|
-
|
1376
|
-
|
1377
|
-
|
1378
|
-
|
1379
|
-
|
1371
|
+
Xe as useContext,
|
1372
|
+
We as useEffect,
|
1373
|
+
Ge as useErrorBoundary,
|
1374
|
+
Ue as useMemo,
|
1375
|
+
qe as useRef,
|
1376
|
+
xe as useState,
|
1377
|
+
it as validateRequest
|
1380
1378
|
};
|
@@ -1,27 +1,27 @@
|
|
1
|
-
(function(a,v){typeof exports=="object"&&typeof module<"u"?v(exports,require("express"),require("path"),require("compression"),require("helmet"),require("morgan"),require("mongoose"),require("fs"),require("jsonwebtoken"),require("bcrypt"),require("crypto")):typeof define=="function"&&define.amd?define(["exports","express","path","compression","helmet","morgan","mongoose","fs","jsonwebtoken","bcrypt","crypto"],v):(a=typeof globalThis<"u"?globalThis:a||self,v(a["frontend-hamroun"]={},a.express,a.path,a.compression,a.helmet,a.morgan,a.mongoose,a.fs,a.jwt,a.bcrypt,a.crypto))})(this,function(a,v,Ee,ze,Qe,Ye,$,Xe,K,Ze,Ke){"use strict";function et(r){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const e in r)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(r,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>r[e]})}}return t.default=r,Object.freeze(t)}const be=et(Ze),Te=globalThis||void 0||self;function tt(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var ve={exports:{}},y=ve.exports={},k,A;function ee(){throw new Error("setTimeout has not been defined")}function te(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?k=setTimeout:k=ee}catch{k=ee}try{typeof clearTimeout=="function"?A=clearTimeout:A=te}catch{A=te}})();function Se(r){if(k===setTimeout)return setTimeout(r,0);if((k===ee||!k)&&setTimeout)return k=setTimeout,setTimeout(r,0);try{return k(r,0)}catch{try{return k.call(null,r,0)}catch{return k.call(this,r,0)}}}function rt(r){if(A===clearTimeout)return clearTimeout(r);if((A===te||!A)&&clearTimeout)return A=clearTimeout,clearTimeout(r);try{return A(r)}catch{try{return A.call(null,r)}catch{return A.call(this,r)}}}var j=[],M=!1,R,W=-1;function nt(){!M||!R||(M=!1,R.length?j=R.concat(j):W=-1,j.length&&ke())}function ke(){if(!M){var r=Se(nt);M=!0;for(var t=j.length;t;){for(R=j,j=[];++W<t;)R&&R[W].run();W=-1,t=j.length}R=null,M=!1,rt(r)}}y.nextTick=function(r){var t=new Array(arguments.length-1);if(arguments.length>1)for(var e=1;e<arguments.length;e++)t[e-1]=arguments[e];j.push(new Ae(r,t)),j.length===1&&!M&&Se(ke)};function Ae(r,t){this.fun=r,this.array=t}Ae.prototype.run=function(){this.fun.apply(null,this.array)},y.title="browser",y.browser=!0,y.env={},y.argv=[],y.version="",y.versions={};function C(){}y.on=C,y.addListener=C,y.once=C,y.off=C,y.removeListener=C,y.removeAllListeners=C,y.emit=C,y.prependListener=C,y.prependOnceListener=C,y.listeners=function(r){return[]},y.binding=function(r){throw new Error("process.binding is not supported")},y.cwd=function(){return"/"},y.chdir=function(r){throw new Error("process.chdir is not supported")},y.umask=function(){return 0};var st=ve.exports;const E=tt(st),x=typeof window<"u"?window:typeof Te<"u"?Te:{};function L(r,t,e){return{type:r,props:t||{},key:e}}function re(r,t,e){return L(r,t,e)}function U(r){if(typeof r=="string"||typeof r=="number")return document.createTextNode(String(r));if(typeof r.type=="function"){const e=r.type(r.props);return U(e)}const t=document.createElement(r.type);return Object.entries(r.props||{}).forEach(([e,n])=>{if(e==="children")(Array.isArray(n)?n:[n]).forEach(i=>{if(i!=null){const o=U(i);E.env.NODE_ENV==="test"&&typeof window<"u"&&(x.__renderStats||(x.__renderStats={elementsCreated:0,textNodesCreated:0,eventsAttached:0,renderTime:0},typeof afterAll=="function"&&afterAll(()=>{try{const c=require("fs"),f=require("path").resolve(E.cwd(),"jsx-runtime-stats.json");c.writeFileSync(f,JSON.stringify(x.__renderStats,null,2)),console.log(`JSX runtime stats written to ${f}`)}catch(c){console.error("Failed to write stats file:",c)}})),o instanceof Text?x.__renderStats.textNodesCreated++:x.__renderStats.elementsCreated++),t.appendChild(o)}});else if(e.startsWith("on")){const s=e.toLowerCase().substring(2);t.addEventListener(s,n),E.env.NODE_ENV==="test"&&typeof window<"u"&&x.__renderStats&&x.__renderStats.eventsAttached++}else e==="className"?t.setAttribute("class",n):e==="style"&&typeof n=="object"?Object.entries(n).forEach(([s,i])=>{t.style[s]=String(i)}):t.setAttribute(e,n)}),t}const ne=Symbol("Fragment"),se=L;typeof window<"u"&&(window.jsx=L,window.jsxs=re,window.jsxDEV=se,window.Fragment=ne);const ot=typeof window<"u"&&typeof document<"u";async function I(r){var t;if(console.log("Creating element from:",r),!ot){if(r==null)return{nodeType:3,textContent:""};if(typeof r=="boolean")return{nodeType:3,textContent:""};if(typeof r=="number"||typeof r=="string")return{nodeType:3,textContent:String(r)};if(Array.isArray(r)){const e={nodeType:11,childNodes:[]};for(const n of r){const s=await I(n);e.childNodes.push(s)}return e}if("type"in r&&r.props!==void 0){const{type:e,props:n}=r;if(typeof e=="function")try{const o=await e(n||{});return await I(o)}catch(o){return console.error("Error rendering component:",o),{nodeType:3,textContent:""}}const s={nodeType:1,tagName:e,attributes:{},style:{},childNodes:[],setAttribute:function(o,c){this.attributes[o]=c},appendChild:function(o){this.childNodes.push(o)}};for(const[o,c]of Object.entries(n||{}))if(o!=="children")if(o.startsWith("on")&&typeof c=="function"){const u=o.toLowerCase().slice(2);s.__events||(s.__events={}),s.__events[u]=c}else o==="style"&&typeof c=="object"?Object.assign(s.style,c):o==="className"?s.setAttribute("class",String(c)):o!=="key"&&o!=="ref"&&s.setAttribute(o,String(c));const i=n==null?void 0:n.children;if(i!=null){const o=Array.isArray(i)?i.flat():[i];for(const c of o){const u=await I(c);s.appendChild(u)}}return s}return{nodeType:3,textContent:String(r)}}if(r==null||typeof r=="boolean")return document.createTextNode("");if(typeof r=="number"||typeof r=="string")return document.createTextNode(String(r));if(Array.isArray(r)){const e=document.createDocumentFragment();for(const n of r){const s=await I(n);e.appendChild(s)}return e}if("type"in r&&r.props!==void 0){const{type:e,props:n}=r;if(typeof e=="function")try{const o=await e(n||{}),c=await I(o);return c instanceof Element&&c.setAttribute("data-component-id",e.name||e.toString()),c}catch(o){return console.error("Error rendering component:",o),document.createTextNode("")}const s=document.createElement(e);for(const[o,c]of Object.entries(n||{}))if(o!=="children")if(o.startsWith("on")&&typeof c=="function"){const u=o.toLowerCase().slice(2),f=(t=s.__events)==null?void 0:t[u];f&&s.removeEventListener(u,f),s.addEventListener(u,c),s.__events||(s.__events={}),s.__events[u]=c}else o==="style"&&typeof c=="object"?Object.assign(s.style,c):o==="className"?s.setAttribute("class",String(c)):o!=="key"&&o!=="ref"&&s.setAttribute(o,String(c));const i=n==null?void 0:n.children;if(i!=null){const o=Array.isArray(i)?i.flat():[i];for(const c of o){const u=await I(c);s.appendChild(u)}}return s}return document.createTextNode(String(r))}class je{constructor(t={}){this.state={},this.element=null,this._mounted=!1,this.props=t}componentDidMount(){}async setState(t){const e={...this.state};this.state={...e,...t},console.log(`${this.constructor.name} state updated:`,{prev:e,next:this.state}),await Promise.resolve(),this._mounted?await this.update():await this.update()}_replayEvents(t,e){const n=t.__events||{};Object.entries(n).forEach(([s,i])=>{e.addEventListener(s,i)}),e.__events=n}_deepCloneWithEvents(t){const e=t.cloneNode(!1),n=t.__events||{};return e.__events=n,Object.entries(n).forEach(([s,i])=>{e.addEventListener(s,i)}),Array.from(t.childNodes).forEach(s=>{s instanceof HTMLElement?e.appendChild(this._deepCloneWithEvents(s)):e.appendChild(s.cloneNode(!0))}),e}async update(){const t=this.render();if(!t)return document.createTextNode("");const e=await I(t);if(e instanceof HTMLElement)return this._updateElement(e);const n=document.createElement("div");return n.appendChild(e),this._updateElement(n)}async _updateElement(t){const e=this._deepCloneWithEvents(t);return e.__instance=this,this.element?this.element.parentNode&&(this.element.parentNode.replaceChild(e,this.element),this.element=e):(this.element=e,this._mounted||(this._mounted=!0,queueMicrotask(()=>this.componentDidMount()))),this.element}render(){throw new Error("Component must implement render() method")}}let G=!1;const oe=[];function J(r){if(G){oe.push(r);return}G=!0;try{for(r();oe.length>0;){const t=oe.shift();t==null||t()}}finally{G=!1}}let l=0;const ie=new Map,T=new Map,V=new Map,ce=new Map,ae=new Map;let ue=null,le=null,de=null;const Ce=typeof window>"u",z=new Map;function _e(r,t,e){ue=r,le=e,de=t}function B(){return l++,T.set(l,0),l}function H(){Ce&&z.delete(l),l=0}function fe(r){if(!l)throw new Error("useState must be called within a render");if(Ce){z.has(l)||z.set(l,new Map);const i=z.get(l),o=T.get(l)||0;i.has(o)||i.set(o,r);const c=i.get(o),u=f=>{};return T.set(l,o+1),[c,u]}ie.has(l)||ie.set(l,[]);const t=ie.get(l),e=T.get(l);e>=t.length&&t.push(r);const n=t[e],s=i=>{const o=typeof i=="function"?i(t[e]):i;t[e]!==o&&(t[e]=o,G?J(()=>xe(l)):xe(l))};return T.set(l,e+1),[n,s]}function $e(r,t){if(!l)throw new Error("useEffect must be called within a render");const e=T.get(l);V.has(l)||V.set(l,[]);const n=V.get(l),s=n[e];(!s||!t||!s.deps||t.some((i,o)=>i!==s.deps[o]))&&(s!=null&&s.cleanup&&s.cleanup(),queueMicrotask(()=>{const i=r()||void 0;n[e]={cleanup:i,deps:t}})),T.set(l,e+1)}function Ie(r,t){if(!l)throw new Error("useMemo must be called within a render");const e=T.get(l);ce.has(l)||ce.set(l,[]);const n=ce.get(l),s=n[e];if(!s||t&&t.some((i,o)=>!Object.is(i,s.deps[o]))){const i=r();return n[e]={value:i,deps:t},T.set(l,e+1),i}return T.set(l,e+1),s.value}function Re(r){if(!l)throw new Error("useRef must be called within a render");const t=T.get(l);ae.has(l)||ae.set(l,[]);const e=ae.get(l);if(t>=e.length){const s={current:r};return e.push(s),T.set(l,t+1),s}const n=e[t];return T.set(l,t+1),n}async function xe(r){try{const t=V.get(r);t&&(t.forEach(e=>{e.cleanup&&e.cleanup()}),V.set(r,[])),ue&&le&&de&&await ue(de,le)}catch(t){console.error("Error during rerender:",t)}}function Oe(){const[r,t]=fe(null);return[r,()=>t(null)]}let Q=!1;async function Ne(r,t){Q=!0;try{await Y(r,t)}finally{Q=!1}}async function Y(r,t){console.log("Rendering to:",t.id||"unnamed-container"),J(async()=>{const e=B();try{_e(Y,r,t);const n=await I(r);Q||(t.innerHTML=""),Q&&t.firstChild?console.log("Hydrating existing DOM"):t.appendChild(n)}finally{H()}})}async function O(r){B(),_e(()=>{},r,null);try{if(r==null||typeof r=="boolean")return"";if(typeof r=="number"||typeof r=="string")return X(String(r));if(Array.isArray(r))return(await Promise.all(r.map(O))).join("");if("type"in r&&r.props!==void 0){const{type:t,props:e}=r;if(typeof t=="function")try{B();const i=await t(e||{}),o=await O(i);return H(),o}catch(i){return console.error("Error rendering component:",i),""}if(t===Symbol.for("react.fragment")||t.name==="Fragment"){if(e.children){const i=Array.isArray(e.children)?e.children:[e.children];return(await Promise.all(i.map(O))).join("")}return""}let n=`<${t}`;for(const[i,o]of Object.entries(e||{}))i==="children"||i==="key"||(i==="className"?n+=` class="${X(String(o))}"`:i==="style"&&typeof o=="object"?n+=` style="${it(o||{})}"`:i.startsWith("on")||(n+=` ${i}="${X(String(o))}"`));if(new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]).has(t))return n+"/>";if(n+=">",e!=null&&e.children){const i=Array.isArray(e.children)?e.children:[e.children];for(const o of i)n+=await O(o)}return n+`</${t}>`}return X(String(r))}finally{H()}}function X(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function it(r){return Object.entries(r).map(([t,e])=>`${ct(t)}:${e}`).join(";")}function ct(r){return r.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Pe(r){const t={_currentValue:r,Provider:function({value:n,children:s}){return t._currentValue=n,s},Consumer:function({children:n}){return n(t._currentValue)}};return t}function De(r){return r._currentValue}class he{constructor(t){this.connection=null,this._connected=!1,this.options={retryAttempts:3,retryDelay:1e3,connectionTimeout:1e4,autoIndex:!0,...t}}async connect(){try{if(this._connected&&this.connection)return this.connection;$.set("strictQuery",!0);let t=0;for(;t<(this.options.retryAttempts||3);)try{await $.connect(this.options.uri,{dbName:this.options.name,connectTimeoutMS:this.options.connectionTimeout,autoIndex:this.options.autoIndex,...this.options.options});break}catch(e){if(t++,t>=(this.options.retryAttempts||3))throw e;console.log(`Connection attempt ${t} failed. Retrying in ${this.options.retryDelay}ms...`),await new Promise(n=>setTimeout(n,this.options.retryDelay))}return this.connection=$.connection,this._connected=!0,console.log(`Connected to MongoDB at ${this.options.uri}/${this.options.name}`),this.connection.on("error",e=>{console.error("MongoDB connection error:",e),this._connected=!1}),this.connection.on("disconnected",()=>{console.log("MongoDB disconnected"),this._connected=!1}),this.connection}catch(t){throw console.error("Failed to connect to MongoDB:",t),t}}async disconnect(){this.connection&&(await $.disconnect(),this._connected=!1,this.connection=null,console.log("Disconnected from MongoDB"))}isConnected(){return this._connected}getConnection(){return this.connection}}function Me(r={}){const t=v(),{port:e=3e3,staticDir:n="public",enableCors:s=!0,apiPrefix:i="/api",ssrEnabled:o=!0,middlewares:c=[],enableCompression:u=!0,enableHelmet:f=!0,logFormat:p="dev",trustProxy:b=!1,showErrorDetails:_=E.env.NODE_ENV!=="production"}=r;if(b&&t.set("trust proxy",b),t.use(v.json()),t.use(v.urlencoded({extended:!0})),u&&t.use(ze()),f&&t.use(Qe({contentSecurityPolicy:r.disableCSP?!1:void 0})),p&&t.use(Ye(p)),s&&t.use((d,m,h)=>{if(m.header("Access-Control-Allow-Origin","*"),m.header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS"),m.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization"),d.method==="OPTIONS")return m.sendStatus(200);h()}),c.forEach(d=>t.use(d)),n){const d=Ee.resolve(E.cwd(),n);Xe.existsSync(d)?(t.use(v.static(d,{maxAge:r.staticCacheAge||"1d",etag:!0})),console.log(`📂 Serving static files from: ${d}`)):console.warn(`⚠️ Static directory not found: ${d}`)}let g=null;t.connectToDatabase=async d=>{try{return g&&g.isConnected()?(console.log("✅ Using existing database connection"),g):(g=new he(d),await g.connect(),console.log("✅ Database connected successfully"),E.on("SIGTERM",async()=>{g&&g.isConnected()&&(await g.disconnect(),console.log("Database connection closed"))}),g)}catch(m){throw console.error("❌ Failed to connect to database:",m),m}};const F={},me={};return t.registerApi=(d,m,h={})=>{try{const{prefix:w=i}=h,S=Ee.posix.join(w,d).replace(/\\/g,"/");t.use(S,m),F[S]={router:m,options:h},console.log(`🔌 API registered: ${S}`)}catch(w){console.error(`❌ Failed to register API at ${d}:`,w)}return t},t.registerSSR=(d,m,h={})=>o?(me[d]={component:m,options:h},t.get(d,async(w,S,ge)=>{try{if(w.query.nossr==="true")return ge();const we={req:w,res:S,params:w.params,query:w.query,user:w.user,...h.props},lt=await O(m(we));S.send(`
|
1
|
+
(function(u,v){typeof exports=="object"&&typeof module<"u"?v(exports,require("express"),require("path"),require("compression"),require("helmet"),require("morgan"),require("mongoose"),require("fs"),require("bcrypt")):typeof define=="function"&&define.amd?define(["exports","express","path","compression","helmet","morgan","mongoose","fs","bcrypt"],v):(u=typeof globalThis<"u"?globalThis:u||self,v(u["frontend-hamroun"]={},u.express,u.path,u.compression,u.helmet,u.morgan,u.mongoose,u.fs))})(this,function(u,v,Ee,Je,Qe,Ye,_,ze){"use strict";const be=globalThis||void 0||self;function Xe(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Te={exports:{}},y=Te.exports={},k,A;function K(){throw new Error("setTimeout has not been defined")}function ee(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?k=setTimeout:k=K}catch{k=K}try{typeof clearTimeout=="function"?A=clearTimeout:A=ee}catch{A=ee}})();function ve(r){if(k===setTimeout)return setTimeout(r,0);if((k===K||!k)&&setTimeout)return k=setTimeout,setTimeout(r,0);try{return k(r,0)}catch{try{return k.call(null,r,0)}catch{return k.call(this,r,0)}}}function Ze(r){if(A===clearTimeout)return clearTimeout(r);if((A===ee||!A)&&clearTimeout)return A=clearTimeout,clearTimeout(r);try{return A(r)}catch{try{return A.call(null,r)}catch{return A.call(this,r)}}}var C=[],M=!1,R,W=-1;function Ke(){!M||!R||(M=!1,R.length?C=R.concat(C):W=-1,C.length&&Se())}function Se(){if(!M){var r=ve(Ke);M=!0;for(var t=C.length;t;){for(R=C,C=[];++W<t;)R&&R[W].run();W=-1,t=C.length}R=null,M=!1,Ze(r)}}y.nextTick=function(r){var t=new Array(arguments.length-1);if(arguments.length>1)for(var e=1;e<arguments.length;e++)t[e-1]=arguments[e];C.push(new ke(r,t)),C.length===1&&!M&&ve(Se)};function ke(r,t){this.fun=r,this.array=t}ke.prototype.run=function(){this.fun.apply(null,this.array)},y.title="browser",y.browser=!0,y.env={},y.argv=[],y.version="",y.versions={};function j(){}y.on=j,y.addListener=j,y.once=j,y.off=j,y.removeListener=j,y.removeAllListeners=j,y.emit=j,y.prependListener=j,y.prependOnceListener=j,y.listeners=function(r){return[]},y.binding=function(r){throw new Error("process.binding is not supported")},y.cwd=function(){return"/"},y.chdir=function(r){throw new Error("process.chdir is not supported")},y.umask=function(){return 0};var et=Te.exports;const E=Xe(et),x=typeof window<"u"?window:typeof be<"u"?be:{};function L(r,t,e){return{type:r,props:t||{},key:e}}function te(r,t,e){return L(r,t,e)}function U(r){if(typeof r=="string"||typeof r=="number")return document.createTextNode(String(r));if(typeof r.type=="function"){const e=r.type(r.props);return U(e)}const t=document.createElement(r.type);return Object.entries(r.props||{}).forEach(([e,n])=>{if(e==="children")(Array.isArray(n)?n:[n]).forEach(i=>{if(i!=null){const o=U(i);E.env.NODE_ENV==="test"&&typeof window<"u"&&(x.__renderStats||(x.__renderStats={elementsCreated:0,textNodesCreated:0,eventsAttached:0,renderTime:0},typeof afterAll=="function"&&afterAll(()=>{try{const a=require("fs"),f=require("path").resolve(E.cwd(),"jsx-runtime-stats.json");a.writeFileSync(f,JSON.stringify(x.__renderStats,null,2)),console.log(`JSX runtime stats written to ${f}`)}catch(a){console.error("Failed to write stats file:",a)}})),o instanceof Text?x.__renderStats.textNodesCreated++:x.__renderStats.elementsCreated++),t.appendChild(o)}});else if(e.startsWith("on")){const s=e.toLowerCase().substring(2);t.addEventListener(s,n),E.env.NODE_ENV==="test"&&typeof window<"u"&&x.__renderStats&&x.__renderStats.eventsAttached++}else e==="className"?t.setAttribute("class",n):e==="style"&&typeof n=="object"?Object.entries(n).forEach(([s,i])=>{t.style[s]=String(i)}):t.setAttribute(e,n)}),t}const re=Symbol("Fragment"),ne=L;typeof window<"u"&&(window.jsx=L,window.jsxs=te,window.jsxDEV=ne,window.Fragment=re);const tt=typeof window<"u"&&typeof document<"u";async function I(r){var t;if(console.log("Creating element from:",r),!tt){if(r==null)return{nodeType:3,textContent:""};if(typeof r=="boolean")return{nodeType:3,textContent:""};if(typeof r=="number"||typeof r=="string")return{nodeType:3,textContent:String(r)};if(Array.isArray(r)){const e={nodeType:11,childNodes:[]};for(const n of r){const s=await I(n);e.childNodes.push(s)}return e}if("type"in r&&r.props!==void 0){const{type:e,props:n}=r;if(typeof e=="function")try{const o=await e(n||{});return await I(o)}catch(o){return console.error("Error rendering component:",o),{nodeType:3,textContent:""}}const s={nodeType:1,tagName:e,attributes:{},style:{},childNodes:[],setAttribute:function(o,a){this.attributes[o]=a},appendChild:function(o){this.childNodes.push(o)}};for(const[o,a]of Object.entries(n||{}))if(o!=="children")if(o.startsWith("on")&&typeof a=="function"){const c=o.toLowerCase().slice(2);s.__events||(s.__events={}),s.__events[c]=a}else o==="style"&&typeof a=="object"?Object.assign(s.style,a):o==="className"?s.setAttribute("class",String(a)):o!=="key"&&o!=="ref"&&s.setAttribute(o,String(a));const i=n==null?void 0:n.children;if(i!=null){const o=Array.isArray(i)?i.flat():[i];for(const a of o){const c=await I(a);s.appendChild(c)}}return s}return{nodeType:3,textContent:String(r)}}if(r==null||typeof r=="boolean")return document.createTextNode("");if(typeof r=="number"||typeof r=="string")return document.createTextNode(String(r));if(Array.isArray(r)){const e=document.createDocumentFragment();for(const n of r){const s=await I(n);e.appendChild(s)}return e}if("type"in r&&r.props!==void 0){const{type:e,props:n}=r;if(typeof e=="function")try{const o=await e(n||{}),a=await I(o);return a instanceof Element&&a.setAttribute("data-component-id",e.name||e.toString()),a}catch(o){return console.error("Error rendering component:",o),document.createTextNode("")}const s=document.createElement(e);for(const[o,a]of Object.entries(n||{}))if(o!=="children")if(o.startsWith("on")&&typeof a=="function"){const c=o.toLowerCase().slice(2),f=(t=s.__events)==null?void 0:t[c];f&&s.removeEventListener(c,f),s.addEventListener(c,a),s.__events||(s.__events={}),s.__events[c]=a}else o==="style"&&typeof a=="object"?Object.assign(s.style,a):o==="className"?s.setAttribute("class",String(a)):o!=="key"&&o!=="ref"&&s.setAttribute(o,String(a));const i=n==null?void 0:n.children;if(i!=null){const o=Array.isArray(i)?i.flat():[i];for(const a of o){const c=await I(a);s.appendChild(c)}}return s}return document.createTextNode(String(r))}class Ae{constructor(t={}){this.state={},this.element=null,this._mounted=!1,this.props=t}componentDidMount(){}async setState(t){const e={...this.state};this.state={...e,...t},console.log(`${this.constructor.name} state updated:`,{prev:e,next:this.state}),await Promise.resolve(),this._mounted?await this.update():await this.update()}_replayEvents(t,e){const n=t.__events||{};Object.entries(n).forEach(([s,i])=>{e.addEventListener(s,i)}),e.__events=n}_deepCloneWithEvents(t){const e=t.cloneNode(!1),n=t.__events||{};return e.__events=n,Object.entries(n).forEach(([s,i])=>{e.addEventListener(s,i)}),Array.from(t.childNodes).forEach(s=>{s instanceof HTMLElement?e.appendChild(this._deepCloneWithEvents(s)):e.appendChild(s.cloneNode(!0))}),e}async update(){const t=this.render();if(!t)return document.createTextNode("");const e=await I(t);if(e instanceof HTMLElement)return this._updateElement(e);const n=document.createElement("div");return n.appendChild(e),this._updateElement(n)}async _updateElement(t){const e=this._deepCloneWithEvents(t);return e.__instance=this,this.element?this.element.parentNode&&(this.element.parentNode.replaceChild(e,this.element),this.element=e):(this.element=e,this._mounted||(this._mounted=!0,queueMicrotask(()=>this.componentDidMount()))),this.element}render(){throw new Error("Component must implement render() method")}}let G=!1;const se=[];function J(r){if(G){se.push(r);return}G=!0;try{for(r();se.length>0;){const t=se.shift();t==null||t()}}finally{G=!1}}let l=0;const oe=new Map,T=new Map,V=new Map,ie=new Map,ae=new Map;let ce=null,ue=null,le=null;const Ce=typeof window>"u",Q=new Map;function je(r,t,e){ce=r,ue=e,le=t}function B(){return l++,T.set(l,0),l}function q(){Ce&&Q.delete(l),l=0}function de(r){if(!l)throw new Error("useState must be called within a render");if(Ce){Q.has(l)||Q.set(l,new Map);const i=Q.get(l),o=T.get(l)||0;i.has(o)||i.set(o,r);const a=i.get(o),c=f=>{};return T.set(l,o+1),[a,c]}oe.has(l)||oe.set(l,[]);const t=oe.get(l),e=T.get(l);e>=t.length&&t.push(r);const n=t[e],s=i=>{const o=typeof i=="function"?i(t[e]):i;t[e]!==o&&(t[e]=o,G?J(()=>Re(l)):Re(l))};return T.set(l,e+1),[n,s]}function $e(r,t){if(!l)throw new Error("useEffect must be called within a render");const e=T.get(l);V.has(l)||V.set(l,[]);const n=V.get(l),s=n[e];(!s||!t||!s.deps||t.some((i,o)=>i!==s.deps[o]))&&(s!=null&&s.cleanup&&s.cleanup(),queueMicrotask(()=>{const i=r()||void 0;n[e]={cleanup:i,deps:t}})),T.set(l,e+1)}function _e(r,t){if(!l)throw new Error("useMemo must be called within a render");const e=T.get(l);ie.has(l)||ie.set(l,[]);const n=ie.get(l),s=n[e];if(!s||t&&t.some((i,o)=>!Object.is(i,s.deps[o]))){const i=r();return n[e]={value:i,deps:t},T.set(l,e+1),i}return T.set(l,e+1),s.value}function Ie(r){if(!l)throw new Error("useRef must be called within a render");const t=T.get(l);ae.has(l)||ae.set(l,[]);const e=ae.get(l);if(t>=e.length){const s={current:r};return e.push(s),T.set(l,t+1),s}const n=e[t];return T.set(l,t+1),n}async function Re(r){try{const t=V.get(r);t&&(t.forEach(e=>{e.cleanup&&e.cleanup()}),V.set(r,[])),ce&&ue&&le&&await ce(le,ue)}catch(t){console.error("Error during rerender:",t)}}function xe(){const[r,t]=de(null);return[r,()=>t(null)]}let Y=!1;async function Ne(r,t){Y=!0;try{await z(r,t)}finally{Y=!1}}async function z(r,t){console.log("Rendering to:",t.id||"unnamed-container"),J(async()=>{const e=B();try{je(z,r,t);const n=await I(r);Y||(t.innerHTML=""),Y&&t.firstChild?console.log("Hydrating existing DOM"):t.appendChild(n)}finally{q()}})}async function N(r){B(),je(()=>{},r,null);try{if(r==null||typeof r=="boolean")return"";if(typeof r=="number"||typeof r=="string")return X(String(r));if(Array.isArray(r))return(await Promise.all(r.map(N))).join("");if("type"in r&&r.props!==void 0){const{type:t,props:e}=r;if(typeof t=="function")try{B();const i=await t(e||{}),o=await N(i);return q(),o}catch(i){return console.error("Error rendering component:",i),""}if(t===Symbol.for("react.fragment")||t.name==="Fragment"){if(e.children){const i=Array.isArray(e.children)?e.children:[e.children];return(await Promise.all(i.map(N))).join("")}return""}let n=`<${t}`;for(const[i,o]of Object.entries(e||{}))i==="children"||i==="key"||(i==="className"?n+=` class="${X(String(o))}"`:i==="style"&&typeof o=="object"?n+=` style="${rt(o||{})}"`:i.startsWith("on")||(n+=` ${i}="${X(String(o))}"`));if(new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]).has(t))return n+"/>";if(n+=">",e!=null&&e.children){const i=Array.isArray(e.children)?e.children:[e.children];for(const o of i)n+=await N(o)}return n+`</${t}>`}return X(String(r))}finally{q()}}function X(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function rt(r){return Object.entries(r).map(([t,e])=>`${nt(t)}:${e}`).join(";")}function nt(r){return r.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Oe(r){const t={_currentValue:r,Provider:function({value:n,children:s}){return t._currentValue=n,s},Consumer:function({children:n}){return n(t._currentValue)}};return t}function Pe(r){return r._currentValue}class fe{constructor(t){this.connection=null,this._connected=!1,this.options={retryAttempts:3,retryDelay:1e3,connectionTimeout:1e4,autoIndex:!0,...t}}async connect(){try{if(this._connected&&this.connection)return this.connection;_.set("strictQuery",!0);let t=0;for(;t<(this.options.retryAttempts||3);)try{await _.connect(this.options.uri,{dbName:this.options.name,connectTimeoutMS:this.options.connectionTimeout,autoIndex:this.options.autoIndex,...this.options.options});break}catch(e){if(t++,t>=(this.options.retryAttempts||3))throw e;console.log(`Connection attempt ${t} failed. Retrying in ${this.options.retryDelay}ms...`),await new Promise(n=>setTimeout(n,this.options.retryDelay))}return this.connection=_.connection,this._connected=!0,console.log(`Connected to MongoDB at ${this.options.uri}/${this.options.name}`),this.connection.on("error",e=>{console.error("MongoDB connection error:",e),this._connected=!1}),this.connection.on("disconnected",()=>{console.log("MongoDB disconnected"),this._connected=!1}),this.connection}catch(t){throw console.error("Failed to connect to MongoDB:",t),t}}async disconnect(){this.connection&&(await _.disconnect(),this._connected=!1,this.connection=null,console.log("Disconnected from MongoDB"))}isConnected(){return this._connected}getConnection(){return this.connection}}function De(r={}){const t=v(),{port:e=3e3,staticDir:n="public",enableCors:s=!0,apiPrefix:i="/api",ssrEnabled:o=!0,middlewares:a=[],enableCompression:c=!0,enableHelmet:f=!0,logFormat:p="dev",trustProxy:b=!1,showErrorDetails:$=E.env.NODE_ENV!=="production"}=r;if(b&&t.set("trust proxy",b),t.use(v.json()),t.use(v.urlencoded({extended:!0})),c&&t.use(Je()),f&&t.use(Qe({contentSecurityPolicy:r.disableCSP?!1:void 0})),p&&t.use(Ye(p)),s&&t.use((d,m,h)=>{if(m.header("Access-Control-Allow-Origin","*"),m.header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS"),m.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization"),d.method==="OPTIONS")return m.sendStatus(200);h()}),a.forEach(d=>t.use(d)),n){const d=Ee.resolve(E.cwd(),n);ze.existsSync(d)?(t.use(v.static(d,{maxAge:r.staticCacheAge||"1d",etag:!0})),console.log(`📂 Serving static files from: ${d}`)):console.warn(`⚠️ Static directory not found: ${d}`)}let g=null;t.connectToDatabase=async d=>{try{return g&&g.isConnected()?(console.log("✅ Using existing database connection"),g):(g=new fe(d),await g.connect(),console.log("✅ Database connected successfully"),E.on("SIGTERM",async()=>{g&&g.isConnected()&&(await g.disconnect(),console.log("Database connection closed"))}),g)}catch(m){throw console.error("❌ Failed to connect to database:",m),m}};const F={},me={};return t.registerApi=(d,m,h={})=>{try{const{prefix:w=i}=h,S=Ee.posix.join(w,d).replace(/\\/g,"/");t.use(S,m),F[S]={router:m,options:h},console.log(`🔌 API registered: ${S}`)}catch(w){console.error(`❌ Failed to register API at ${d}:`,w)}return t},t.registerSSR=(d,m,h={})=>o?(me[d]={component:m,options:h},t.get(d,async(w,S,ge)=>{try{if(w.query.nossr==="true")return ge();const we={req:w,res:S,params:w.params,query:w.query,user:w.user,...h.props},at=await N(m(we));S.send(`
|
2
2
|
<!DOCTYPE html>
|
3
3
|
<html lang="${h.lang||"en"}">
|
4
4
|
<head>
|
5
5
|
<meta charset="UTF-8">
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
7
7
|
<title>${h.title||"Frontend Hamroun App"}</title>
|
8
|
-
${h.meta?h.meta.map(
|
8
|
+
${h.meta?h.meta.map(H=>`<meta ${Object.entries(H).map(([ct,ut])=>`${ct}="${ut}"`).join(" ")}>`).join(`
|
9
9
|
`):""}
|
10
10
|
${h.head||""}
|
11
11
|
${h.styles?`<style>${h.styles}</style>`:""}
|
12
|
-
${h.styleSheets?h.styleSheets.map(
|
12
|
+
${h.styleSheets?h.styleSheets.map(H=>`<link rel="stylesheet" href="${H}">`).join(`
|
13
13
|
`):""}
|
14
14
|
</head>
|
15
15
|
<body ${h.bodyAttributes||""}>
|
16
|
-
<div id="${h.rootId||"root"}">${
|
16
|
+
<div id="${h.rootId||"root"}">${at}</div>
|
17
17
|
<script>
|
18
18
|
window.__INITIAL_DATA__ = ${JSON.stringify(h.initialData||{})};
|
19
19
|
<\/script>
|
20
|
-
${h.scripts?h.scripts.map(
|
20
|
+
${h.scripts?h.scripts.map(H=>`<script src="${H}"><\/script>`).join(`
|
21
21
|
`):""}
|
22
22
|
</body>
|
23
23
|
</html>
|
24
|
-
`)}catch(we){if(console.error("SSR Error:",we),h.fallback)return ge();S.status(500).send("Server rendering error")}}),console.log(`🖥️ SSR registered: ${d}`),t):(console.log(`⚠️ SSR disabled: skipping registration of ${d}`),t),t.use((d,m,h,w)=>{console.error("Server error:",d);const S=d.statusCode||d.status||500;m.path.startsWith(i)?h.status(S).json({success:!1,error
|
24
|
+
`)}catch(we){if(console.error("SSR Error:",we),h.fallback)return ge();S.status(500).send("Server rendering error")}}),console.log(`🖥️ SSR registered: ${d}`),t):(console.log(`⚠️ SSR disabled: skipping registration of ${d}`),t),t.use((d,m,h,w)=>{console.error("Server error:",d);const S=d.statusCode||d.status||500;m.path.startsWith(i)?h.status(S).json({success:!1,error:$?d.message:"Internal Server Error",stack:$?d.stack:void 0}):h.status(S).send(`
|
25
25
|
<!DOCTYPE html>
|
26
26
|
<html>
|
27
27
|
<head>
|
@@ -34,8 +34,8 @@
|
|
34
34
|
</head>
|
35
35
|
<body>
|
36
36
|
<h1>Error ${S}</h1>
|
37
|
-
<div class="error">${
|
38
|
-
${
|
37
|
+
<div class="error">${$?d.message:"Internal Server Error"}</div>
|
38
|
+
${$&&d.stack?`<pre class="stack">${d.stack}</pre>`:""}
|
39
39
|
</body>
|
40
40
|
</html>
|
41
41
|
`)}),t.use((d,m)=>{d.path.startsWith(i)?m.status(404).json({success:!1,error:"Not Found"}):m.status(404).send(`
|
@@ -63,4 +63,4 @@ ${Object.keys(me).length>0?`
|
|
63
63
|
🖥️ Registered SSR Routes:
|
64
64
|
${Object.keys(me).map(w=>` ${w}`).join(`
|
65
65
|
`)}`:""}
|
66
|
-
`),d&&d()}),h=async w=>{console.log(`${w} signal received: closing HTTP server and cleaning up`),m.close(async()=>{console.log("HTTP server closed"),g&&g.isConnected()&&(await g.disconnect(),console.log("Database connection closed")),E.exit(0)}),setTimeout(()=>{console.error("Could not close connections in time, forcefully shutting down"),E.exit(1)},1e4)};return E.on("SIGTERM",()=>h("SIGTERM")),E.on("SIGINT",()=>h("SIGINT")),m},t}const Fe=be.default||be;class at{constructor(t){if(this.loginAttempts=new Map,this.login=async(e,n)=>{try{const{username:s,password:i}=e.body,o=e.ip||e.connection.remoteAddress||"";if(!this.checkRateLimit(o)){n.status(429).json({success:!1,message:"Too many login attempts. Please try again later."});return}if(!s||!i){n.status(400).json({success:!1,message:"Username and password are required"});return}if(!this.options.findUser){n.status(500).json({success:!1,message:"User finder function not configured"});return}const c=await this.options.findUser(s);if(!c){n.status(401).json({success:!1,message:"Invalid credentials"});return}if(!await this.options.verifyPassword(i,c.password)){n.status(401).json({success:!1,message:"Invalid credentials"});return}const f={...c};delete f.password;const p=this.generateTokenPair({id:c.id||c._id,username:c.username,role:c.role||"user"});if(this.options.saveRefreshToken){const b=new Date;b.setSeconds(b.getSeconds()+this.getExpirationSeconds(this.options.refreshExpiration||"7d")),await this.options.saveRefreshToken(c.id||c._id,p.refreshToken,b)}e.body.useCookies&&this.setAuthCookies(n,p),n.json({success:!0,message:"Authentication successful",tokens:p,user:f})}catch(s){console.error("Authentication error:",s),n.status(500).json({success:!1,message:"Authentication failed",error:E.env.NODE_ENV!=="production"?s.message:void 0})}},this.refreshToken=async(e,n)=>{var s,i;try{const o=((s=e.cookies)==null?void 0:s.refreshToken)||e.body.refreshToken;if(!o){n.status(401).json({success:!1,message:"Refresh token required"});return}const c=this.verifyToken(o,"refresh");if(this.options.verifyRefreshToken&&!await this.options.verifyRefreshToken(c.id,o)){this.clearAuthCookies(n),n.status(401).json({success:!1,message:"Invalid refresh token"});return}const u=this.generateTokenPair({id:c.id,...this.options.findUser?await this.options.findUser(c.id):{}});if(this.options.saveRefreshToken){const p=new Date;p.setSeconds(p.getSeconds()+this.getExpirationSeconds(this.options.refreshExpiration||"7d")),await this.options.saveRefreshToken(c.id,u.refreshToken,p)}(((i=e.cookies)==null?void 0:i.accessToken)||e.body.useCookies)&&this.setAuthCookies(n,u),n.json({success:!0,message:"Token refreshed successfully",tokens:u})}catch(o){this.clearAuthCookies(n),n.status(401).json({success:!1,message:"Invalid or expired refresh token",error:E.env.NODE_ENV!=="production"?o.message:void 0})}},this.logout=async(e,n)=>{var s;try{this.clearAuthCookies(n);const i=((s=e.cookies)==null?void 0:s.refreshToken)||e.body.refreshToken;if(i&&this.options.saveRefreshToken)try{const o=this.verifyToken(i,"refresh");typeof this.options.saveRefreshToken=="function"&&await this.options.saveRefreshToken(o.id,"",new Date)}catch{}n.json({success:!0,message:"Logged out successfully"})}catch(i){console.error("Logout error:",i),n.status(500).json({success:!1,message:"Logout failed",error:i.message})}},this.authenticate=(e,n,s)=>{var i;try{let o=(i=e.cookies)==null?void 0:i.accessToken;if(!o){const u=e.headers.authorization;u&&u.startsWith("Bearer ")&&(o=u.split(" ")[1])}if(!o){n.status(401).json({success:!1,message:"Authentication required"});return}const c=this.verifyToken(o,"access");e.user=c,s()}catch(o){n.status(401).json({success:!1,message:"Invalid or expired token",error:E.env.NODE_ENV!=="production"?o.message:void 0})}},this.hasRole=e=>(n,s,i)=>{const o=n.user;if(!o){s.status(401).json({success:!1,message:"Authentication required"});return}(Array.isArray(e)?e:[e]).includes(o.role)?i():s.status(403).json({success:!1,message:"Insufficient permissions"})},this.options={tokenExpiration:"15m",refreshExpiration:"7d",saltRounds:10,secureCookies:E.env.NODE_ENV==="production",httpOnlyCookies:!0,rateLimit:!0,...t,refreshSecret:t.refreshSecret||t.jwtSecret},!t.jwtSecret)throw new Error("JWT secret is required for authentication");this.options.verifyPassword||(this.options.verifyPassword=this.verifyPasswordWithBcrypt)}async hashPassword(t){return await Fe.hash(t,this.options.saltRounds||10)}async verifyPasswordWithBcrypt(t,e){return await Fe.compare(t,e)}generateSecureToken(t=32){return Ke.randomBytes(t).toString("hex")}generateTokenPair(t){const e=this.getExpirationSeconds(this.options.tokenExpiration||"15m"),n=K.sign({...t,type:"access"},this.options.jwtSecret,{expiresIn:this.options.tokenExpiration}),s=K.sign({id:t.id,type:"refresh"},this.options.refreshSecret,{expiresIn:this.options.refreshExpiration});return{accessToken:n,refreshToken:s,expiresIn:e}}getExpirationSeconds(t){const e=t.charAt(t.length-1),n=parseInt(t.slice(0,-1));switch(e){case"s":return n;case"m":return n*60;case"h":return n*60*60;case"d":return n*60*60*24;default:return 3600}}verifyToken(t,e="access"){try{const n=e==="access"?this.options.jwtSecret:this.options.refreshSecret,s=K.verify(t,n);if(typeof s=="object"&&s.type!==e)throw new Error("Invalid token type");return s}catch{throw new Error("Invalid or expired token")}}setAuthCookies(t,e){t.cookie("accessToken",e.accessToken,{httpOnly:this.options.httpOnlyCookies,secure:this.options.secureCookies,domain:this.options.cookieDomain,sameSite:"strict",maxAge:e.expiresIn*1e3});const n=this.getExpirationSeconds(this.options.refreshExpiration||"7d");t.cookie("refreshToken",e.refreshToken,{httpOnly:!0,secure:this.options.secureCookies,domain:this.options.cookieDomain,sameSite:"strict",maxAge:n*1e3,path:"/api/auth/refresh"})}clearAuthCookies(t){t.clearCookie("accessToken"),t.clearCookie("refreshToken",{path:"/api/auth/refresh"})}checkRateLimit(t){if(!this.options.rateLimit)return!0;const e=Date.now(),n=this.loginAttempts.get(t);return n?e>n.resetTime?(this.loginAttempts.set(t,{count:1,resetTime:e+36e5}),!0):n.count>=5?!1:(n.count++,this.loginAttempts.set(t,n),!0):(this.loginAttempts.set(t,{count:1,resetTime:e+36e5}),!0)}}function Le(r){return new at(r)}function Ve(r,t){const e=$.model(r,t);return{getAll:async n=>{try{const{page:s=1,limit:i=10,sort:o="_id",order:c="desc"}=n||{},u=(s-1)*i,f=c==="asc"?1:-1,p={[o]:f},[b,_]=await Promise.all([e.find().sort(p).skip(u).limit(i).exec(),e.countDocuments().exec()]),g=Math.ceil(_/i);return{data:b,pagination:{total:_,totalPages:g,currentPage:s,limit:i,hasNextPage:s<g,hasPrevPage:s>1}}}catch(s){throw console.error(`Error in ${r}.getAll:`,s),new Error(`Failed to retrieve ${r} records: ${s.message}`)}},getById:async n=>{try{return $.isValidObjectId(n)?await e.findById(n).exec():null}catch(s){throw console.error(`Error in ${r}.getById:`,s),new Error(`Failed to retrieve ${r} by ID: ${s.message}`)}},create:async n=>{try{return await new e(n).save()}catch(s){throw console.error(`Error in ${r}.create:`,s),new Error(`Failed to create ${r}: ${s.message}`)}},createMany:async n=>{try{return await e.insertMany(n)}catch(s){throw console.error(`Error in ${r}.createMany:`,s),new Error(`Failed to create multiple ${r} records: ${s.message}`)}},update:async(n,s)=>{try{return $.isValidObjectId(n)?await e.findByIdAndUpdate(n,{$set:s},{new:!0,runValidators:!0}).exec():null}catch(i){throw console.error(`Error in ${r}.update:`,i),new Error(`Failed to update ${r}: ${i.message}`)}},delete:async n=>{try{return $.isValidObjectId(n)?await e.findByIdAndDelete(n).exec()!==null:!1}catch(s){throw console.error(`Error in ${r}.delete:`,s),new Error(`Failed to delete ${r}: ${s.message}`)}},find:async(n,s)=>{try{const{page:i=1,limit:o=10,sort:c="_id",order:u="desc"}=s||{},f=(i-1)*o,p=u==="asc"?1:-1,b={[c]:p},[_,g]=await Promise.all([e.find(n).sort(b).skip(f).limit(o).exec(),e.countDocuments(n).exec()]),F=Math.ceil(g/o);return{data:_,pagination:{total:g,totalPages:F,currentPage:i,limit:o,hasNextPage:i<F,hasPrevPage:i>1}}}catch(i){throw console.error(`Error in ${r}.find:`,i),new Error(`Failed to find ${r} records: ${i.message}`)}},count:async n=>{try{return await e.countDocuments(n||{}).exec()}catch(s){throw console.error(`Error in ${r}.count:`,s),new Error(`Failed to count ${r} records: ${s.message}`)}},findOne:async n=>{try{return await e.findOne(n).exec()}catch(s){throw console.error(`Error in ${r}.findOne:`,s),new Error(`Failed to find ${r} record: ${s.message}`)}}}}const Be={String:{type:String},Number:{type:Number},Boolean:{type:Boolean},Date:{type:Date},ObjectId:{type:String},Required:r=>({...r,required:!0}),Unique:r=>({...r,unique:!0}),Ref:r=>({type:String,ref:r}),Enum:r=>({type:String,enum:r}),Default:(r,t)=>({...r,default:t}),Array:r=>({type:[r]})},He=(r,{res:t})=>{console.error("API Error:",r);const e=r.status||r.statusCode||500,n=r.message||"Internal server error";t.status(e).json({success:!1,error:n,stack:E.env.NODE_ENV!=="production"?r.stack:void 0})};function qe(r,t={}){const e=v.Router(),{middleware:n=[],errorHandler:s=He}=t;n.forEach(o=>e.use(o));const i=o=>async(c,u,f)=>{try{const p={req:c,res:u,next:f,params:c.params,query:c.query,body:c.body};return await o(p)}catch(p){const b={req:c,res:u,next:f,params:c.params,query:c.query,body:c.body};return s(p,b)}};return e.get("/",i(async({req:o,res:c})=>{const u=o.pagination||{page:1,limit:10},f=await r.getAll(u);c.json({success:!0,...f})})),e.get("/:id",i(async({params:o,res:c})=>{const u=await r.getById(o.id);if(!u){c.status(404).json({success:!1,error:"Item not found"});return}c.json({success:!0,data:u})})),e.post("/",i(async({body:o,res:c})=>{const u=await r.create(o);c.status(201).json({success:!0,data:u,message:"Item created successfully"})})),e.put("/:id",i(async({params:o,body:c,res:u})=>{const f=await r.update(o.id,c);if(!f){u.status(404).json({success:!1,error:"Item not found"});return}u.json({success:!0,data:f,message:"Item updated successfully"})})),e.delete("/:id",i(async({params:o,res:c})=>{if(!await r.delete(o.id)){c.status(404).json({success:!1,error:"Item not found"});return}c.json({success:!0,message:"Item deleted successfully"})})),e}function We(r,t={}){const e=v.Router(),{middleware:n=[],errorHandler:s=He}=t;n.forEach(o=>e.use(o));const i=o=>async(c,u,f)=>{try{const p={req:c,res:u,next:f,params:c.params,query:c.query,body:c.body};return u.headersSent?void 0:await o(p)}catch(p){if(u.headersSent){console.error("Error occurred after response was sent:",p);return}const b={req:c,res:u,next:f,params:c.params,query:c.query,body:c.body};return s(p,b)}};return Object.entries(r).forEach(([o,c])=>{const{method:u,handler:f}=c;e[u](o,i(f))}),e}function Z(r,t,e,n,s){const i={success:r};return t!==void 0&&(i.data=t),e&&(i.message=e),n&&(i.error=n),s&&(i.meta=s),i}function N(r,t,e,n=200,s){r.status(n).json(Z(!0,t,e,void 0,s))}function P(r,t,e=400,n){const s=t instanceof Error?t.message:t;r.status(e).json(Z(!1,void 0,void 0,s,n))}function pe(r){const t=parseInt(r.query.page)||1,e=parseInt(r.query.limit)||10,n=r.query.sort||"createdAt",s=r.query.order==="asc"?"asc":"desc";return{page:t,limit:e,sort:n,order:s}}function ye(r,t,e){r.pagination=pe(r),e()}function Ue(r){return(t,e,n)=>{try{const{error:s,value:i}=r.validate(t.body);if(s){P(e,`Validation error: ${s.message}`,400);return}t.body=i,n()}catch{P(e,"Validation error",400)}}}function Ge(r={},t){const e=v.Router();return r.requireAuth&&t&&(e.use(t.authenticate),r.requiredRole&&e.use(t.hasRole(r.requiredRole))),r.rateLimit&&console.warn("Rate limiting is disabled: express-rate-limit dependency is not installed"),e}function D(r){return(t,e,n)=>{r(t,e,n).catch(n)}}function Je(r){const t=v.Router();return t.get("/",ye,D(async(e,n)=>{const s=await r.getAll(e.pagination);N(n,s)})),t.get("/:id",D(async(e,n)=>{const s=await r.getById(e.params.id);if(!s)return P(n,"Item not found",404);N(n,s)})),t.post("/",D(async(e,n)=>{const s=await r.create(e.body);N(n,s,"Item created successfully",201)})),t.put("/:id",D(async(e,n)=>{const s=await r.update(e.params.id,e.body);if(!s)return P(n,"Item not found",404);N(n,s,"Item updated successfully")})),t.delete("/:id",D(async(e,n)=>{if(!await r.delete(e.params.id))return P(n,"Item not found",404);N(n,null,"Item deleted successfully")})),t}const ut={jsx:L,jsxs:re,jsxDEV:se,createElement:U,Fragment:ne,Component:je,useState:fe,useEffect:$e,useRef:Re,useMemo:Ie,useErrorBoundary:Oe,render:Y,hydrate:Ne,renderToString:O,prepareRender:B,finishRender:H,batchUpdates:J,createContext:Pe,useContext:De,createServer:Me,createAuth:Le,createModel:Ve,FieldTypes:Be,createModelRouter:qe,createCustomRouter:We,createApiRouter:Ge,sendSuccess:N,sendError:P,apiResponse:Z,getPaginationParams:pe,paginationMiddleware:ye,validateRequest:Ue,asyncHandler:D,createRestEndpoints:Je,DatabaseConnector:he};a.Component=je,a.DatabaseConnector=he,a.FieldTypes=Be,a.Fragment=ne,a.apiResponse=Z,a.asyncHandler=D,a.batchUpdates=J,a.createApiRouter=Ge,a.createAuth=Le,a.createContext=Pe,a.createCustomRouter=We,a.createElement=U,a.createModel=Ve,a.createModelRouter=qe,a.createRestEndpoints=Je,a.createServer=Me,a.default=ut,a.finishRender=H,a.getPaginationParams=pe,a.hydrate=Ne,a.jsx=L,a.jsxDEV=se,a.jsxs=re,a.paginationMiddleware=ye,a.prepareRender=B,a.render=Y,a.renderToString=O,a.sendError=P,a.sendSuccess=N,a.useContext=De,a.useEffect=$e,a.useErrorBoundary=Oe,a.useMemo=Ie,a.useRef=Re,a.useState=fe,a.validateRequest=Ue,Object.defineProperties(a,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
66
|
+
`),d&&d()}),h=async w=>{console.log(`${w} signal received: closing HTTP server and cleaning up`),m.close(async()=>{console.log("HTTP server closed"),g&&g.isConnected()&&(await g.disconnect(),console.log("Database connection closed")),E.exit(0)}),setTimeout(()=>{console.error("Could not close connections in time, forcefully shutting down"),E.exit(1)},1e4)};return E.on("SIGTERM",()=>h("SIGTERM")),E.on("SIGINT",()=>h("SIGINT")),m},t}const he=require("jsonwebtoken"),Me=require("bcrypt"),st=require("crypto");class ot{constructor(t){if(this.loginAttempts=new Map,this.login=async(e,n)=>{try{const{username:s,password:i}=e.body,o=e.ip||e.connection.remoteAddress||"";if(!this.checkRateLimit(o)){n.status(429).json({success:!1,message:"Too many login attempts. Please try again later."});return}if(!s||!i){n.status(400).json({success:!1,message:"Username and password are required"});return}if(!this.options.findUser){n.status(500).json({success:!1,message:"User finder function not configured"});return}const a=await this.options.findUser(s);if(!a){n.status(401).json({success:!1,message:"Invalid credentials"});return}if(!await this.options.verifyPassword(i,a.password)){n.status(401).json({success:!1,message:"Invalid credentials"});return}const f={...a};delete f.password;const p=this.generateTokenPair({id:a.id||a._id,username:a.username,role:a.role||"user"});if(this.options.saveRefreshToken){const b=new Date;b.setSeconds(b.getSeconds()+this.getExpirationSeconds(this.options.refreshExpiration||"7d")),await this.options.saveRefreshToken(a.id||a._id,p.refreshToken,b)}e.body.useCookies&&this.setAuthCookies(n,p),n.json({success:!0,message:"Authentication successful",tokens:p,user:f})}catch(s){console.error("Authentication error:",s),n.status(500).json({success:!1,message:"Authentication failed",error:E.env.NODE_ENV!=="production"?s.message:void 0})}},this.refreshToken=async(e,n)=>{var s,i;try{const o=((s=e.cookies)==null?void 0:s.refreshToken)||e.body.refreshToken;if(!o){n.status(401).json({success:!1,message:"Refresh token required"});return}const a=this.verifyToken(o,"refresh");if(this.options.verifyRefreshToken&&!await this.options.verifyRefreshToken(a.id,o)){this.clearAuthCookies(n),n.status(401).json({success:!1,message:"Invalid refresh token"});return}const c=this.generateTokenPair({id:a.id,...this.options.findUser?await this.options.findUser(a.id):{}});if(this.options.saveRefreshToken){const p=new Date;p.setSeconds(p.getSeconds()+this.getExpirationSeconds(this.options.refreshExpiration||"7d")),await this.options.saveRefreshToken(a.id,c.refreshToken,p)}(((i=e.cookies)==null?void 0:i.accessToken)||e.body.useCookies)&&this.setAuthCookies(n,c),n.json({success:!0,message:"Token refreshed successfully",tokens:c})}catch(o){this.clearAuthCookies(n),n.status(401).json({success:!1,message:"Invalid or expired refresh token",error:E.env.NODE_ENV!=="production"?o.message:void 0})}},this.logout=async(e,n)=>{var s;try{this.clearAuthCookies(n);const i=((s=e.cookies)==null?void 0:s.refreshToken)||e.body.refreshToken;if(i&&this.options.saveRefreshToken)try{const o=this.verifyToken(i,"refresh");typeof this.options.saveRefreshToken=="function"&&await this.options.saveRefreshToken(o.id,"",new Date)}catch{}n.json({success:!0,message:"Logged out successfully"})}catch(i){console.error("Logout error:",i),n.status(500).json({success:!1,message:"Logout failed",error:i.message})}},this.authenticate=(e,n,s)=>{var i;try{let o=(i=e.cookies)==null?void 0:i.accessToken;if(!o){const c=e.headers.authorization;c&&c.startsWith("Bearer ")&&(o=c.split(" ")[1])}if(!o){n.status(401).json({success:!1,message:"Authentication required"});return}const a=this.verifyToken(o,"access");e.user=a,s()}catch(o){n.status(401).json({success:!1,message:"Invalid or expired token",error:E.env.NODE_ENV!=="production"?o.message:void 0})}},this.hasRole=e=>(n,s,i)=>{const o=n.user;if(!o){s.status(401).json({success:!1,message:"Authentication required"});return}(Array.isArray(e)?e:[e]).includes(o.role)?i():s.status(403).json({success:!1,message:"Insufficient permissions"})},this.options={tokenExpiration:"15m",refreshExpiration:"7d",saltRounds:10,secureCookies:E.env.NODE_ENV==="production",httpOnlyCookies:!0,rateLimit:!0,...t,refreshSecret:t.refreshSecret||t.jwtSecret},!t.jwtSecret)throw new Error("JWT secret is required for authentication");this.options.verifyPassword||(this.options.verifyPassword=this.verifyPasswordWithBcrypt)}async hashPassword(t){return await Me.hash(t,this.options.saltRounds||10)}async verifyPasswordWithBcrypt(t,e){return await Me.compare(t,e)}generateSecureToken(t=32){return st.randomBytes(t).toString("hex")}generateTokenPair(t){const e=this.getExpirationSeconds(this.options.tokenExpiration||"15m"),n=he.sign({...t,type:"access"},this.options.jwtSecret,{expiresIn:this.options.tokenExpiration}),s=he.sign({id:t.id,type:"refresh"},this.options.refreshSecret,{expiresIn:this.options.refreshExpiration});return{accessToken:n,refreshToken:s,expiresIn:e}}getExpirationSeconds(t){const e=t.charAt(t.length-1),n=parseInt(t.slice(0,-1));switch(e){case"s":return n;case"m":return n*60;case"h":return n*60*60;case"d":return n*60*60*24;default:return 3600}}verifyToken(t,e="access"){try{const n=e==="access"?this.options.jwtSecret:this.options.refreshSecret,s=he.verify(t,n);if(typeof s=="object"&&s.type!==e)throw new Error("Invalid token type");return s}catch{throw new Error("Invalid or expired token")}}setAuthCookies(t,e){t.cookie("accessToken",e.accessToken,{httpOnly:this.options.httpOnlyCookies,secure:this.options.secureCookies,domain:this.options.cookieDomain,sameSite:"strict",maxAge:e.expiresIn*1e3});const n=this.getExpirationSeconds(this.options.refreshExpiration||"7d");t.cookie("refreshToken",e.refreshToken,{httpOnly:!0,secure:this.options.secureCookies,domain:this.options.cookieDomain,sameSite:"strict",maxAge:n*1e3,path:"/api/auth/refresh"})}clearAuthCookies(t){t.clearCookie("accessToken"),t.clearCookie("refreshToken",{path:"/api/auth/refresh"})}checkRateLimit(t){if(!this.options.rateLimit)return!0;const e=Date.now(),n=this.loginAttempts.get(t);return n?e>n.resetTime?(this.loginAttempts.set(t,{count:1,resetTime:e+36e5}),!0):n.count>=5?!1:(n.count++,this.loginAttempts.set(t,n),!0):(this.loginAttempts.set(t,{count:1,resetTime:e+36e5}),!0)}}function Fe(r){return new ot(r)}function Le(r,t){const e=_.model(r,t);return{getAll:async n=>{try{const{page:s=1,limit:i=10,sort:o="_id",order:a="desc"}=n||{},c=(s-1)*i,f=a==="asc"?1:-1,p={[o]:f},[b,$]=await Promise.all([e.find().sort(p).skip(c).limit(i).exec(),e.countDocuments().exec()]),g=Math.ceil($/i);return{data:b,pagination:{total:$,totalPages:g,currentPage:s,limit:i,hasNextPage:s<g,hasPrevPage:s>1}}}catch(s){throw console.error(`Error in ${r}.getAll:`,s),new Error(`Failed to retrieve ${r} records: ${s.message}`)}},getById:async n=>{try{return _.isValidObjectId(n)?await e.findById(n).exec():null}catch(s){throw console.error(`Error in ${r}.getById:`,s),new Error(`Failed to retrieve ${r} by ID: ${s.message}`)}},create:async n=>{try{return await new e(n).save()}catch(s){throw console.error(`Error in ${r}.create:`,s),new Error(`Failed to create ${r}: ${s.message}`)}},createMany:async n=>{try{return await e.insertMany(n)}catch(s){throw console.error(`Error in ${r}.createMany:`,s),new Error(`Failed to create multiple ${r} records: ${s.message}`)}},update:async(n,s)=>{try{return _.isValidObjectId(n)?await e.findByIdAndUpdate(n,{$set:s},{new:!0,runValidators:!0}).exec():null}catch(i){throw console.error(`Error in ${r}.update:`,i),new Error(`Failed to update ${r}: ${i.message}`)}},delete:async n=>{try{return _.isValidObjectId(n)?await e.findByIdAndDelete(n).exec()!==null:!1}catch(s){throw console.error(`Error in ${r}.delete:`,s),new Error(`Failed to delete ${r}: ${s.message}`)}},find:async(n,s)=>{try{const{page:i=1,limit:o=10,sort:a="_id",order:c="desc"}=s||{},f=(i-1)*o,p=c==="asc"?1:-1,b={[a]:p},[$,g]=await Promise.all([e.find(n).sort(b).skip(f).limit(o).exec(),e.countDocuments(n).exec()]),F=Math.ceil(g/o);return{data:$,pagination:{total:g,totalPages:F,currentPage:i,limit:o,hasNextPage:i<F,hasPrevPage:i>1}}}catch(i){throw console.error(`Error in ${r}.find:`,i),new Error(`Failed to find ${r} records: ${i.message}`)}},count:async n=>{try{return await e.countDocuments(n||{}).exec()}catch(s){throw console.error(`Error in ${r}.count:`,s),new Error(`Failed to count ${r} records: ${s.message}`)}},findOne:async n=>{try{return await e.findOne(n).exec()}catch(s){throw console.error(`Error in ${r}.findOne:`,s),new Error(`Failed to find ${r} record: ${s.message}`)}}}}const Ve={String:{type:String},Number:{type:Number},Boolean:{type:Boolean},Date:{type:Date},ObjectId:{type:String},Required:r=>({...r,required:!0}),Unique:r=>({...r,unique:!0}),Ref:r=>({type:String,ref:r}),Enum:r=>({type:String,enum:r}),Default:(r,t)=>({...r,default:t}),Array:r=>({type:[r]})},Be=(r,{res:t})=>{console.error("API Error:",r);const e=r.status||r.statusCode||500,n=r.message||"Internal server error";t.status(e).json({success:!1,error:n,stack:E.env.NODE_ENV!=="production"?r.stack:void 0})};function qe(r,t={}){const e=v.Router(),{middleware:n=[],errorHandler:s=Be}=t;n.forEach(o=>e.use(o));const i=o=>async(a,c,f)=>{try{const p={req:a,res:c,next:f,params:a.params,query:a.query,body:a.body};return await o(p)}catch(p){const b={req:a,res:c,next:f,params:a.params,query:a.query,body:a.body};return s(p,b)}};return e.get("/",i(async({req:o,res:a})=>{const c=o.pagination||{page:1,limit:10},f=await r.getAll(c);a.json({success:!0,...f})})),e.get("/:id",i(async({params:o,res:a})=>{const c=await r.getById(o.id);if(!c){a.status(404).json({success:!1,error:"Item not found"});return}a.json({success:!0,data:c})})),e.post("/",i(async({body:o,res:a})=>{const c=await r.create(o);a.status(201).json({success:!0,data:c,message:"Item created successfully"})})),e.put("/:id",i(async({params:o,body:a,res:c})=>{const f=await r.update(o.id,a);if(!f){c.status(404).json({success:!1,error:"Item not found"});return}c.json({success:!0,data:f,message:"Item updated successfully"})})),e.delete("/:id",i(async({params:o,res:a})=>{if(!await r.delete(o.id)){a.status(404).json({success:!1,error:"Item not found"});return}a.json({success:!0,message:"Item deleted successfully"})})),e}function He(r,t={}){const e=v.Router(),{middleware:n=[],errorHandler:s=Be}=t;n.forEach(o=>e.use(o));const i=o=>async(a,c,f)=>{try{const p={req:a,res:c,next:f,params:a.params,query:a.query,body:a.body};return c.headersSent?void 0:await o(p)}catch(p){if(c.headersSent){console.error("Error occurred after response was sent:",p);return}const b={req:a,res:c,next:f,params:a.params,query:a.query,body:a.body};return s(p,b)}};return Object.entries(r).forEach(([o,a])=>{const{method:c,handler:f}=a;e[c](o,i(f))}),e}function Z(r,t,e,n,s){const i={success:r};return t!==void 0&&(i.data=t),e&&(i.message=e),n&&(i.error=n),s&&(i.meta=s),i}function O(r,t,e,n=200,s){r.status(n).json(Z(!0,t,e,void 0,s))}function P(r,t,e=400,n){const s=t instanceof Error?t.message:t;r.status(e).json(Z(!1,void 0,void 0,s,n))}function pe(r){const t=parseInt(r.query.page)||1,e=parseInt(r.query.limit)||10,n=r.query.sort||"createdAt",s=r.query.order==="asc"?"asc":"desc";return{page:t,limit:e,sort:n,order:s}}function ye(r,t,e){r.pagination=pe(r),e()}function We(r){return(t,e,n)=>{try{const{error:s,value:i}=r.validate(t.body);if(s){P(e,`Validation error: ${s.message}`,400);return}t.body=i,n()}catch{P(e,"Validation error",400)}}}function Ue(r={},t){const e=v.Router();return r.requireAuth&&t&&(e.use(t.authenticate),r.requiredRole&&e.use(t.hasRole(r.requiredRole))),r.rateLimit&&console.warn("Rate limiting is disabled: express-rate-limit dependency is not installed"),e}function D(r){return(t,e,n)=>{r(t,e,n).catch(n)}}function Ge(r){const t=v.Router();return t.get("/",ye,D(async(e,n)=>{const s=await r.getAll(e.pagination);O(n,s)})),t.get("/:id",D(async(e,n)=>{const s=await r.getById(e.params.id);if(!s)return P(n,"Item not found",404);O(n,s)})),t.post("/",D(async(e,n)=>{const s=await r.create(e.body);O(n,s,"Item created successfully",201)})),t.put("/:id",D(async(e,n)=>{const s=await r.update(e.params.id,e.body);if(!s)return P(n,"Item not found",404);O(n,s,"Item updated successfully")})),t.delete("/:id",D(async(e,n)=>{if(!await r.delete(e.params.id))return P(n,"Item not found",404);O(n,null,"Item deleted successfully")})),t}const it={jsx:L,jsxs:te,jsxDEV:ne,createElement:U,Fragment:re,Component:Ae,useState:de,useEffect:$e,useRef:Ie,useMemo:_e,useErrorBoundary:xe,render:z,hydrate:Ne,renderToString:N,prepareRender:B,finishRender:q,batchUpdates:J,createContext:Oe,useContext:Pe,createServer:De,createAuth:Fe,createModel:Le,FieldTypes:Ve,createModelRouter:qe,createCustomRouter:He,createApiRouter:Ue,sendSuccess:O,sendError:P,apiResponse:Z,getPaginationParams:pe,paginationMiddleware:ye,validateRequest:We,asyncHandler:D,createRestEndpoints:Ge,DatabaseConnector:fe};u.Component=Ae,u.DatabaseConnector=fe,u.FieldTypes=Ve,u.Fragment=re,u.apiResponse=Z,u.asyncHandler=D,u.batchUpdates=J,u.createApiRouter=Ue,u.createAuth=Fe,u.createContext=Oe,u.createCustomRouter=He,u.createElement=U,u.createModel=Le,u.createModelRouter=qe,u.createRestEndpoints=Ge,u.createServer=De,u.default=it,u.finishRender=q,u.getPaginationParams=pe,u.hydrate=Ne,u.jsx=L,u.jsxDEV=ne,u.jsxs=te,u.paginationMiddleware=ye,u.prepareRender=B,u.render=z,u.renderToString=N,u.sendError=P,u.sendSuccess=O,u.useContext=Pe,u.useEffect=$e,u.useErrorBoundary=xe,u.useMemo=_e,u.useRef=Ie,u.useState=de,u.validateRequest=We,Object.defineProperties(u,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
package/package.json
CHANGED
package/src/backend/auth.ts
CHANGED
@@ -1,8 +1,8 @@
|
|
1
1
|
import { Request, Response, NextFunction } from 'express';
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
2
|
+
const jwt =require('jsonwebtoken');
|
3
|
+
const bcrypt=require('bcrypt');
|
4
|
+
|
5
|
+
const crypto=require('crypto');
|
6
6
|
|
7
7
|
/**
|
8
8
|
* Authentication configuration options
|