@frontegg/nextjs 4.0.17 → 5.0.1-alpha.2295828351

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/index.cjs.js ADDED
@@ -0,0 +1,1999 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var jsxRuntime = require('react/jsx-runtime');
6
+ var react = require('react');
7
+ var adminPortal = require('@frontegg/admin-portal');
8
+ var reactHooks = require('@frontegg/react-hooks');
9
+ var restApi = require('@frontegg/rest-api');
10
+ var router = require('next/router');
11
+ var jose = require('jose');
12
+ var reduxStore = require('@frontegg/redux-store');
13
+ var url = require('url');
14
+ var cookie = require('cookie');
15
+ var ironSession = require('iron-session');
16
+ var httpProxy = require('http-proxy');
17
+ var types = require('@frontegg/types');
18
+
19
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
20
+
21
+ var cookie__default = /*#__PURE__*/_interopDefaultLegacy(cookie);
22
+ var httpProxy__default = /*#__PURE__*/_interopDefaultLegacy(httpProxy);
23
+
24
+ /******************************************************************************
25
+ Copyright (c) Microsoft Corporation.
26
+
27
+ Permission to use, copy, modify, and/or distribute this software for any
28
+ purpose with or without fee is hereby granted.
29
+
30
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
31
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
32
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
33
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
34
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
35
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
36
+ PERFORMANCE OF THIS SOFTWARE.
37
+ ***************************************************************************** */
38
+
39
+ function __rest(s, e) {
40
+ var t = {};
41
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
42
+ t[p] = s[p];
43
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
44
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
45
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
46
+ t[p[i]] = s[p[i]];
47
+ }
48
+ return t;
49
+ }
50
+
51
+ function __awaiter(thisArg, _arguments, P, generator) {
52
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
53
+ return new (P || (P = Promise))(function (resolve, reject) {
54
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
55
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
56
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
57
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
58
+ });
59
+ }
60
+
61
+ var Connector = function Connector(_a) {
62
+ var _b;
63
+
64
+ var router = _a.router,
65
+ appName = _a.appName,
66
+ props = __rest(_a, ["router", "appName"]);
67
+
68
+ var isSSR = typeof window === 'undefined';
69
+ var baseName = (_b = props.basename) !== null && _b !== void 0 ? _b : router.basePath;
70
+ var onRedirectTo = react.useCallback(function (_path, opts) {
71
+ var path = _path;
72
+
73
+ if (path.startsWith(baseName)) {
74
+ path = path.substring(baseName.length);
75
+ }
76
+
77
+ if (opts === null || opts === void 0 ? void 0 : opts.preserveQueryParams) {
78
+ path = "".concat(path).concat(window.location.search);
79
+ }
80
+
81
+ if ((opts === null || opts === void 0 ? void 0 : opts.refresh) && !isSSR) {
82
+ // @ts-ignore
83
+ window.Cypress ? router.push(path) : window.location.href = path;
84
+ } else {
85
+ (opts === null || opts === void 0 ? void 0 : opts.replace) ? router.replace(path) : router.push(path);
86
+ }
87
+ }, []);
88
+ var contextOptions = react.useMemo(function () {
89
+ return {
90
+ baseUrl: function baseUrl(path) {
91
+ if (restApi.fronteggAuthApiRoutes.indexOf(path) !== -1) {
92
+ return "".concat(props.envAppUrl, "/api");
93
+ } else {
94
+ return props.envBaseUrl;
95
+ }
96
+ },
97
+ clientId: props.envClientId
98
+ };
99
+ }, [props.contextOptions]);
100
+ var app = react.useMemo(function () {
101
+ var _a;
102
+
103
+ var createdApp;
104
+
105
+ try {
106
+ createdApp = adminPortal.AppHolder.getInstance(appName !== null && appName !== void 0 ? appName : 'default');
107
+ } catch (e) {
108
+ createdApp = adminPortal.initialize(Object.assign(Object.assign({}, props), {
109
+ basename: (_a = props.basename) !== null && _a !== void 0 ? _a : baseName,
110
+ contextOptions: Object.assign(Object.assign({
111
+ requestCredentials: 'include'
112
+ }, props.contextOptions), contextOptions),
113
+ onRedirectTo: onRedirectTo
114
+ }), appName !== null && appName !== void 0 ? appName : 'default');
115
+ }
116
+
117
+ return createdApp;
118
+ }, [onRedirectTo]);
119
+ restApi.ContextHolder.setOnRedirectTo(onRedirectTo);
120
+ react.useEffect(function () {
121
+ var _a; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
122
+ // @ts-ignore
123
+
124
+
125
+ app.store.dispatch({
126
+ type: 'auth/requestAuthorizeSSR',
127
+ payload: (_a = props.session) === null || _a === void 0 ? void 0 : _a.accessToken
128
+ });
129
+ }, [app]);
130
+ return jsxRuntime.jsx(reactHooks.FronteggStoreProvider, Object.assign({}, Object.assign(Object.assign({}, props), {
131
+ app: app
132
+ }), {
133
+ children: props.children
134
+ }));
135
+ };
136
+
137
+ var ExpireInListener = function ExpireInListener() {
138
+ var user = reactHooks.useAuthUserOrNull();
139
+ var actions = reactHooks.useAuthActions();
140
+ react.useEffect(function () {
141
+ if (user && (user === null || user === void 0 ? void 0 : user.expiresIn) == null) {
142
+ actions.setUser(Object.assign(Object.assign({}, user), {
143
+ expiresIn: Math.floor((user['exp'] * 1000 - Date.now()) / 1000)
144
+ }));
145
+ }
146
+ }, [actions, user]);
147
+ return jsxRuntime.jsx(jsxRuntime.Fragment, {});
148
+ };
149
+
150
+ var FronteggNextJSProvider = function FronteggNextJSProvider(props) {
151
+ var router$1 = router.useRouter();
152
+ return jsxRuntime.jsxs(Connector, Object.assign({}, props, {
153
+ router: router$1
154
+ }, {
155
+ children: [jsxRuntime.jsx(ExpireInListener, {}), props.children]
156
+ }));
157
+ };
158
+
159
+ var FronteggProvider = function FronteggProvider(props) {
160
+ return jsxRuntime.jsx(FronteggNextJSProvider, Object.assign({}, props, {
161
+ framework: 'nextjs'
162
+ }, {
163
+ children: props.children
164
+ }));
165
+ };
166
+
167
+ function _createForOfIteratorHelper$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
168
+
169
+ function _unsupportedIterableToArray$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen); }
170
+
171
+ function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
172
+ var AuthorizedContent = function AuthorizedContent(props) {
173
+ var _a, _b;
174
+
175
+ var isAuthorized = true; // Initially
176
+
177
+ var user = reactHooks.useAuthUserOrNull();
178
+
179
+ if (!(user === null || user === void 0 ? void 0 : user.superUser)) {
180
+ if (props.requiredPermissions) {
181
+ if (!(user === null || user === void 0 ? void 0 : user.permissions) || (user === null || user === void 0 ? void 0 : user.permissions.length) === 0) {
182
+ isAuthorized = false;
183
+ }
184
+
185
+ var _iterator = _createForOfIteratorHelper$1(props.requiredPermissions),
186
+ _step;
187
+
188
+ try {
189
+ var _loop = function _loop() {
190
+ var permission = _step.value;
191
+
192
+ if (!((_a = user === null || user === void 0 ? void 0 : user.permissions) === null || _a === void 0 ? void 0 : _a.find(function (_ref) {
193
+ var key = _ref.key;
194
+ return key === permission;
195
+ }))) {
196
+ isAuthorized = false;
197
+ }
198
+ };
199
+
200
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
201
+ _loop();
202
+ }
203
+ } catch (err) {
204
+ _iterator.e(err);
205
+ } finally {
206
+ _iterator.f();
207
+ }
208
+ }
209
+
210
+ if (props.requiredRoles) {
211
+ if (!(user === null || user === void 0 ? void 0 : user.roles) || (user === null || user === void 0 ? void 0 : user.roles.length) === 0) {
212
+ isAuthorized = false;
213
+ }
214
+
215
+ var _iterator2 = _createForOfIteratorHelper$1(props.requiredRoles),
216
+ _step2;
217
+
218
+ try {
219
+ var _loop2 = function _loop2() {
220
+ var role = _step2.value;
221
+
222
+ if (!((_b = user === null || user === void 0 ? void 0 : user.roles) === null || _b === void 0 ? void 0 : _b.find(function (_ref2) {
223
+ var key = _ref2.key;
224
+ return key === role;
225
+ }))) {
226
+ isAuthorized = false;
227
+ }
228
+ };
229
+
230
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
231
+ _loop2();
232
+ }
233
+ } catch (err) {
234
+ _iterator2.e(err);
235
+ } finally {
236
+ _iterator2.f();
237
+ }
238
+ }
239
+ }
240
+
241
+ if (typeof props.render === 'function') {
242
+ return jsxRuntime.jsx(jsxRuntime.Fragment, {
243
+ children: props.render(isAuthorized)
244
+ });
245
+ }
246
+
247
+ return isAuthorized ? jsxRuntime.jsx(jsxRuntime.Fragment, {
248
+ children: props.children
249
+ }) : null;
250
+ };
251
+
252
+ function _classCallCheck(instance, Constructor) {
253
+ if (!(instance instanceof Constructor)) {
254
+ throw new TypeError("Cannot call a class as a function");
255
+ }
256
+ }
257
+
258
+ function _defineProperties(target, props) {
259
+ for (var i = 0; i < props.length; i++) {
260
+ var descriptor = props[i];
261
+ descriptor.enumerable = descriptor.enumerable || false;
262
+ descriptor.configurable = true;
263
+ if ("value" in descriptor) descriptor.writable = true;
264
+ Object.defineProperty(target, descriptor.key, descriptor);
265
+ }
266
+ }
267
+
268
+ function _createClass(Constructor, protoProps, staticProps) {
269
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
270
+ if (staticProps) _defineProperties(Constructor, staticProps);
271
+ Object.defineProperty(Constructor, "prototype", {
272
+ writable: false
273
+ });
274
+ return Constructor;
275
+ }
276
+
277
+ var runtime = {exports: {}};
278
+
279
+ /**
280
+ * Copyright (c) 2014-present, Facebook, Inc.
281
+ *
282
+ * This source code is licensed under the MIT license found in the
283
+ * LICENSE file in the root directory of this source tree.
284
+ */
285
+
286
+ (function (module) {
287
+ var runtime = (function (exports) {
288
+
289
+ var Op = Object.prototype;
290
+ var hasOwn = Op.hasOwnProperty;
291
+ var undefined$1; // More compressible than void 0.
292
+ var $Symbol = typeof Symbol === "function" ? Symbol : {};
293
+ var iteratorSymbol = $Symbol.iterator || "@@iterator";
294
+ var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
295
+ var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
296
+
297
+ function define(obj, key, value) {
298
+ Object.defineProperty(obj, key, {
299
+ value: value,
300
+ enumerable: true,
301
+ configurable: true,
302
+ writable: true
303
+ });
304
+ return obj[key];
305
+ }
306
+ try {
307
+ // IE 8 has a broken Object.defineProperty that only works on DOM objects.
308
+ define({}, "");
309
+ } catch (err) {
310
+ define = function(obj, key, value) {
311
+ return obj[key] = value;
312
+ };
313
+ }
314
+
315
+ function wrap(innerFn, outerFn, self, tryLocsList) {
316
+ // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
317
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
318
+ var generator = Object.create(protoGenerator.prototype);
319
+ var context = new Context(tryLocsList || []);
320
+
321
+ // The ._invoke method unifies the implementations of the .next,
322
+ // .throw, and .return methods.
323
+ generator._invoke = makeInvokeMethod(innerFn, self, context);
324
+
325
+ return generator;
326
+ }
327
+ exports.wrap = wrap;
328
+
329
+ // Try/catch helper to minimize deoptimizations. Returns a completion
330
+ // record like context.tryEntries[i].completion. This interface could
331
+ // have been (and was previously) designed to take a closure to be
332
+ // invoked without arguments, but in all the cases we care about we
333
+ // already have an existing method we want to call, so there's no need
334
+ // to create a new function object. We can even get away with assuming
335
+ // the method takes exactly one argument, since that happens to be true
336
+ // in every case, so we don't have to touch the arguments object. The
337
+ // only additional allocation required is the completion record, which
338
+ // has a stable shape and so hopefully should be cheap to allocate.
339
+ function tryCatch(fn, obj, arg) {
340
+ try {
341
+ return { type: "normal", arg: fn.call(obj, arg) };
342
+ } catch (err) {
343
+ return { type: "throw", arg: err };
344
+ }
345
+ }
346
+
347
+ var GenStateSuspendedStart = "suspendedStart";
348
+ var GenStateSuspendedYield = "suspendedYield";
349
+ var GenStateExecuting = "executing";
350
+ var GenStateCompleted = "completed";
351
+
352
+ // Returning this object from the innerFn has the same effect as
353
+ // breaking out of the dispatch switch statement.
354
+ var ContinueSentinel = {};
355
+
356
+ // Dummy constructor functions that we use as the .constructor and
357
+ // .constructor.prototype properties for functions that return Generator
358
+ // objects. For full spec compliance, you may wish to configure your
359
+ // minifier not to mangle the names of these two functions.
360
+ function Generator() {}
361
+ function GeneratorFunction() {}
362
+ function GeneratorFunctionPrototype() {}
363
+
364
+ // This is a polyfill for %IteratorPrototype% for environments that
365
+ // don't natively support it.
366
+ var IteratorPrototype = {};
367
+ define(IteratorPrototype, iteratorSymbol, function () {
368
+ return this;
369
+ });
370
+
371
+ var getProto = Object.getPrototypeOf;
372
+ var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
373
+ if (NativeIteratorPrototype &&
374
+ NativeIteratorPrototype !== Op &&
375
+ hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
376
+ // This environment has a native %IteratorPrototype%; use it instead
377
+ // of the polyfill.
378
+ IteratorPrototype = NativeIteratorPrototype;
379
+ }
380
+
381
+ var Gp = GeneratorFunctionPrototype.prototype =
382
+ Generator.prototype = Object.create(IteratorPrototype);
383
+ GeneratorFunction.prototype = GeneratorFunctionPrototype;
384
+ define(Gp, "constructor", GeneratorFunctionPrototype);
385
+ define(GeneratorFunctionPrototype, "constructor", GeneratorFunction);
386
+ GeneratorFunction.displayName = define(
387
+ GeneratorFunctionPrototype,
388
+ toStringTagSymbol,
389
+ "GeneratorFunction"
390
+ );
391
+
392
+ // Helper for defining the .next, .throw, and .return methods of the
393
+ // Iterator interface in terms of a single ._invoke method.
394
+ function defineIteratorMethods(prototype) {
395
+ ["next", "throw", "return"].forEach(function(method) {
396
+ define(prototype, method, function(arg) {
397
+ return this._invoke(method, arg);
398
+ });
399
+ });
400
+ }
401
+
402
+ exports.isGeneratorFunction = function(genFun) {
403
+ var ctor = typeof genFun === "function" && genFun.constructor;
404
+ return ctor
405
+ ? ctor === GeneratorFunction ||
406
+ // For the native GeneratorFunction constructor, the best we can
407
+ // do is to check its .name property.
408
+ (ctor.displayName || ctor.name) === "GeneratorFunction"
409
+ : false;
410
+ };
411
+
412
+ exports.mark = function(genFun) {
413
+ if (Object.setPrototypeOf) {
414
+ Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
415
+ } else {
416
+ genFun.__proto__ = GeneratorFunctionPrototype;
417
+ define(genFun, toStringTagSymbol, "GeneratorFunction");
418
+ }
419
+ genFun.prototype = Object.create(Gp);
420
+ return genFun;
421
+ };
422
+
423
+ // Within the body of any async function, `await x` is transformed to
424
+ // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
425
+ // `hasOwn.call(value, "__await")` to determine if the yielded value is
426
+ // meant to be awaited.
427
+ exports.awrap = function(arg) {
428
+ return { __await: arg };
429
+ };
430
+
431
+ function AsyncIterator(generator, PromiseImpl) {
432
+ function invoke(method, arg, resolve, reject) {
433
+ var record = tryCatch(generator[method], generator, arg);
434
+ if (record.type === "throw") {
435
+ reject(record.arg);
436
+ } else {
437
+ var result = record.arg;
438
+ var value = result.value;
439
+ if (value &&
440
+ typeof value === "object" &&
441
+ hasOwn.call(value, "__await")) {
442
+ return PromiseImpl.resolve(value.__await).then(function(value) {
443
+ invoke("next", value, resolve, reject);
444
+ }, function(err) {
445
+ invoke("throw", err, resolve, reject);
446
+ });
447
+ }
448
+
449
+ return PromiseImpl.resolve(value).then(function(unwrapped) {
450
+ // When a yielded Promise is resolved, its final value becomes
451
+ // the .value of the Promise<{value,done}> result for the
452
+ // current iteration.
453
+ result.value = unwrapped;
454
+ resolve(result);
455
+ }, function(error) {
456
+ // If a rejected Promise was yielded, throw the rejection back
457
+ // into the async generator function so it can be handled there.
458
+ return invoke("throw", error, resolve, reject);
459
+ });
460
+ }
461
+ }
462
+
463
+ var previousPromise;
464
+
465
+ function enqueue(method, arg) {
466
+ function callInvokeWithMethodAndArg() {
467
+ return new PromiseImpl(function(resolve, reject) {
468
+ invoke(method, arg, resolve, reject);
469
+ });
470
+ }
471
+
472
+ return previousPromise =
473
+ // If enqueue has been called before, then we want to wait until
474
+ // all previous Promises have been resolved before calling invoke,
475
+ // so that results are always delivered in the correct order. If
476
+ // enqueue has not been called before, then it is important to
477
+ // call invoke immediately, without waiting on a callback to fire,
478
+ // so that the async generator function has the opportunity to do
479
+ // any necessary setup in a predictable way. This predictability
480
+ // is why the Promise constructor synchronously invokes its
481
+ // executor callback, and why async functions synchronously
482
+ // execute code before the first await. Since we implement simple
483
+ // async functions in terms of async generators, it is especially
484
+ // important to get this right, even though it requires care.
485
+ previousPromise ? previousPromise.then(
486
+ callInvokeWithMethodAndArg,
487
+ // Avoid propagating failures to Promises returned by later
488
+ // invocations of the iterator.
489
+ callInvokeWithMethodAndArg
490
+ ) : callInvokeWithMethodAndArg();
491
+ }
492
+
493
+ // Define the unified helper method that is used to implement .next,
494
+ // .throw, and .return (see defineIteratorMethods).
495
+ this._invoke = enqueue;
496
+ }
497
+
498
+ defineIteratorMethods(AsyncIterator.prototype);
499
+ define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
500
+ return this;
501
+ });
502
+ exports.AsyncIterator = AsyncIterator;
503
+
504
+ // Note that simple async functions are implemented on top of
505
+ // AsyncIterator objects; they just return a Promise for the value of
506
+ // the final result produced by the iterator.
507
+ exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
508
+ if (PromiseImpl === void 0) PromiseImpl = Promise;
509
+
510
+ var iter = new AsyncIterator(
511
+ wrap(innerFn, outerFn, self, tryLocsList),
512
+ PromiseImpl
513
+ );
514
+
515
+ return exports.isGeneratorFunction(outerFn)
516
+ ? iter // If outerFn is a generator, return the full iterator.
517
+ : iter.next().then(function(result) {
518
+ return result.done ? result.value : iter.next();
519
+ });
520
+ };
521
+
522
+ function makeInvokeMethod(innerFn, self, context) {
523
+ var state = GenStateSuspendedStart;
524
+
525
+ return function invoke(method, arg) {
526
+ if (state === GenStateExecuting) {
527
+ throw new Error("Generator is already running");
528
+ }
529
+
530
+ if (state === GenStateCompleted) {
531
+ if (method === "throw") {
532
+ throw arg;
533
+ }
534
+
535
+ // Be forgiving, per 25.3.3.3.3 of the spec:
536
+ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
537
+ return doneResult();
538
+ }
539
+
540
+ context.method = method;
541
+ context.arg = arg;
542
+
543
+ while (true) {
544
+ var delegate = context.delegate;
545
+ if (delegate) {
546
+ var delegateResult = maybeInvokeDelegate(delegate, context);
547
+ if (delegateResult) {
548
+ if (delegateResult === ContinueSentinel) continue;
549
+ return delegateResult;
550
+ }
551
+ }
552
+
553
+ if (context.method === "next") {
554
+ // Setting context._sent for legacy support of Babel's
555
+ // function.sent implementation.
556
+ context.sent = context._sent = context.arg;
557
+
558
+ } else if (context.method === "throw") {
559
+ if (state === GenStateSuspendedStart) {
560
+ state = GenStateCompleted;
561
+ throw context.arg;
562
+ }
563
+
564
+ context.dispatchException(context.arg);
565
+
566
+ } else if (context.method === "return") {
567
+ context.abrupt("return", context.arg);
568
+ }
569
+
570
+ state = GenStateExecuting;
571
+
572
+ var record = tryCatch(innerFn, self, context);
573
+ if (record.type === "normal") {
574
+ // If an exception is thrown from innerFn, we leave state ===
575
+ // GenStateExecuting and loop back for another invocation.
576
+ state = context.done
577
+ ? GenStateCompleted
578
+ : GenStateSuspendedYield;
579
+
580
+ if (record.arg === ContinueSentinel) {
581
+ continue;
582
+ }
583
+
584
+ return {
585
+ value: record.arg,
586
+ done: context.done
587
+ };
588
+
589
+ } else if (record.type === "throw") {
590
+ state = GenStateCompleted;
591
+ // Dispatch the exception by looping back around to the
592
+ // context.dispatchException(context.arg) call above.
593
+ context.method = "throw";
594
+ context.arg = record.arg;
595
+ }
596
+ }
597
+ };
598
+ }
599
+
600
+ // Call delegate.iterator[context.method](context.arg) and handle the
601
+ // result, either by returning a { value, done } result from the
602
+ // delegate iterator, or by modifying context.method and context.arg,
603
+ // setting context.delegate to null, and returning the ContinueSentinel.
604
+ function maybeInvokeDelegate(delegate, context) {
605
+ var method = delegate.iterator[context.method];
606
+ if (method === undefined$1) {
607
+ // A .throw or .return when the delegate iterator has no .throw
608
+ // method always terminates the yield* loop.
609
+ context.delegate = null;
610
+
611
+ if (context.method === "throw") {
612
+ // Note: ["return"] must be used for ES3 parsing compatibility.
613
+ if (delegate.iterator["return"]) {
614
+ // If the delegate iterator has a return method, give it a
615
+ // chance to clean up.
616
+ context.method = "return";
617
+ context.arg = undefined$1;
618
+ maybeInvokeDelegate(delegate, context);
619
+
620
+ if (context.method === "throw") {
621
+ // If maybeInvokeDelegate(context) changed context.method from
622
+ // "return" to "throw", let that override the TypeError below.
623
+ return ContinueSentinel;
624
+ }
625
+ }
626
+
627
+ context.method = "throw";
628
+ context.arg = new TypeError(
629
+ "The iterator does not provide a 'throw' method");
630
+ }
631
+
632
+ return ContinueSentinel;
633
+ }
634
+
635
+ var record = tryCatch(method, delegate.iterator, context.arg);
636
+
637
+ if (record.type === "throw") {
638
+ context.method = "throw";
639
+ context.arg = record.arg;
640
+ context.delegate = null;
641
+ return ContinueSentinel;
642
+ }
643
+
644
+ var info = record.arg;
645
+
646
+ if (! info) {
647
+ context.method = "throw";
648
+ context.arg = new TypeError("iterator result is not an object");
649
+ context.delegate = null;
650
+ return ContinueSentinel;
651
+ }
652
+
653
+ if (info.done) {
654
+ // Assign the result of the finished delegate to the temporary
655
+ // variable specified by delegate.resultName (see delegateYield).
656
+ context[delegate.resultName] = info.value;
657
+
658
+ // Resume execution at the desired location (see delegateYield).
659
+ context.next = delegate.nextLoc;
660
+
661
+ // If context.method was "throw" but the delegate handled the
662
+ // exception, let the outer generator proceed normally. If
663
+ // context.method was "next", forget context.arg since it has been
664
+ // "consumed" by the delegate iterator. If context.method was
665
+ // "return", allow the original .return call to continue in the
666
+ // outer generator.
667
+ if (context.method !== "return") {
668
+ context.method = "next";
669
+ context.arg = undefined$1;
670
+ }
671
+
672
+ } else {
673
+ // Re-yield the result returned by the delegate method.
674
+ return info;
675
+ }
676
+
677
+ // The delegate iterator is finished, so forget it and continue with
678
+ // the outer generator.
679
+ context.delegate = null;
680
+ return ContinueSentinel;
681
+ }
682
+
683
+ // Define Generator.prototype.{next,throw,return} in terms of the
684
+ // unified ._invoke helper method.
685
+ defineIteratorMethods(Gp);
686
+
687
+ define(Gp, toStringTagSymbol, "Generator");
688
+
689
+ // A Generator should always return itself as the iterator object when the
690
+ // @@iterator function is called on it. Some browsers' implementations of the
691
+ // iterator prototype chain incorrectly implement this, causing the Generator
692
+ // object to not be returned from this call. This ensures that doesn't happen.
693
+ // See https://github.com/facebook/regenerator/issues/274 for more details.
694
+ define(Gp, iteratorSymbol, function() {
695
+ return this;
696
+ });
697
+
698
+ define(Gp, "toString", function() {
699
+ return "[object Generator]";
700
+ });
701
+
702
+ function pushTryEntry(locs) {
703
+ var entry = { tryLoc: locs[0] };
704
+
705
+ if (1 in locs) {
706
+ entry.catchLoc = locs[1];
707
+ }
708
+
709
+ if (2 in locs) {
710
+ entry.finallyLoc = locs[2];
711
+ entry.afterLoc = locs[3];
712
+ }
713
+
714
+ this.tryEntries.push(entry);
715
+ }
716
+
717
+ function resetTryEntry(entry) {
718
+ var record = entry.completion || {};
719
+ record.type = "normal";
720
+ delete record.arg;
721
+ entry.completion = record;
722
+ }
723
+
724
+ function Context(tryLocsList) {
725
+ // The root entry object (effectively a try statement without a catch
726
+ // or a finally block) gives us a place to store values thrown from
727
+ // locations where there is no enclosing try statement.
728
+ this.tryEntries = [{ tryLoc: "root" }];
729
+ tryLocsList.forEach(pushTryEntry, this);
730
+ this.reset(true);
731
+ }
732
+
733
+ exports.keys = function(object) {
734
+ var keys = [];
735
+ for (var key in object) {
736
+ keys.push(key);
737
+ }
738
+ keys.reverse();
739
+
740
+ // Rather than returning an object with a next method, we keep
741
+ // things simple and return the next function itself.
742
+ return function next() {
743
+ while (keys.length) {
744
+ var key = keys.pop();
745
+ if (key in object) {
746
+ next.value = key;
747
+ next.done = false;
748
+ return next;
749
+ }
750
+ }
751
+
752
+ // To avoid creating an additional object, we just hang the .value
753
+ // and .done properties off the next function object itself. This
754
+ // also ensures that the minifier will not anonymize the function.
755
+ next.done = true;
756
+ return next;
757
+ };
758
+ };
759
+
760
+ function values(iterable) {
761
+ if (iterable) {
762
+ var iteratorMethod = iterable[iteratorSymbol];
763
+ if (iteratorMethod) {
764
+ return iteratorMethod.call(iterable);
765
+ }
766
+
767
+ if (typeof iterable.next === "function") {
768
+ return iterable;
769
+ }
770
+
771
+ if (!isNaN(iterable.length)) {
772
+ var i = -1, next = function next() {
773
+ while (++i < iterable.length) {
774
+ if (hasOwn.call(iterable, i)) {
775
+ next.value = iterable[i];
776
+ next.done = false;
777
+ return next;
778
+ }
779
+ }
780
+
781
+ next.value = undefined$1;
782
+ next.done = true;
783
+
784
+ return next;
785
+ };
786
+
787
+ return next.next = next;
788
+ }
789
+ }
790
+
791
+ // Return an iterator with no values.
792
+ return { next: doneResult };
793
+ }
794
+ exports.values = values;
795
+
796
+ function doneResult() {
797
+ return { value: undefined$1, done: true };
798
+ }
799
+
800
+ Context.prototype = {
801
+ constructor: Context,
802
+
803
+ reset: function(skipTempReset) {
804
+ this.prev = 0;
805
+ this.next = 0;
806
+ // Resetting context._sent for legacy support of Babel's
807
+ // function.sent implementation.
808
+ this.sent = this._sent = undefined$1;
809
+ this.done = false;
810
+ this.delegate = null;
811
+
812
+ this.method = "next";
813
+ this.arg = undefined$1;
814
+
815
+ this.tryEntries.forEach(resetTryEntry);
816
+
817
+ if (!skipTempReset) {
818
+ for (var name in this) {
819
+ // Not sure about the optimal order of these conditions:
820
+ if (name.charAt(0) === "t" &&
821
+ hasOwn.call(this, name) &&
822
+ !isNaN(+name.slice(1))) {
823
+ this[name] = undefined$1;
824
+ }
825
+ }
826
+ }
827
+ },
828
+
829
+ stop: function() {
830
+ this.done = true;
831
+
832
+ var rootEntry = this.tryEntries[0];
833
+ var rootRecord = rootEntry.completion;
834
+ if (rootRecord.type === "throw") {
835
+ throw rootRecord.arg;
836
+ }
837
+
838
+ return this.rval;
839
+ },
840
+
841
+ dispatchException: function(exception) {
842
+ if (this.done) {
843
+ throw exception;
844
+ }
845
+
846
+ var context = this;
847
+ function handle(loc, caught) {
848
+ record.type = "throw";
849
+ record.arg = exception;
850
+ context.next = loc;
851
+
852
+ if (caught) {
853
+ // If the dispatched exception was caught by a catch block,
854
+ // then let that catch block handle the exception normally.
855
+ context.method = "next";
856
+ context.arg = undefined$1;
857
+ }
858
+
859
+ return !! caught;
860
+ }
861
+
862
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
863
+ var entry = this.tryEntries[i];
864
+ var record = entry.completion;
865
+
866
+ if (entry.tryLoc === "root") {
867
+ // Exception thrown outside of any try block that could handle
868
+ // it, so set the completion value of the entire function to
869
+ // throw the exception.
870
+ return handle("end");
871
+ }
872
+
873
+ if (entry.tryLoc <= this.prev) {
874
+ var hasCatch = hasOwn.call(entry, "catchLoc");
875
+ var hasFinally = hasOwn.call(entry, "finallyLoc");
876
+
877
+ if (hasCatch && hasFinally) {
878
+ if (this.prev < entry.catchLoc) {
879
+ return handle(entry.catchLoc, true);
880
+ } else if (this.prev < entry.finallyLoc) {
881
+ return handle(entry.finallyLoc);
882
+ }
883
+
884
+ } else if (hasCatch) {
885
+ if (this.prev < entry.catchLoc) {
886
+ return handle(entry.catchLoc, true);
887
+ }
888
+
889
+ } else if (hasFinally) {
890
+ if (this.prev < entry.finallyLoc) {
891
+ return handle(entry.finallyLoc);
892
+ }
893
+
894
+ } else {
895
+ throw new Error("try statement without catch or finally");
896
+ }
897
+ }
898
+ }
899
+ },
900
+
901
+ abrupt: function(type, arg) {
902
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
903
+ var entry = this.tryEntries[i];
904
+ if (entry.tryLoc <= this.prev &&
905
+ hasOwn.call(entry, "finallyLoc") &&
906
+ this.prev < entry.finallyLoc) {
907
+ var finallyEntry = entry;
908
+ break;
909
+ }
910
+ }
911
+
912
+ if (finallyEntry &&
913
+ (type === "break" ||
914
+ type === "continue") &&
915
+ finallyEntry.tryLoc <= arg &&
916
+ arg <= finallyEntry.finallyLoc) {
917
+ // Ignore the finally entry if control is not jumping to a
918
+ // location outside the try/catch block.
919
+ finallyEntry = null;
920
+ }
921
+
922
+ var record = finallyEntry ? finallyEntry.completion : {};
923
+ record.type = type;
924
+ record.arg = arg;
925
+
926
+ if (finallyEntry) {
927
+ this.method = "next";
928
+ this.next = finallyEntry.finallyLoc;
929
+ return ContinueSentinel;
930
+ }
931
+
932
+ return this.complete(record);
933
+ },
934
+
935
+ complete: function(record, afterLoc) {
936
+ if (record.type === "throw") {
937
+ throw record.arg;
938
+ }
939
+
940
+ if (record.type === "break" ||
941
+ record.type === "continue") {
942
+ this.next = record.arg;
943
+ } else if (record.type === "return") {
944
+ this.rval = this.arg = record.arg;
945
+ this.method = "return";
946
+ this.next = "end";
947
+ } else if (record.type === "normal" && afterLoc) {
948
+ this.next = afterLoc;
949
+ }
950
+
951
+ return ContinueSentinel;
952
+ },
953
+
954
+ finish: function(finallyLoc) {
955
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
956
+ var entry = this.tryEntries[i];
957
+ if (entry.finallyLoc === finallyLoc) {
958
+ this.complete(entry.completion, entry.afterLoc);
959
+ resetTryEntry(entry);
960
+ return ContinueSentinel;
961
+ }
962
+ }
963
+ },
964
+
965
+ "catch": function(tryLoc) {
966
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
967
+ var entry = this.tryEntries[i];
968
+ if (entry.tryLoc === tryLoc) {
969
+ var record = entry.completion;
970
+ if (record.type === "throw") {
971
+ var thrown = record.arg;
972
+ resetTryEntry(entry);
973
+ }
974
+ return thrown;
975
+ }
976
+ }
977
+
978
+ // The context.catch method must only be called with a location
979
+ // argument that corresponds to a known catch block.
980
+ throw new Error("illegal catch attempt");
981
+ },
982
+
983
+ delegateYield: function(iterable, resultName, nextLoc) {
984
+ this.delegate = {
985
+ iterator: values(iterable),
986
+ resultName: resultName,
987
+ nextLoc: nextLoc
988
+ };
989
+
990
+ if (this.method === "next") {
991
+ // Deliberately forget the last sent value so that we don't
992
+ // accidentally pass it on to the delegate.
993
+ this.arg = undefined$1;
994
+ }
995
+
996
+ return ContinueSentinel;
997
+ }
998
+ };
999
+
1000
+ // Regardless of whether this script is executing as a CommonJS module
1001
+ // or not, return the runtime object so that we can declare the variable
1002
+ // regeneratorRuntime in the outer scope, which allows this module to be
1003
+ // injected easily by `bin/regenerator --include-runtime script.js`.
1004
+ return exports;
1005
+
1006
+ }(
1007
+ // If this script is executing as a CommonJS module, use module.exports
1008
+ // as the regeneratorRuntime namespace. Otherwise create a new empty
1009
+ // object. Either way, the resulting object will be used to initialize
1010
+ // the regeneratorRuntime variable at the top of this file.
1011
+ module.exports
1012
+ ));
1013
+
1014
+ try {
1015
+ regeneratorRuntime = runtime;
1016
+ } catch (accidentalStrictMode) {
1017
+ // This module should not be running in strict mode, so the above
1018
+ // assignment should always work unless something is misconfigured. Just
1019
+ // in case runtime.js accidentally runs in strict mode, in modern engines
1020
+ // we can explicitly access globalThis. In older engines we can escape
1021
+ // strict mode using a global Function call. This could conceivably fail
1022
+ // if a Content Security Policy forbids using Function, but in that case
1023
+ // the proper solution is to fix the accidental strict mode problem. If
1024
+ // you've misconfigured your bundler to force strict mode and applied a
1025
+ // CSP to forbid Function, and you're not willing to fix either of those
1026
+ // problems, please detail your unique predicament in a GitHub issue.
1027
+ if (typeof globalThis === "object") {
1028
+ globalThis.regeneratorRuntime = runtime;
1029
+ } else {
1030
+ Function("r", "regeneratorRuntime = r")(runtime);
1031
+ }
1032
+ }
1033
+ }(runtime));
1034
+
1035
+ var regenerator = runtime.exports;
1036
+
1037
+ function normalizeStringPasswordToMap(password) {
1038
+ return typeof password === 'string' ? {
1039
+ 1: password
1040
+ } : password;
1041
+ }
1042
+
1043
+ var FronteggConfig = /*#__PURE__*/function () {
1044
+ function FronteggConfig() {
1045
+ _classCallCheck(this, FronteggConfig);
1046
+
1047
+ var _a, _b, _c;
1048
+
1049
+ this.authRoutes = {};
1050
+ this._clientId = (_a = process.env['FRONTEGG_CLIENT_ID']) !== null && _a !== void 0 ? _a : '';
1051
+ this._cookieName = (_b = process.env['FRONTEGG_COOKIE_NAME']) !== null && _b !== void 0 ? _b : "fe_session";
1052
+ this._password = (_c = process.env['FRONTEGG_ENCRYPTION_PASSWORD']) !== null && _c !== void 0 ? _c : '';
1053
+ this._passwordsAsMap = normalizeStringPasswordToMap(this._password);
1054
+ }
1055
+
1056
+ _createClass(FronteggConfig, [{
1057
+ key: "cookieName",
1058
+ get: function get() {
1059
+ return this._cookieName;
1060
+ }
1061
+ }, {
1062
+ key: "password",
1063
+ get: function get() {
1064
+ return this._password;
1065
+ }
1066
+ }, {
1067
+ key: "clientId",
1068
+ get: function get() {
1069
+ return this._clientId;
1070
+ }
1071
+ }, {
1072
+ key: "baseUrlHost",
1073
+ get: function get() {
1074
+ var _a;
1075
+
1076
+ return new URL((_a = process.env['FRONTEGG_BASE_URL']) !== null && _a !== void 0 ? _a : '').hostname;
1077
+ }
1078
+ }, {
1079
+ key: "appUrl",
1080
+ get: function get() {
1081
+ var _a;
1082
+
1083
+ return (_a = process.env['FRONTEGG_APP_URL']) !== null && _a !== void 0 ? _a : 'http://localhost:3000';
1084
+ }
1085
+ }, {
1086
+ key: "cookieDomain",
1087
+ get: function get() {
1088
+ var _a;
1089
+
1090
+ return new URL((_a = process.env['FRONTEGG_APP_URL']) !== null && _a !== void 0 ? _a : '').hostname.replace(/:(\d)+$/, '');
1091
+ }
1092
+ }, {
1093
+ key: "getJwtPublicKey",
1094
+ value: function getJwtPublicKey() {
1095
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
1096
+ var response, data, publicKey;
1097
+ return regenerator.wrap(function _callee$(_context) {
1098
+ while (1) {
1099
+ switch (_context.prev = _context.next) {
1100
+ case 0:
1101
+ if (this._jwtPublicKey) {
1102
+ _context.next = 11;
1103
+ break;
1104
+ }
1105
+
1106
+ _context.next = 3;
1107
+ return fetch("".concat(process.env['FRONTEGG_BASE_URL'], "/.well-known/jwks.json"));
1108
+
1109
+ case 3:
1110
+ response = _context.sent;
1111
+ _context.next = 6;
1112
+ return response.json();
1113
+
1114
+ case 6:
1115
+ data = _context.sent;
1116
+ publicKey = data.keys.find(function (key) {
1117
+ return key.kty === 'RSA';
1118
+ });
1119
+ _context.next = 10;
1120
+ return jose.importJWK(publicKey);
1121
+
1122
+ case 10:
1123
+ this._jwtPublicKey = _context.sent;
1124
+
1125
+ case 11:
1126
+ return _context.abrupt("return", this._jwtPublicKey);
1127
+
1128
+ case 12:
1129
+ case "end":
1130
+ return _context.stop();
1131
+ }
1132
+ }
1133
+ }, _callee, this);
1134
+ }));
1135
+ }
1136
+ }, {
1137
+ key: "passwordsAsMap",
1138
+ get: function get() {
1139
+ return this._passwordsAsMap;
1140
+ }
1141
+ }]);
1142
+
1143
+ return FronteggConfig;
1144
+ }();
1145
+
1146
+ var fronteggConfig = new FronteggConfig();
1147
+
1148
+ function _arrayLikeToArray$1(arr, len) {
1149
+ if (len == null || len > arr.length) len = arr.length;
1150
+
1151
+ for (var i = 0, arr2 = new Array(len); i < len; i++) {
1152
+ arr2[i] = arr[i];
1153
+ }
1154
+
1155
+ return arr2;
1156
+ }
1157
+
1158
+ function _arrayWithoutHoles(arr) {
1159
+ if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
1160
+ }
1161
+
1162
+ function _iterableToArray(iter) {
1163
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1164
+ }
1165
+
1166
+ function _unsupportedIterableToArray$1(o, minLen) {
1167
+ if (!o) return;
1168
+ if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
1169
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1170
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1171
+ if (n === "Map" || n === "Set") return Array.from(o);
1172
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
1173
+ }
1174
+
1175
+ function _nonIterableSpread() {
1176
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1177
+ }
1178
+
1179
+ function _toConsumableArray(arr) {
1180
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread();
1181
+ }
1182
+
1183
+ function FronteggRouter() {
1184
+ return '';
1185
+ }
1186
+ function FronteggRouterProps(context) {
1187
+ var routesObj = Object.assign(Object.assign({}, reduxStore.authInitialState.routes), fronteggConfig.authRoutes);
1188
+ var routesArr = Object.keys(routesObj).reduce(function (p, key) {
1189
+ return [].concat(_toConsumableArray(p), [routesObj[key]]);
1190
+ }, []);
1191
+
1192
+ var _parse = url.parse(context.req.url, true),
1193
+ pathname = _parse.pathname;
1194
+
1195
+ if (!pathname || pathname.startsWith('/_next/data')) {
1196
+ var query = context.req.query[Object.keys(context.req.query)[0]];
1197
+ pathname = "/".concat(Array.isArray(query) ? query.join('/') : query);
1198
+ }
1199
+
1200
+ var notFound = routesArr.indexOf(pathname) === -1;
1201
+ return {
1202
+ notFound: notFound,
1203
+ props: {}
1204
+ };
1205
+ }
1206
+
1207
+ function _arrayWithHoles(arr) {
1208
+ if (Array.isArray(arr)) return arr;
1209
+ }
1210
+
1211
+ function _iterableToArrayLimit(arr, i) {
1212
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
1213
+
1214
+ if (_i == null) return;
1215
+ var _arr = [];
1216
+ var _n = true;
1217
+ var _d = false;
1218
+
1219
+ var _s, _e;
1220
+
1221
+ try {
1222
+ for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
1223
+ _arr.push(_s.value);
1224
+
1225
+ if (i && _arr.length === i) break;
1226
+ }
1227
+ } catch (err) {
1228
+ _d = true;
1229
+ _e = err;
1230
+ } finally {
1231
+ try {
1232
+ if (!_n && _i["return"] != null) _i["return"]();
1233
+ } finally {
1234
+ if (_d) throw _e;
1235
+ }
1236
+ }
1237
+
1238
+ return _arr;
1239
+ }
1240
+
1241
+ function _nonIterableRest() {
1242
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1243
+ }
1244
+
1245
+ function _slicedToArray(arr, i) {
1246
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest();
1247
+ }
1248
+
1249
+ function _defineProperty(obj, key, value) {
1250
+ if (key in obj) {
1251
+ Object.defineProperty(obj, key, {
1252
+ value: value,
1253
+ enumerable: true,
1254
+ configurable: true,
1255
+ writable: true
1256
+ });
1257
+ } else {
1258
+ obj[key] = value;
1259
+ }
1260
+
1261
+ return obj;
1262
+ }
1263
+
1264
+ function rewriteCookieProperty(header, config, property) {
1265
+ if (Array.isArray(header)) {
1266
+ return header.map(function (headerElement) {
1267
+ return rewriteCookieProperty(headerElement, config, property);
1268
+ });
1269
+ }
1270
+
1271
+ return header.replace(new RegExp('(;\\s*' + property + '=)([^;]+)', 'i'), function (match, prefix, previousValue) {
1272
+ var newValue;
1273
+
1274
+ if (previousValue in config) {
1275
+ newValue = config[previousValue];
1276
+ } else if ('*' in config) {
1277
+ newValue = config['*'];
1278
+ } else {
1279
+ // no match, return previous value
1280
+ return match;
1281
+ }
1282
+
1283
+ if (newValue) {
1284
+ // replace value
1285
+ return prefix + newValue;
1286
+ } else {
1287
+ // remove value
1288
+ return '';
1289
+ }
1290
+ });
1291
+ }
1292
+
1293
+ function refreshToken(ctx) {
1294
+ var _a;
1295
+
1296
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
1297
+ var request, headers, cookies, refreshTokenKey, cookieKey, response, data, rewriteCookieDomainConfig, cookieHeader, newSetCookie, _yield$createSessionF, _yield$createSessionF2, session, decodedJwt, isSecured, cookieValue;
1298
+
1299
+ return regenerator.wrap(function _callee$(_context) {
1300
+ while (1) {
1301
+ switch (_context.prev = _context.next) {
1302
+ case 0:
1303
+ _context.prev = 0;
1304
+ request = ctx.req;
1305
+
1306
+ if (request) {
1307
+ _context.next = 4;
1308
+ break;
1309
+ }
1310
+
1311
+ return _context.abrupt("return", null);
1312
+
1313
+ case 4:
1314
+ headers = request.headers;
1315
+ cookies = request.cookies;
1316
+ refreshTokenKey = "fe_refresh_".concat(fronteggConfig.clientId).replace(/-/g, '');
1317
+ cookieKey = Object.keys(cookies).find(function (cookie) {
1318
+ return cookie.replace(/-/g, '') === refreshTokenKey;
1319
+ });
1320
+
1321
+ if (!cookieKey) {
1322
+ _context.next = 36;
1323
+ break;
1324
+ }
1325
+
1326
+ _context.next = 11;
1327
+ return fetch("".concat(process.env['FRONTEGG_BASE_URL'], "/frontegg").concat(restApi.fronteggRefreshTokenUrl), {
1328
+ method: 'POST',
1329
+ credentials: 'include',
1330
+ body: '{}',
1331
+ headers: {
1332
+ 'accept-encoding': headers['accept-encoding'],
1333
+ 'accept-language': headers['accept-language'],
1334
+ cookie: headers['cookie'],
1335
+ accept: headers['accept'],
1336
+ 'user-agent': headers['user-agent'],
1337
+ connection: headers['connection'],
1338
+ 'cache-control': headers['cache-control']
1339
+ }
1340
+ });
1341
+
1342
+ case 11:
1343
+ response = _context.sent;
1344
+
1345
+ if (!response.ok) {
1346
+ _context.next = 36;
1347
+ break;
1348
+ }
1349
+
1350
+ _context.next = 15;
1351
+ return response.text();
1352
+
1353
+ case 15:
1354
+ data = _context.sent;
1355
+ rewriteCookieDomainConfig = _defineProperty({}, fronteggConfig.baseUrlHost, fronteggConfig.cookieDomain); // @ts-ignore
1356
+
1357
+ cookieHeader = response.headers.raw()['set-cookie'];
1358
+ newSetCookie = rewriteCookieProperty(cookieHeader, rewriteCookieDomainConfig, 'domain');
1359
+ _context.next = 21;
1360
+ return createSessionFromAccessToken(data);
1361
+
1362
+ case 21:
1363
+ _yield$createSessionF = _context.sent;
1364
+ _yield$createSessionF2 = _slicedToArray(_yield$createSessionF, 2);
1365
+ session = _yield$createSessionF2[0];
1366
+ decodedJwt = _yield$createSessionF2[1];
1367
+
1368
+ if (session) {
1369
+ _context.next = 27;
1370
+ break;
1371
+ }
1372
+
1373
+ return _context.abrupt("return", null);
1374
+
1375
+ case 27:
1376
+ isSecured = new URL(fronteggConfig.appUrl).protocol === 'https:';
1377
+ cookieValue = cookie__default["default"].serialize(fronteggConfig.cookieName, session, {
1378
+ expires: new Date(decodedJwt.exp * 1000),
1379
+ httpOnly: true,
1380
+ domain: fronteggConfig.cookieDomain,
1381
+ path: '/',
1382
+ sameSite: isSecured ? 'none' : undefined,
1383
+ secure: isSecured
1384
+ });
1385
+
1386
+ if (cookieValue.length > 4096) {
1387
+ console.error("@frontegg/nextjs: Cookie length is too big ".concat(cookieValue.length, ", browsers will refuse it. Try to remove some data."));
1388
+ }
1389
+
1390
+ if (typeof newSetCookie === 'string') {
1391
+ newSetCookie = [newSetCookie];
1392
+ }
1393
+
1394
+ newSetCookie.push(cookieValue);
1395
+ (_a = ctx.res) === null || _a === void 0 ? void 0 : _a.setHeader('set-cookie', newSetCookie);
1396
+ return _context.abrupt("return", {
1397
+ accessToken: JSON.parse(data).accessToken,
1398
+ user: decodedJwt
1399
+ });
1400
+
1401
+ case 36:
1402
+ return _context.abrupt("return", null);
1403
+
1404
+ case 39:
1405
+ _context.prev = 39;
1406
+ _context.t0 = _context["catch"](0);
1407
+ console.log(_context.t0);
1408
+ return _context.abrupt("return", null);
1409
+
1410
+ case 43:
1411
+ case "end":
1412
+ return _context.stop();
1413
+ }
1414
+ }
1415
+ }, _callee, null, [[0, 39]]);
1416
+ }));
1417
+ }
1418
+ function addToCookies(cookieValue, res) {
1419
+ var _a;
1420
+
1421
+ var existingSetCookie = (_a = res.getHeader('set-cookie')) !== null && _a !== void 0 ? _a : [];
1422
+
1423
+ if (typeof existingSetCookie === 'string') {
1424
+ existingSetCookie = [existingSetCookie];
1425
+ }
1426
+
1427
+ res.setHeader('set-cookie', [].concat(_toConsumableArray(existingSetCookie), [cookieValue]));
1428
+ }
1429
+ function removeCookies(cookieName, isSecured, cookieDomain, res) {
1430
+ var _a;
1431
+
1432
+ var cookieValue = cookie__default["default"].serialize(cookieName, '', {
1433
+ expires: new Date(),
1434
+ httpOnly: true,
1435
+ domain: cookieDomain,
1436
+ path: '/',
1437
+ sameSite: isSecured ? 'none' : undefined,
1438
+ secure: isSecured
1439
+ });
1440
+ var existingSetCookie = (_a = res.getHeader('set-cookie')) !== null && _a !== void 0 ? _a : [];
1441
+
1442
+ if (typeof existingSetCookie === 'string') {
1443
+ existingSetCookie = [existingSetCookie];
1444
+ }
1445
+
1446
+ res.setHeader('set-cookie', [].concat(_toConsumableArray(existingSetCookie), [cookieValue]));
1447
+ }
1448
+ function createSessionFromAccessToken(output) {
1449
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee2() {
1450
+ var _JSON$parse, accessToken, decodedJwt, session;
1451
+
1452
+ return regenerator.wrap(function _callee2$(_context2) {
1453
+ while (1) {
1454
+ switch (_context2.prev = _context2.next) {
1455
+ case 0:
1456
+ _context2.prev = 0;
1457
+ _JSON$parse = JSON.parse(output), accessToken = _JSON$parse.accessToken;
1458
+ decodedJwt = jose.decodeJwt(accessToken);
1459
+ decodedJwt.expiresIn = Math.floor((decodedJwt.exp * 1000 - Date.now()) / 1000);
1460
+ _context2.next = 6;
1461
+ return ironSession.sealData(accessToken, {
1462
+ password: fronteggConfig.passwordsAsMap,
1463
+ ttl: decodedJwt.exp
1464
+ });
1465
+
1466
+ case 6:
1467
+ session = _context2.sent;
1468
+ return _context2.abrupt("return", [session, decodedJwt]);
1469
+
1470
+ case 10:
1471
+ _context2.prev = 10;
1472
+ _context2.t0 = _context2["catch"](0);
1473
+ return _context2.abrupt("return", []);
1474
+
1475
+ case 13:
1476
+ case "end":
1477
+ return _context2.stop();
1478
+ }
1479
+ }
1480
+ }, _callee2, null, [[0, 10]]);
1481
+ }));
1482
+ }
1483
+ var modifySetCookieIfUnsecure = function modifySetCookieIfUnsecure(setCookieValue, isSecured) {
1484
+ if (!setCookieValue) {
1485
+ return setCookieValue;
1486
+ }
1487
+
1488
+ if (setCookieValue.length > 0) {
1489
+ return setCookieValue.map(function (c) {
1490
+ var cookie = c.split('; ');
1491
+
1492
+ if (isSecured) {
1493
+ return c;
1494
+ }
1495
+
1496
+ return cookie.filter(function (property) {
1497
+ return property !== 'Secure' && property !== 'SameSite=None';
1498
+ }).join('; ');
1499
+ });
1500
+ }
1501
+
1502
+ return setCookieValue;
1503
+ };
1504
+
1505
+ var withFronteggApp = function withFronteggApp(app, options) {
1506
+ var _a, _b;
1507
+
1508
+ var originalGetInitialProps = app.getInitialProps;
1509
+
1510
+ app.getInitialProps = function (appContext) {
1511
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
1512
+ var _c, _d, ctx, Component, session;
1513
+
1514
+ return regenerator.wrap(function _callee$(_context) {
1515
+ while (1) {
1516
+ switch (_context.prev = _context.next) {
1517
+ case 0:
1518
+ ctx = appContext.ctx, Component = appContext.Component;
1519
+
1520
+ if (!(((_d = (_c = ctx.req) === null || _c === void 0 ? void 0 : _c.url) === null || _d === void 0 ? void 0 : _d.indexOf('/_next/data/')) === -1)) {
1521
+ _context.next = 39;
1522
+ break;
1523
+ }
1524
+
1525
+ _context.next = 4;
1526
+ return refreshToken(ctx);
1527
+
1528
+ case 4:
1529
+ session = _context.sent;
1530
+ appContext.session = session;
1531
+
1532
+ if (process.env['FRONTEGG_APP_URL']) {
1533
+ _context.next = 8;
1534
+ break;
1535
+ }
1536
+
1537
+ throw Error('@frontegg/nextjs: .env.local must contain FRONTEGG_APP_URL');
1538
+
1539
+ case 8:
1540
+ if (process.env['FRONTEGG_BASE_URL']) {
1541
+ _context.next = 10;
1542
+ break;
1543
+ }
1544
+
1545
+ throw Error('@frontegg/nextjs: .env.local must contain FRONTEGG_BASE_URL');
1546
+
1547
+ case 10:
1548
+ if (process.env['FRONTEGG_CLIENT_ID']) {
1549
+ _context.next = 12;
1550
+ break;
1551
+ }
1552
+
1553
+ throw Error('@frontegg/nextjs: .env.local must contain FRONTEGG_CLIENT_ID');
1554
+
1555
+ case 12:
1556
+ _context.t0 = Object;
1557
+ _context.t1 = Object;
1558
+ _context.t2 = Object;
1559
+ _context.t3 = {};
1560
+
1561
+ if (!originalGetInitialProps) {
1562
+ _context.next = 22;
1563
+ break;
1564
+ }
1565
+
1566
+ _context.next = 19;
1567
+ return originalGetInitialProps(appContext);
1568
+
1569
+ case 19:
1570
+ _context.t4 = _context.sent;
1571
+ _context.next = 23;
1572
+ break;
1573
+
1574
+ case 22:
1575
+ _context.t4 = {};
1576
+
1577
+ case 23:
1578
+ _context.t5 = _context.t4;
1579
+ _context.t6 = _context.t2.assign.call(_context.t2, _context.t3, _context.t5);
1580
+
1581
+ if (!Component.getInitialProps) {
1582
+ _context.next = 31;
1583
+ break;
1584
+ }
1585
+
1586
+ _context.next = 28;
1587
+ return Component.getInitialProps(ctx);
1588
+
1589
+ case 28:
1590
+ _context.t7 = _context.sent;
1591
+ _context.next = 32;
1592
+ break;
1593
+
1594
+ case 31:
1595
+ _context.t7 = {};
1596
+
1597
+ case 32:
1598
+ _context.t8 = _context.t7;
1599
+ _context.t9 = _context.t1.assign.call(_context.t1, _context.t6, _context.t8);
1600
+ _context.t10 = {
1601
+ session: session,
1602
+ envAppUrl: process.env['FRONTEGG_APP_URL'],
1603
+ envBaseUrl: process.env['FRONTEGG_BASE_URL'],
1604
+ envClientId: process.env['FRONTEGG_CLIENT_ID']
1605
+ };
1606
+ _context.t11 = _context.t0.assign.call(_context.t0, _context.t9, _context.t10);
1607
+ return _context.abrupt("return", {
1608
+ pageProps: _context.t11
1609
+ });
1610
+
1611
+ case 39:
1612
+ appContext.session = null;
1613
+ _context.t12 = Object;
1614
+ _context.t13 = Object;
1615
+ _context.t14 = {};
1616
+
1617
+ if (!originalGetInitialProps) {
1618
+ _context.next = 49;
1619
+ break;
1620
+ }
1621
+
1622
+ _context.next = 46;
1623
+ return originalGetInitialProps(appContext);
1624
+
1625
+ case 46:
1626
+ _context.t15 = _context.sent;
1627
+ _context.next = 50;
1628
+ break;
1629
+
1630
+ case 49:
1631
+ _context.t15 = {};
1632
+
1633
+ case 50:
1634
+ _context.t16 = _context.t15;
1635
+ _context.t17 = _context.t13.assign.call(_context.t13, _context.t14, _context.t16);
1636
+
1637
+ if (!Component.getInitialProps) {
1638
+ _context.next = 58;
1639
+ break;
1640
+ }
1641
+
1642
+ _context.next = 55;
1643
+ return Component.getInitialProps(ctx);
1644
+
1645
+ case 55:
1646
+ _context.t18 = _context.sent;
1647
+ _context.next = 59;
1648
+ break;
1649
+
1650
+ case 58:
1651
+ _context.t18 = {};
1652
+
1653
+ case 59:
1654
+ _context.t19 = _context.t18;
1655
+ _context.t20 = _context.t12.assign.call(_context.t12, _context.t17, _context.t19);
1656
+ return _context.abrupt("return", {
1657
+ pageProps: _context.t20
1658
+ });
1659
+
1660
+ case 62:
1661
+ case "end":
1662
+ return _context.stop();
1663
+ }
1664
+ }
1665
+ }, _callee);
1666
+ }));
1667
+ };
1668
+
1669
+ fronteggConfig.authRoutes = (_b = (_a = options === null || options === void 0 ? void 0 : options.authOptions) === null || _a === void 0 ? void 0 : _a.routes) !== null && _b !== void 0 ? _b : {};
1670
+
1671
+ function CustomFronteggApp(appProps) {
1672
+ return jsxRuntime.jsx(FronteggProvider, Object.assign({}, options, {
1673
+ session: appProps.pageProps.session,
1674
+ envAppUrl: appProps.pageProps.envAppUrl,
1675
+ envBaseUrl: appProps.pageProps.envBaseUrl,
1676
+ envClientId: appProps.pageProps.envClientId
1677
+ }, {
1678
+ children: app(appProps)
1679
+ }));
1680
+ }
1681
+
1682
+ CustomFronteggApp.getInitialProps = app.getInitialProps;
1683
+ return CustomFronteggApp;
1684
+ };
1685
+
1686
+ function getSession(req) {
1687
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
1688
+ var sealFromCookies, jwt, publicKey, _yield$jwtVerify, payload, session;
1689
+
1690
+ return regenerator.wrap(function _callee$(_context) {
1691
+ while (1) {
1692
+ switch (_context.prev = _context.next) {
1693
+ case 0:
1694
+ _context.prev = 0;
1695
+ sealFromCookies = cookie__default["default"].parse(req.headers.cookie || '')[fronteggConfig.cookieName];
1696
+
1697
+ if (sealFromCookies) {
1698
+ _context.next = 4;
1699
+ break;
1700
+ }
1701
+
1702
+ return _context.abrupt("return", undefined);
1703
+
1704
+ case 4:
1705
+ _context.next = 6;
1706
+ return ironSession.unsealData(sealFromCookies, {
1707
+ password: fronteggConfig.passwordsAsMap
1708
+ });
1709
+
1710
+ case 6:
1711
+ jwt = _context.sent;
1712
+ _context.next = 9;
1713
+ return fronteggConfig.getJwtPublicKey();
1714
+
1715
+ case 9:
1716
+ publicKey = _context.sent;
1717
+ _context.next = 12;
1718
+ return jose.jwtVerify(jwt, publicKey);
1719
+
1720
+ case 12:
1721
+ _yield$jwtVerify = _context.sent;
1722
+ payload = _yield$jwtVerify.payload;
1723
+ session = {
1724
+ accessToken: jwt,
1725
+ user: payload
1726
+ };
1727
+
1728
+ if (!(session.user.exp * 1000 < Date.now())) {
1729
+ _context.next = 17;
1730
+ break;
1731
+ }
1732
+
1733
+ return _context.abrupt("return", undefined);
1734
+
1735
+ case 17:
1736
+ return _context.abrupt("return", session);
1737
+
1738
+ case 20:
1739
+ _context.prev = 20;
1740
+ _context.t0 = _context["catch"](0);
1741
+ console.error(_context.t0);
1742
+ return _context.abrupt("return", undefined);
1743
+
1744
+ case 24:
1745
+ case "end":
1746
+ return _context.stop();
1747
+ }
1748
+ }
1749
+ }, _callee, null, [[0, 20]]);
1750
+ }));
1751
+ }
1752
+ function withSSRSession(handler) {
1753
+ var _this = this;
1754
+
1755
+ return function (context) {
1756
+ return __awaiter(_this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee2() {
1757
+ var session;
1758
+ return regenerator.wrap(function _callee2$(_context2) {
1759
+ while (1) {
1760
+ switch (_context2.prev = _context2.next) {
1761
+ case 0:
1762
+ _context2.next = 2;
1763
+ return getSession(context.req);
1764
+
1765
+ case 2:
1766
+ session = _context2.sent;
1767
+
1768
+ if (!session) {
1769
+ _context2.next = 7;
1770
+ break;
1771
+ }
1772
+
1773
+ return _context2.abrupt("return", handler(context, session));
1774
+
1775
+ case 7:
1776
+ return _context2.abrupt("return", {
1777
+ redirect: {
1778
+ permanent: false,
1779
+ destination: "/account/login?redirectUrl=".concat(encodeURIComponent(context.req.url))
1780
+ },
1781
+ props: {}
1782
+ });
1783
+
1784
+ case 8:
1785
+ case "end":
1786
+ return _context2.stop();
1787
+ }
1788
+ }
1789
+ }, _callee2);
1790
+ }));
1791
+ };
1792
+ }
1793
+
1794
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
1795
+
1796
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
1797
+
1798
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
1799
+ /**
1800
+ * @see https://www.npmjs.com/package/http-proxy
1801
+ */
1802
+
1803
+ var proxy = httpProxy__default["default"].createProxyServer({
1804
+ target: process.env['FRONTEGG_BASE_URL']
1805
+ });
1806
+ /**
1807
+ * Please refer to the following links for the specification document for HTTP.
1808
+ * @see https://tools.ietf.org/html/rfc7231
1809
+ * @see https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
1810
+ */
1811
+
1812
+ var hasRequestBodyMethods = ['HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'PATCH'];
1813
+ /**
1814
+ * If pattern information matching the input url information is found in the `pathRewrite` array,
1815
+ * the url value is partially replaced with the `pathRewrite.replaceStr` value.
1816
+ * @param url
1817
+ * @param pathRewrite
1818
+ */
1819
+
1820
+ var rewritePath = function rewritePath(url, pathRewrite) {
1821
+ if (Array.isArray(pathRewrite)) {
1822
+ var _iterator = _createForOfIteratorHelper(pathRewrite),
1823
+ _step;
1824
+
1825
+ try {
1826
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
1827
+ var item = _step.value;
1828
+ var patternStr = item.patternStr,
1829
+ replaceStr = item.replaceStr;
1830
+ var pattern = RegExp(patternStr);
1831
+
1832
+ if (pattern.test(url)) {
1833
+ return url.replace(pattern, replaceStr);
1834
+ }
1835
+ }
1836
+ } catch (err) {
1837
+ _iterator.e(err);
1838
+ } finally {
1839
+ _iterator.f();
1840
+ }
1841
+ } else {
1842
+ // tslint:disable-next-line:forin
1843
+ for (var _patternStr in pathRewrite) {
1844
+ var _pattern = RegExp(_patternStr);
1845
+
1846
+ var path = pathRewrite[_patternStr];
1847
+
1848
+ if (_pattern.test(url)) {
1849
+ return url.replace(_pattern, path);
1850
+ }
1851
+ }
1852
+ }
1853
+
1854
+ return url;
1855
+ };
1856
+ /**
1857
+ * Next.js HTTP Proxy Middleware
1858
+ * @see https://nextjs.org/docs/api-routes/api-middlewares
1859
+ * @param {NextApiRequest} req
1860
+ * @param {NextApiResponse} res
1861
+ */
1862
+
1863
+ function fronteggMiddleware(req, res) {
1864
+ var _this = this;
1865
+
1866
+ return new Promise(function (resolve, reject) {
1867
+ var pathRewrite = [{
1868
+ patternStr: '^/api/',
1869
+ replaceStr: '/'
1870
+ }];
1871
+
1872
+ if (pathRewrite) {
1873
+ req.url = rewritePath(req.url, pathRewrite);
1874
+ }
1875
+
1876
+ if (hasRequestBodyMethods.indexOf(req.method) >= 0 && typeof req.body === 'object') {
1877
+ req.body = JSON.stringify(req.body);
1878
+ }
1879
+
1880
+ var isSecured = new URL(fronteggConfig.appUrl).protocol === 'https:';
1881
+ proxy.once('proxyReq', function (proxyReq, req) {
1882
+ if (hasRequestBodyMethods.indexOf(req.method) >= 0 && typeof req.body === 'string') {
1883
+ proxyReq.write(req.body);
1884
+ proxyReq.end();
1885
+ }
1886
+ }).once('proxyRes', function (proxyRes, req, serverResponse) {
1887
+ proxyRes.headers['set-cookie'] = modifySetCookieIfUnsecure(proxyRes.headers['set-cookie'], isSecured);
1888
+ var _end = res.end;
1889
+ var buffer = new Buffer('');
1890
+ proxyRes.on('data', function (chunk) {
1891
+ buffer = Buffer.concat([buffer, chunk]);
1892
+ }).on('end', function () {
1893
+ return __awaiter(_this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
1894
+ var _a, _b, output, isLogout, _yield$createSessionF, _yield$createSessionF2, session, decodedJwt, cookieValue;
1895
+
1896
+ return regenerator.wrap(function _callee$(_context) {
1897
+ while (1) {
1898
+ switch (_context.prev = _context.next) {
1899
+ case 0:
1900
+ output = buffer.toString('utf-8');
1901
+ isLogout = (_a = req === null || req === void 0 ? void 0 : req.url) === null || _a === void 0 ? void 0 : _a.endsWith((_b = restApi.fronteggAuthApiRoutes.find(function (path) {
1902
+ return path.endsWith('/logout');
1903
+ })) !== null && _b !== void 0 ? _b : '/logout');
1904
+
1905
+ if (!isLogout) {
1906
+ _context.next = 6;
1907
+ break;
1908
+ }
1909
+
1910
+ removeCookies(fronteggConfig.cookieName, isSecured, fronteggConfig.cookieDomain, serverResponse);
1911
+ _context.next = 13;
1912
+ break;
1913
+
1914
+ case 6:
1915
+ _context.next = 8;
1916
+ return createSessionFromAccessToken(output);
1917
+
1918
+ case 8:
1919
+ _yield$createSessionF = _context.sent;
1920
+ _yield$createSessionF2 = _slicedToArray(_yield$createSessionF, 2);
1921
+ session = _yield$createSessionF2[0];
1922
+ decodedJwt = _yield$createSessionF2[1];
1923
+
1924
+ if (session) {
1925
+ cookieValue = cookie__default["default"].serialize(fronteggConfig.cookieName, session, {
1926
+ expires: new Date(decodedJwt.exp * 1000),
1927
+ httpOnly: true,
1928
+ domain: fronteggConfig.cookieDomain,
1929
+ path: '/',
1930
+ sameSite: isSecured ? 'none' : undefined,
1931
+ secure: isSecured
1932
+ });
1933
+
1934
+ if (cookieValue.length > 4096) {
1935
+ console.error("@frontegg/nextjs: Cookie length is too big ".concat(cookieValue.length, ", browsers will refuse it. Try to remove some data."));
1936
+ }
1937
+
1938
+ addToCookies(cookieValue, serverResponse);
1939
+ }
1940
+
1941
+ case 13:
1942
+ res.setHeader('content-length', output.length);
1943
+ res.setHeader('content-encoding', ''); // @ts-ignore
1944
+
1945
+ _end.apply(res, [output]);
1946
+
1947
+ case 16:
1948
+ case "end":
1949
+ return _context.stop();
1950
+ }
1951
+ }
1952
+ }, _callee);
1953
+ }));
1954
+ }); // disable default behavior to read jwt
1955
+ // @ts-ignore
1956
+
1957
+ serverResponse.write = function () {
1958
+ return undefined;
1959
+ }; // @ts-ignore
1960
+
1961
+
1962
+ serverResponse.end = function () {
1963
+ return undefined;
1964
+ };
1965
+ }).once('error', reject).web(req, res, {
1966
+ changeOrigin: true,
1967
+ cookieDomainRewrite: _defineProperty({}, fronteggConfig.baseUrlHost, fronteggConfig.cookieDomain) // ...serverOptions
1968
+
1969
+ });
1970
+ });
1971
+ }
1972
+
1973
+ Object.defineProperty(exports, 'AdminPortal', {
1974
+ enumerable: true,
1975
+ get: function () { return adminPortal.AdminPortal; }
1976
+ });
1977
+ exports.AuthorizedContent = AuthorizedContent;
1978
+ exports.Connector = Connector;
1979
+ exports.FronteggConfig = fronteggConfig;
1980
+ exports.FronteggProvider = FronteggProvider;
1981
+ exports.FronteggRouter = FronteggRouter;
1982
+ exports.FronteggRouterProps = FronteggRouterProps;
1983
+ exports.fronteggMiddleware = fronteggMiddleware;
1984
+ exports.getSession = getSession;
1985
+ exports.rewritePath = rewritePath;
1986
+ exports.withFronteggApp = withFronteggApp;
1987
+ exports.withSSRSession = withSSRSession;
1988
+ Object.keys(reactHooks).forEach(function (k) {
1989
+ if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1990
+ enumerable: true,
1991
+ get: function () { return reactHooks[k]; }
1992
+ });
1993
+ });
1994
+ Object.keys(types).forEach(function (k) {
1995
+ if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1996
+ enumerable: true,
1997
+ get: function () { return types[k]; }
1998
+ });
1999
+ });