@frontegg/nextjs 6.7.8 → 6.7.9-alpha.3757258005

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/FronteggClientProviderNext13-b55f477b.js +127 -0
  3. package/FronteggClientProviderNext13-b55f477b.js.map +1 -0
  4. package/FronteggConfig-7ae86562.js +123 -0
  5. package/FronteggConfig-7ae86562.js.map +1 -0
  6. package/FronteggProvider.d.ts +3 -12
  7. package/FronteggProviderNoSSR.d.ts +2 -4
  8. package/README.md +56 -4
  9. package/api-70f0e81e.js +58 -0
  10. package/api-70f0e81e.js.map +1 -0
  11. package/client/FronteggAppRouter.d.ts +10 -0
  12. package/client/FronteggClientProviderNext13.d.ts +3 -0
  13. package/client/index.d.ts +2 -0
  14. package/client/index.js +63 -0
  15. package/client/index.js.map +1 -0
  16. package/{FronteggConfig.d.ts → common/FronteggConfig.d.ts} +1 -1
  17. package/{api.d.ts → common/api.d.ts} +0 -0
  18. package/{AppContext.d.ts → common/client/AppContext.d.ts} +0 -0
  19. package/common/client/ExpireInListener.d.ts +1 -0
  20. package/common/client/FronteggBaseProvider.d.ts +3 -0
  21. package/common/client/createOrGetFronteggApp.d.ts +11 -0
  22. package/common/client/hooks/index.d.ts +1 -0
  23. package/common/client/hooks/useRequestAuthorizeSSR.d.ts +9 -0
  24. package/common/client/index.d.ts +4 -0
  25. package/{consts.d.ts → common/consts.d.ts} +0 -0
  26. package/common/getMeAndTenants.d.ts +2 -0
  27. package/{helpers.d.ts → common/helpers.d.ts} +7 -9
  28. package/common/index.d.ts +6 -0
  29. package/common/index.js +20 -0
  30. package/common/index.js.map +1 -0
  31. package/common/types.d.ts +74 -0
  32. package/common/utils/createGetSession.d.ts +7 -0
  33. package/common/utils/getCookieFromRequest.d.ts +2 -0
  34. package/common/utils/index.d.ts +3 -0
  35. package/common/utils/parseCookie.d.ts +1 -0
  36. package/createGetSession-81b1748e.js +50 -0
  37. package/createGetSession-81b1748e.js.map +1 -0
  38. package/edge/getSessionOnEdge.d.ts +2 -0
  39. package/edge/index.d.ts +1 -0
  40. package/edge/index.js +29 -0
  41. package/edge/index.js.map +1 -0
  42. package/getCookieFromRequest-624c37b5.js +28 -0
  43. package/getCookieFromRequest-624c37b5.js.map +1 -0
  44. package/helpers-dac4dc7b.js +189 -0
  45. package/helpers-dac4dc7b.js.map +1 -0
  46. package/index.d.ts +1 -2
  47. package/index.js +1168 -0
  48. package/index.js.map +1 -0
  49. package/package.json +17 -12
  50. package/refreshToken.d.ts +3 -0
  51. package/server/FronteggProviderNext13.d.ts +3 -0
  52. package/server/getSessionNext13.d.ts +4 -0
  53. package/server/index.d.ts +2 -0
  54. package/server/index.js +86 -0
  55. package/server/index.js.map +1 -0
  56. package/session.d.ts +4 -8
  57. package/withFronteggApp.d.ts +10 -8
  58. package/index.cjs.js +0 -2747
  59. package/index.esm.js +0 -2691
  60. package/types.d.ts +0 -53
package/index.esm.js DELETED
@@ -1,2691 +0,0 @@
1
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
2
- import { createContext, useRef, useCallback, useMemo, useEffect, useContext } from 'react';
3
- import { AppHolder, initialize } from '@frontegg/js';
4
- export { AdminPortal } from '@frontegg/js';
5
- import { createFronteggStore, authInitialState } from '@frontegg/redux-store';
6
- import { FronteggStoreProvider, useAuthUserOrNull, useAuthActions, useLoginWithRedirect, useLoginActions } from '@frontegg/react-hooks';
7
- export * from '@frontegg/react-hooks';
8
- import { fronteggAuthApiRoutes, ContextHolder, fronteggUsersUrl, fronteggTenantsUrl, fronteggRefreshTokenUrl, fronteggSilentRefreshTokenUrl } from '@frontegg/rest-api';
9
- export { ContextHolder } from '@frontegg/rest-api';
10
- import { useRouter } from 'next/router';
11
- import { importJWK, jwtVerify, decodeJwt } from 'jose';
12
- import { parse } from 'url';
13
- import cookie from 'cookie';
14
- import { unsealData, sealData } from 'iron-session';
15
- import * as zlib from 'zlib';
16
- import httpProxy from 'http-proxy';
17
- export * from '@frontegg/types';
18
-
19
- /******************************************************************************
20
- Copyright (c) Microsoft Corporation.
21
-
22
- Permission to use, copy, modify, and/or distribute this software for any
23
- purpose with or without fee is hereby granted.
24
-
25
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
26
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
27
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
28
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
29
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
30
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
31
- PERFORMANCE OF THIS SOFTWARE.
32
- ***************************************************************************** */
33
-
34
- function __rest(s, e) {
35
- var t = {};
36
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
- t[p] = s[p];
38
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
- t[p[i]] = s[p[i]];
42
- }
43
- return t;
44
- }
45
-
46
- function __awaiter(thisArg, _arguments, P, generator) {
47
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
48
- return new (P || (P = Promise))(function (resolve, reject) {
49
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
50
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
51
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
52
- step((generator = generator.apply(thisArg, _arguments || [])).next());
53
- });
54
- }
55
-
56
- var AppContext = /*#__PURE__*/createContext(null);
57
-
58
- var Connector$1 = function Connector(_a) {
59
- var _b;
60
-
61
- var router = _a.router,
62
- appName = _a.appName,
63
- hostedLoginBox = _a.hostedLoginBox,
64
- customLoginBox = _a.customLoginBox,
65
- user = _a.user,
66
- tenants = _a.tenants,
67
- session = _a.session,
68
- props = __rest(_a, ["router", "appName", "hostedLoginBox", "customLoginBox", "user", "tenants", "session"]);
69
-
70
- var _ref = session !== null && session !== void 0 ? session : {},
71
- accessToken = _ref.accessToken,
72
- refreshToken = _ref.refreshToken;
73
-
74
- var isSSR = typeof window === 'undefined';
75
- var storeHolder = useRef({});
76
- var baseName = (_b = props.basename) !== null && _b !== void 0 ? _b : router.basePath;
77
- var onRedirectTo = useCallback(function (_path, opts) {
78
- var path = _path;
79
-
80
- if (path.startsWith(baseName)) {
81
- path = path.substring(baseName.length);
82
- }
83
-
84
- if (opts === null || opts === void 0 ? void 0 : opts.preserveQueryParams) {
85
- path = "".concat(path).concat(window.location.search);
86
- }
87
-
88
- if ((opts === null || opts === void 0 ? void 0 : opts.refresh) && !isSSR) {
89
- // @ts-ignore
90
- window.Cypress ? router.push(path) : window.location.href = path;
91
- } else {
92
- (opts === null || opts === void 0 ? void 0 : opts.replace) ? router.replace(path) : router.push(path);
93
- }
94
- }, []);
95
- var contextOptions = useMemo(function () {
96
- return Object.assign(Object.assign({
97
- requestCredentials: 'include'
98
- }, props.contextOptions), {
99
- baseUrl: function baseUrl(path) {
100
- if (fronteggAuthApiRoutes.indexOf(path) !== -1 || path.endsWith('/postlogin') || path.endsWith('/prelogin') || path === '/oauth/token') {
101
- return "".concat(props.envAppUrl, "/api");
102
- } else {
103
- return props.envBaseUrl;
104
- }
105
- },
106
- clientId: props.envClientId
107
- });
108
- }, [props.envAppUrl, props.envBaseUrl, props.envClientId, props.contextOptions]);
109
- var authOptions = useMemo(function () {
110
- var _a, _b, _c, _d;
111
-
112
- var tenantsState = tenants ? Object.assign({
113
- tenantTree: null,
114
- subTenants: [],
115
- tenants: tenants,
116
- loading: false
117
- }, (_a = props.authOptions) === null || _a === void 0 ? void 0 : _a.tenantsState) : undefined;
118
- var userData = user ? Object.assign(Object.assign(Object.assign({}, user), {
119
- accessToken: accessToken !== null && accessToken !== void 0 ? accessToken : '',
120
- refreshToken: refreshToken !== null && refreshToken !== void 0 ? refreshToken : undefined
121
- }), (_b = props.authOptions) === null || _b === void 0 ? void 0 : _b.user) : null;
122
- return Object.assign(Object.assign({}, props.authOptions), {
123
- onRedirectTo: onRedirectTo,
124
- isLoading: false,
125
- isAuthenticated: !!session,
126
- hostedLoginBox: hostedLoginBox !== null && hostedLoginBox !== void 0 ? hostedLoginBox : false,
127
- disableSilentRefresh: (_d = (_c = props.authOptions) === null || _c === void 0 ? void 0 : _c.disableSilentRefresh) !== null && _d !== void 0 ? _d : false,
128
- user: userData,
129
- tenantsState: tenantsState
130
- });
131
- }, [accessToken, hostedLoginBox, onRedirectTo, props.authOptions, refreshToken, session, tenants, user]);
132
- var sharedStore = useMemo(function () {
133
- var _a;
134
-
135
- return createFronteggStore({
136
- context: contextOptions
137
- }, storeHolder.current, props.previewMode, authOptions, {
138
- auth: authOptions !== null && authOptions !== void 0 ? authOptions : {},
139
- audits: (_a = props.auditsOptions) !== null && _a !== void 0 ? _a : {}
140
- }, false, props.urlStrategy);
141
- }, [authOptions, contextOptions, props.auditsOptions, props.previewMode, props.urlStrategy]);
142
- var app = useMemo(function () {
143
- var _a;
144
-
145
- var createdApp;
146
-
147
- try {
148
- createdApp = AppHolder.getInstance(appName !== null && appName !== void 0 ? appName : 'default');
149
- createdApp.store = sharedStore;
150
- } catch (e) {
151
- createdApp = initialize(Object.assign(Object.assign({}, props), {
152
- store: sharedStore,
153
- hostedLoginBox: hostedLoginBox !== null && hostedLoginBox !== void 0 ? hostedLoginBox : false,
154
- customLoginBox: customLoginBox !== null && customLoginBox !== void 0 ? customLoginBox : false,
155
- basename: (_a = props.basename) !== null && _a !== void 0 ? _a : baseName,
156
- authOptions: authOptions,
157
- contextOptions: contextOptions,
158
- onRedirectTo: onRedirectTo
159
- }), appName !== null && appName !== void 0 ? appName : 'default');
160
- }
161
-
162
- return createdApp;
163
- }, [appName, props, hostedLoginBox, baseName, onRedirectTo, contextOptions, customLoginBox, authOptions, sharedStore]);
164
- ContextHolder.setOnRedirectTo(onRedirectTo);
165
- useEffect(function () {
166
- app === null || app === void 0 ? void 0 : app.store.dispatch({
167
- type: 'auth/requestAuthorizeSSR',
168
- payload: {
169
- accessToken: accessToken,
170
- user: user ? Object.assign(Object.assign({}, user), {
171
- refreshToken: refreshToken
172
- }) : null,
173
- tenants: tenants
174
- }
175
- });
176
- }, [app]);
177
- return jsx(AppContext.Provider, Object.assign({
178
- value: app
179
- }, {
180
- children: jsx(FronteggStoreProvider, Object.assign({}, Object.assign(Object.assign({}, props), {
181
- app: app
182
- }), {
183
- children: props.children
184
- }))
185
- }));
186
- };
187
-
188
- var ExpireInListener$1 = function ExpireInListener() {
189
- var user = useAuthUserOrNull();
190
- var actions = useAuthActions();
191
- useEffect(function () {
192
- if (user && (user === null || user === void 0 ? void 0 : user.expiresIn) == null) {
193
- actions.setUser(Object.assign(Object.assign({}, user), {
194
- expiresIn: Math.floor((user['exp'] * 1000 - Date.now()) / 1000)
195
- }));
196
- }
197
- }, [actions, user]); // eslint-disable-next-line react/jsx-no-useless-fragment
198
-
199
- return jsx(Fragment, {});
200
- };
201
-
202
- var FronteggNextJSProvider$1 = function FronteggNextJSProvider(props) {
203
- var router = useRouter();
204
- return jsxs(Connector$1, Object.assign({}, props, {
205
- router: router
206
- }, {
207
- children: [jsx(ExpireInListener$1, {}), props.children]
208
- }));
209
- };
210
-
211
- var FronteggProvider = function FronteggProvider(props) {
212
- return jsx(FronteggNextJSProvider$1, Object.assign({}, props, {
213
- framework: 'nextjs'
214
- }, {
215
- children: props.children
216
- }));
217
- };
218
-
219
- var Connector = function Connector(_props) {
220
- var _a;
221
-
222
- var router = _props.router,
223
- appName = _props.appName,
224
- hostedLoginBox = _props.hostedLoginBox;
225
- _props.customLoginBox;
226
- var props = __rest(_props, ["router", "appName", "hostedLoginBox", "customLoginBox"]);
227
-
228
- var isSSR = typeof window === 'undefined';
229
- var baseName = (_a = props.basename) !== null && _a !== void 0 ? _a : router.basePath;
230
- var onRedirectTo = useCallback(function (_path, opts) {
231
- var path = _path;
232
-
233
- if (path.startsWith(baseName)) {
234
- path = path.substring(baseName.length);
235
- }
236
-
237
- if (opts === null || opts === void 0 ? void 0 : opts.preserveQueryParams) {
238
- path = "".concat(path).concat(window.location.search);
239
- }
240
-
241
- if ((opts === null || opts === void 0 ? void 0 : opts.refresh) && !isSSR) {
242
- // @ts-ignore
243
- window.Cypress ? router.push(path) : window.location.href = path;
244
- } else {
245
- (opts === null || opts === void 0 ? void 0 : opts.replace) ? router.replace(path) : router.push(path);
246
- }
247
- }, []);
248
- var app = useMemo(function () {
249
- var _a;
250
-
251
- var createdApp;
252
-
253
- try {
254
- createdApp = AppHolder.getInstance(appName !== null && appName !== void 0 ? appName : 'default');
255
- } catch (e) {
256
- createdApp = initialize(Object.assign(Object.assign({}, props), {
257
- hostedLoginBox: hostedLoginBox !== null && hostedLoginBox !== void 0 ? hostedLoginBox : false,
258
- basename: (_a = props.basename) !== null && _a !== void 0 ? _a : baseName,
259
- authOptions: Object.assign(Object.assign({}, props.authOptions), {
260
- onRedirectTo: onRedirectTo
261
- }),
262
- contextOptions: Object.assign({
263
- requestCredentials: 'include'
264
- }, props.contextOptions),
265
- onRedirectTo: onRedirectTo
266
- }), appName !== null && appName !== void 0 ? appName : 'default');
267
- }
268
-
269
- return createdApp;
270
- }, [appName, props, hostedLoginBox, baseName, onRedirectTo]);
271
- ContextHolder.setOnRedirectTo(onRedirectTo);
272
- useEffect(function () {
273
- app.store.dispatch({
274
- type: 'auth/requestAuthorize',
275
- payload: true
276
- });
277
- }, [app]);
278
- return jsx(AppContext.Provider, Object.assign({
279
- value: app
280
- }, {
281
- children: jsx(FronteggStoreProvider, Object.assign({}, Object.assign(Object.assign({}, props), {
282
- app: app
283
- }), {
284
- children: props.children
285
- }))
286
- }));
287
- };
288
-
289
- var ExpireInListener = function ExpireInListener() {
290
- var user = useAuthUserOrNull();
291
- var actions = useAuthActions();
292
- useEffect(function () {
293
- if (user && (user === null || user === void 0 ? void 0 : user.expiresIn) == null) {
294
- actions.setUser(Object.assign(Object.assign({}, user), {
295
- expiresIn: Math.floor((user['exp'] * 1000 - Date.now()) / 1000)
296
- }));
297
- }
298
- }, [actions, user]); // eslint-disable-next-line react/jsx-no-useless-fragment
299
-
300
- return jsx(Fragment, {});
301
- };
302
-
303
- var FronteggNextJSProvider = function FronteggNextJSProvider(props) {
304
- var router = useRouter();
305
- return jsxs(Connector, Object.assign({}, props, {
306
- router: router
307
- }, {
308
- children: [jsx(ExpireInListener, {}), props.children]
309
- }));
310
- };
311
-
312
- var FronteggProviderNoSSR = function FronteggProviderNoSSR(props) {
313
- return jsx(FronteggNextJSProvider, Object.assign({}, props, {
314
- framework: 'nextjs'
315
- }, {
316
- children: props.children
317
- }));
318
- };
319
-
320
- 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; } } }; }
321
-
322
- 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); }
323
-
324
- 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; }
325
- var AuthorizedContent = function AuthorizedContent(props) {
326
- var _a, _b;
327
-
328
- var isAuthorized = true; // Initially
329
-
330
- var user = useAuthUserOrNull();
331
-
332
- if (!(user === null || user === void 0 ? void 0 : user.superUser)) {
333
- if (props.requiredPermissions) {
334
- if (!(user === null || user === void 0 ? void 0 : user.permissions) || (user === null || user === void 0 ? void 0 : user.permissions.length) === 0) {
335
- isAuthorized = false;
336
- }
337
-
338
- var _iterator = _createForOfIteratorHelper$1(props.requiredPermissions),
339
- _step;
340
-
341
- try {
342
- var _loop = function _loop() {
343
- var permission = _step.value;
344
-
345
- if (!((_a = user === null || user === void 0 ? void 0 : user.permissions) === null || _a === void 0 ? void 0 : _a.find(function (_ref) {
346
- var key = _ref.key;
347
- return key === permission;
348
- }))) {
349
- isAuthorized = false;
350
- }
351
- };
352
-
353
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
354
- _loop();
355
- }
356
- } catch (err) {
357
- _iterator.e(err);
358
- } finally {
359
- _iterator.f();
360
- }
361
- }
362
-
363
- if (props.requiredRoles) {
364
- if (!(user === null || user === void 0 ? void 0 : user.roles) || (user === null || user === void 0 ? void 0 : user.roles.length) === 0) {
365
- isAuthorized = false;
366
- }
367
-
368
- var _iterator2 = _createForOfIteratorHelper$1(props.requiredRoles),
369
- _step2;
370
-
371
- try {
372
- var _loop2 = function _loop2() {
373
- var role = _step2.value;
374
-
375
- if (!((_b = user === null || user === void 0 ? void 0 : user.roles) === null || _b === void 0 ? void 0 : _b.find(function (_ref2) {
376
- var key = _ref2.key;
377
- return key === role;
378
- }))) {
379
- isAuthorized = false;
380
- }
381
- };
382
-
383
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
384
- _loop2();
385
- }
386
- } catch (err) {
387
- _iterator2.e(err);
388
- } finally {
389
- _iterator2.f();
390
- }
391
- }
392
- }
393
-
394
- if (typeof props.render === 'function') {
395
- return jsx(Fragment, {
396
- children: props.render(isAuthorized)
397
- });
398
- }
399
-
400
- return isAuthorized ? jsx(Fragment, {
401
- children: props.children
402
- }) : null;
403
- };
404
-
405
- function _classCallCheck(instance, Constructor) {
406
- if (!(instance instanceof Constructor)) {
407
- throw new TypeError("Cannot call a class as a function");
408
- }
409
- }
410
-
411
- function _defineProperties(target, props) {
412
- for (var i = 0; i < props.length; i++) {
413
- var descriptor = props[i];
414
- descriptor.enumerable = descriptor.enumerable || false;
415
- descriptor.configurable = true;
416
- if ("value" in descriptor) descriptor.writable = true;
417
- Object.defineProperty(target, descriptor.key, descriptor);
418
- }
419
- }
420
-
421
- function _createClass(Constructor, protoProps, staticProps) {
422
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
423
- if (staticProps) _defineProperties(Constructor, staticProps);
424
- Object.defineProperty(Constructor, "prototype", {
425
- writable: false
426
- });
427
- return Constructor;
428
- }
429
-
430
- var runtime = {exports: {}};
431
-
432
- /**
433
- * Copyright (c) 2014-present, Facebook, Inc.
434
- *
435
- * This source code is licensed under the MIT license found in the
436
- * LICENSE file in the root directory of this source tree.
437
- */
438
-
439
- (function (module) {
440
- var runtime = (function (exports) {
441
-
442
- var Op = Object.prototype;
443
- var hasOwn = Op.hasOwnProperty;
444
- var undefined$1; // More compressible than void 0.
445
- var $Symbol = typeof Symbol === "function" ? Symbol : {};
446
- var iteratorSymbol = $Symbol.iterator || "@@iterator";
447
- var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
448
- var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
449
-
450
- function define(obj, key, value) {
451
- Object.defineProperty(obj, key, {
452
- value: value,
453
- enumerable: true,
454
- configurable: true,
455
- writable: true
456
- });
457
- return obj[key];
458
- }
459
- try {
460
- // IE 8 has a broken Object.defineProperty that only works on DOM objects.
461
- define({}, "");
462
- } catch (err) {
463
- define = function(obj, key, value) {
464
- return obj[key] = value;
465
- };
466
- }
467
-
468
- function wrap(innerFn, outerFn, self, tryLocsList) {
469
- // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
470
- var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
471
- var generator = Object.create(protoGenerator.prototype);
472
- var context = new Context(tryLocsList || []);
473
-
474
- // The ._invoke method unifies the implementations of the .next,
475
- // .throw, and .return methods.
476
- generator._invoke = makeInvokeMethod(innerFn, self, context);
477
-
478
- return generator;
479
- }
480
- exports.wrap = wrap;
481
-
482
- // Try/catch helper to minimize deoptimizations. Returns a completion
483
- // record like context.tryEntries[i].completion. This interface could
484
- // have been (and was previously) designed to take a closure to be
485
- // invoked without arguments, but in all the cases we care about we
486
- // already have an existing method we want to call, so there's no need
487
- // to create a new function object. We can even get away with assuming
488
- // the method takes exactly one argument, since that happens to be true
489
- // in every case, so we don't have to touch the arguments object. The
490
- // only additional allocation required is the completion record, which
491
- // has a stable shape and so hopefully should be cheap to allocate.
492
- function tryCatch(fn, obj, arg) {
493
- try {
494
- return { type: "normal", arg: fn.call(obj, arg) };
495
- } catch (err) {
496
- return { type: "throw", arg: err };
497
- }
498
- }
499
-
500
- var GenStateSuspendedStart = "suspendedStart";
501
- var GenStateSuspendedYield = "suspendedYield";
502
- var GenStateExecuting = "executing";
503
- var GenStateCompleted = "completed";
504
-
505
- // Returning this object from the innerFn has the same effect as
506
- // breaking out of the dispatch switch statement.
507
- var ContinueSentinel = {};
508
-
509
- // Dummy constructor functions that we use as the .constructor and
510
- // .constructor.prototype properties for functions that return Generator
511
- // objects. For full spec compliance, you may wish to configure your
512
- // minifier not to mangle the names of these two functions.
513
- function Generator() {}
514
- function GeneratorFunction() {}
515
- function GeneratorFunctionPrototype() {}
516
-
517
- // This is a polyfill for %IteratorPrototype% for environments that
518
- // don't natively support it.
519
- var IteratorPrototype = {};
520
- define(IteratorPrototype, iteratorSymbol, function () {
521
- return this;
522
- });
523
-
524
- var getProto = Object.getPrototypeOf;
525
- var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
526
- if (NativeIteratorPrototype &&
527
- NativeIteratorPrototype !== Op &&
528
- hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
529
- // This environment has a native %IteratorPrototype%; use it instead
530
- // of the polyfill.
531
- IteratorPrototype = NativeIteratorPrototype;
532
- }
533
-
534
- var Gp = GeneratorFunctionPrototype.prototype =
535
- Generator.prototype = Object.create(IteratorPrototype);
536
- GeneratorFunction.prototype = GeneratorFunctionPrototype;
537
- define(Gp, "constructor", GeneratorFunctionPrototype);
538
- define(GeneratorFunctionPrototype, "constructor", GeneratorFunction);
539
- GeneratorFunction.displayName = define(
540
- GeneratorFunctionPrototype,
541
- toStringTagSymbol,
542
- "GeneratorFunction"
543
- );
544
-
545
- // Helper for defining the .next, .throw, and .return methods of the
546
- // Iterator interface in terms of a single ._invoke method.
547
- function defineIteratorMethods(prototype) {
548
- ["next", "throw", "return"].forEach(function(method) {
549
- define(prototype, method, function(arg) {
550
- return this._invoke(method, arg);
551
- });
552
- });
553
- }
554
-
555
- exports.isGeneratorFunction = function(genFun) {
556
- var ctor = typeof genFun === "function" && genFun.constructor;
557
- return ctor
558
- ? ctor === GeneratorFunction ||
559
- // For the native GeneratorFunction constructor, the best we can
560
- // do is to check its .name property.
561
- (ctor.displayName || ctor.name) === "GeneratorFunction"
562
- : false;
563
- };
564
-
565
- exports.mark = function(genFun) {
566
- if (Object.setPrototypeOf) {
567
- Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
568
- } else {
569
- genFun.__proto__ = GeneratorFunctionPrototype;
570
- define(genFun, toStringTagSymbol, "GeneratorFunction");
571
- }
572
- genFun.prototype = Object.create(Gp);
573
- return genFun;
574
- };
575
-
576
- // Within the body of any async function, `await x` is transformed to
577
- // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
578
- // `hasOwn.call(value, "__await")` to determine if the yielded value is
579
- // meant to be awaited.
580
- exports.awrap = function(arg) {
581
- return { __await: arg };
582
- };
583
-
584
- function AsyncIterator(generator, PromiseImpl) {
585
- function invoke(method, arg, resolve, reject) {
586
- var record = tryCatch(generator[method], generator, arg);
587
- if (record.type === "throw") {
588
- reject(record.arg);
589
- } else {
590
- var result = record.arg;
591
- var value = result.value;
592
- if (value &&
593
- typeof value === "object" &&
594
- hasOwn.call(value, "__await")) {
595
- return PromiseImpl.resolve(value.__await).then(function(value) {
596
- invoke("next", value, resolve, reject);
597
- }, function(err) {
598
- invoke("throw", err, resolve, reject);
599
- });
600
- }
601
-
602
- return PromiseImpl.resolve(value).then(function(unwrapped) {
603
- // When a yielded Promise is resolved, its final value becomes
604
- // the .value of the Promise<{value,done}> result for the
605
- // current iteration.
606
- result.value = unwrapped;
607
- resolve(result);
608
- }, function(error) {
609
- // If a rejected Promise was yielded, throw the rejection back
610
- // into the async generator function so it can be handled there.
611
- return invoke("throw", error, resolve, reject);
612
- });
613
- }
614
- }
615
-
616
- var previousPromise;
617
-
618
- function enqueue(method, arg) {
619
- function callInvokeWithMethodAndArg() {
620
- return new PromiseImpl(function(resolve, reject) {
621
- invoke(method, arg, resolve, reject);
622
- });
623
- }
624
-
625
- return previousPromise =
626
- // If enqueue has been called before, then we want to wait until
627
- // all previous Promises have been resolved before calling invoke,
628
- // so that results are always delivered in the correct order. If
629
- // enqueue has not been called before, then it is important to
630
- // call invoke immediately, without waiting on a callback to fire,
631
- // so that the async generator function has the opportunity to do
632
- // any necessary setup in a predictable way. This predictability
633
- // is why the Promise constructor synchronously invokes its
634
- // executor callback, and why async functions synchronously
635
- // execute code before the first await. Since we implement simple
636
- // async functions in terms of async generators, it is especially
637
- // important to get this right, even though it requires care.
638
- previousPromise ? previousPromise.then(
639
- callInvokeWithMethodAndArg,
640
- // Avoid propagating failures to Promises returned by later
641
- // invocations of the iterator.
642
- callInvokeWithMethodAndArg
643
- ) : callInvokeWithMethodAndArg();
644
- }
645
-
646
- // Define the unified helper method that is used to implement .next,
647
- // .throw, and .return (see defineIteratorMethods).
648
- this._invoke = enqueue;
649
- }
650
-
651
- defineIteratorMethods(AsyncIterator.prototype);
652
- define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
653
- return this;
654
- });
655
- exports.AsyncIterator = AsyncIterator;
656
-
657
- // Note that simple async functions are implemented on top of
658
- // AsyncIterator objects; they just return a Promise for the value of
659
- // the final result produced by the iterator.
660
- exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
661
- if (PromiseImpl === void 0) PromiseImpl = Promise;
662
-
663
- var iter = new AsyncIterator(
664
- wrap(innerFn, outerFn, self, tryLocsList),
665
- PromiseImpl
666
- );
667
-
668
- return exports.isGeneratorFunction(outerFn)
669
- ? iter // If outerFn is a generator, return the full iterator.
670
- : iter.next().then(function(result) {
671
- return result.done ? result.value : iter.next();
672
- });
673
- };
674
-
675
- function makeInvokeMethod(innerFn, self, context) {
676
- var state = GenStateSuspendedStart;
677
-
678
- return function invoke(method, arg) {
679
- if (state === GenStateExecuting) {
680
- throw new Error("Generator is already running");
681
- }
682
-
683
- if (state === GenStateCompleted) {
684
- if (method === "throw") {
685
- throw arg;
686
- }
687
-
688
- // Be forgiving, per 25.3.3.3.3 of the spec:
689
- // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
690
- return doneResult();
691
- }
692
-
693
- context.method = method;
694
- context.arg = arg;
695
-
696
- while (true) {
697
- var delegate = context.delegate;
698
- if (delegate) {
699
- var delegateResult = maybeInvokeDelegate(delegate, context);
700
- if (delegateResult) {
701
- if (delegateResult === ContinueSentinel) continue;
702
- return delegateResult;
703
- }
704
- }
705
-
706
- if (context.method === "next") {
707
- // Setting context._sent for legacy support of Babel's
708
- // function.sent implementation.
709
- context.sent = context._sent = context.arg;
710
-
711
- } else if (context.method === "throw") {
712
- if (state === GenStateSuspendedStart) {
713
- state = GenStateCompleted;
714
- throw context.arg;
715
- }
716
-
717
- context.dispatchException(context.arg);
718
-
719
- } else if (context.method === "return") {
720
- context.abrupt("return", context.arg);
721
- }
722
-
723
- state = GenStateExecuting;
724
-
725
- var record = tryCatch(innerFn, self, context);
726
- if (record.type === "normal") {
727
- // If an exception is thrown from innerFn, we leave state ===
728
- // GenStateExecuting and loop back for another invocation.
729
- state = context.done
730
- ? GenStateCompleted
731
- : GenStateSuspendedYield;
732
-
733
- if (record.arg === ContinueSentinel) {
734
- continue;
735
- }
736
-
737
- return {
738
- value: record.arg,
739
- done: context.done
740
- };
741
-
742
- } else if (record.type === "throw") {
743
- state = GenStateCompleted;
744
- // Dispatch the exception by looping back around to the
745
- // context.dispatchException(context.arg) call above.
746
- context.method = "throw";
747
- context.arg = record.arg;
748
- }
749
- }
750
- };
751
- }
752
-
753
- // Call delegate.iterator[context.method](context.arg) and handle the
754
- // result, either by returning a { value, done } result from the
755
- // delegate iterator, or by modifying context.method and context.arg,
756
- // setting context.delegate to null, and returning the ContinueSentinel.
757
- function maybeInvokeDelegate(delegate, context) {
758
- var method = delegate.iterator[context.method];
759
- if (method === undefined$1) {
760
- // A .throw or .return when the delegate iterator has no .throw
761
- // method always terminates the yield* loop.
762
- context.delegate = null;
763
-
764
- if (context.method === "throw") {
765
- // Note: ["return"] must be used for ES3 parsing compatibility.
766
- if (delegate.iterator["return"]) {
767
- // If the delegate iterator has a return method, give it a
768
- // chance to clean up.
769
- context.method = "return";
770
- context.arg = undefined$1;
771
- maybeInvokeDelegate(delegate, context);
772
-
773
- if (context.method === "throw") {
774
- // If maybeInvokeDelegate(context) changed context.method from
775
- // "return" to "throw", let that override the TypeError below.
776
- return ContinueSentinel;
777
- }
778
- }
779
-
780
- context.method = "throw";
781
- context.arg = new TypeError(
782
- "The iterator does not provide a 'throw' method");
783
- }
784
-
785
- return ContinueSentinel;
786
- }
787
-
788
- var record = tryCatch(method, delegate.iterator, context.arg);
789
-
790
- if (record.type === "throw") {
791
- context.method = "throw";
792
- context.arg = record.arg;
793
- context.delegate = null;
794
- return ContinueSentinel;
795
- }
796
-
797
- var info = record.arg;
798
-
799
- if (! info) {
800
- context.method = "throw";
801
- context.arg = new TypeError("iterator result is not an object");
802
- context.delegate = null;
803
- return ContinueSentinel;
804
- }
805
-
806
- if (info.done) {
807
- // Assign the result of the finished delegate to the temporary
808
- // variable specified by delegate.resultName (see delegateYield).
809
- context[delegate.resultName] = info.value;
810
-
811
- // Resume execution at the desired location (see delegateYield).
812
- context.next = delegate.nextLoc;
813
-
814
- // If context.method was "throw" but the delegate handled the
815
- // exception, let the outer generator proceed normally. If
816
- // context.method was "next", forget context.arg since it has been
817
- // "consumed" by the delegate iterator. If context.method was
818
- // "return", allow the original .return call to continue in the
819
- // outer generator.
820
- if (context.method !== "return") {
821
- context.method = "next";
822
- context.arg = undefined$1;
823
- }
824
-
825
- } else {
826
- // Re-yield the result returned by the delegate method.
827
- return info;
828
- }
829
-
830
- // The delegate iterator is finished, so forget it and continue with
831
- // the outer generator.
832
- context.delegate = null;
833
- return ContinueSentinel;
834
- }
835
-
836
- // Define Generator.prototype.{next,throw,return} in terms of the
837
- // unified ._invoke helper method.
838
- defineIteratorMethods(Gp);
839
-
840
- define(Gp, toStringTagSymbol, "Generator");
841
-
842
- // A Generator should always return itself as the iterator object when the
843
- // @@iterator function is called on it. Some browsers' implementations of the
844
- // iterator prototype chain incorrectly implement this, causing the Generator
845
- // object to not be returned from this call. This ensures that doesn't happen.
846
- // See https://github.com/facebook/regenerator/issues/274 for more details.
847
- define(Gp, iteratorSymbol, function() {
848
- return this;
849
- });
850
-
851
- define(Gp, "toString", function() {
852
- return "[object Generator]";
853
- });
854
-
855
- function pushTryEntry(locs) {
856
- var entry = { tryLoc: locs[0] };
857
-
858
- if (1 in locs) {
859
- entry.catchLoc = locs[1];
860
- }
861
-
862
- if (2 in locs) {
863
- entry.finallyLoc = locs[2];
864
- entry.afterLoc = locs[3];
865
- }
866
-
867
- this.tryEntries.push(entry);
868
- }
869
-
870
- function resetTryEntry(entry) {
871
- var record = entry.completion || {};
872
- record.type = "normal";
873
- delete record.arg;
874
- entry.completion = record;
875
- }
876
-
877
- function Context(tryLocsList) {
878
- // The root entry object (effectively a try statement without a catch
879
- // or a finally block) gives us a place to store values thrown from
880
- // locations where there is no enclosing try statement.
881
- this.tryEntries = [{ tryLoc: "root" }];
882
- tryLocsList.forEach(pushTryEntry, this);
883
- this.reset(true);
884
- }
885
-
886
- exports.keys = function(object) {
887
- var keys = [];
888
- for (var key in object) {
889
- keys.push(key);
890
- }
891
- keys.reverse();
892
-
893
- // Rather than returning an object with a next method, we keep
894
- // things simple and return the next function itself.
895
- return function next() {
896
- while (keys.length) {
897
- var key = keys.pop();
898
- if (key in object) {
899
- next.value = key;
900
- next.done = false;
901
- return next;
902
- }
903
- }
904
-
905
- // To avoid creating an additional object, we just hang the .value
906
- // and .done properties off the next function object itself. This
907
- // also ensures that the minifier will not anonymize the function.
908
- next.done = true;
909
- return next;
910
- };
911
- };
912
-
913
- function values(iterable) {
914
- if (iterable) {
915
- var iteratorMethod = iterable[iteratorSymbol];
916
- if (iteratorMethod) {
917
- return iteratorMethod.call(iterable);
918
- }
919
-
920
- if (typeof iterable.next === "function") {
921
- return iterable;
922
- }
923
-
924
- if (!isNaN(iterable.length)) {
925
- var i = -1, next = function next() {
926
- while (++i < iterable.length) {
927
- if (hasOwn.call(iterable, i)) {
928
- next.value = iterable[i];
929
- next.done = false;
930
- return next;
931
- }
932
- }
933
-
934
- next.value = undefined$1;
935
- next.done = true;
936
-
937
- return next;
938
- };
939
-
940
- return next.next = next;
941
- }
942
- }
943
-
944
- // Return an iterator with no values.
945
- return { next: doneResult };
946
- }
947
- exports.values = values;
948
-
949
- function doneResult() {
950
- return { value: undefined$1, done: true };
951
- }
952
-
953
- Context.prototype = {
954
- constructor: Context,
955
-
956
- reset: function(skipTempReset) {
957
- this.prev = 0;
958
- this.next = 0;
959
- // Resetting context._sent for legacy support of Babel's
960
- // function.sent implementation.
961
- this.sent = this._sent = undefined$1;
962
- this.done = false;
963
- this.delegate = null;
964
-
965
- this.method = "next";
966
- this.arg = undefined$1;
967
-
968
- this.tryEntries.forEach(resetTryEntry);
969
-
970
- if (!skipTempReset) {
971
- for (var name in this) {
972
- // Not sure about the optimal order of these conditions:
973
- if (name.charAt(0) === "t" &&
974
- hasOwn.call(this, name) &&
975
- !isNaN(+name.slice(1))) {
976
- this[name] = undefined$1;
977
- }
978
- }
979
- }
980
- },
981
-
982
- stop: function() {
983
- this.done = true;
984
-
985
- var rootEntry = this.tryEntries[0];
986
- var rootRecord = rootEntry.completion;
987
- if (rootRecord.type === "throw") {
988
- throw rootRecord.arg;
989
- }
990
-
991
- return this.rval;
992
- },
993
-
994
- dispatchException: function(exception) {
995
- if (this.done) {
996
- throw exception;
997
- }
998
-
999
- var context = this;
1000
- function handle(loc, caught) {
1001
- record.type = "throw";
1002
- record.arg = exception;
1003
- context.next = loc;
1004
-
1005
- if (caught) {
1006
- // If the dispatched exception was caught by a catch block,
1007
- // then let that catch block handle the exception normally.
1008
- context.method = "next";
1009
- context.arg = undefined$1;
1010
- }
1011
-
1012
- return !! caught;
1013
- }
1014
-
1015
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
1016
- var entry = this.tryEntries[i];
1017
- var record = entry.completion;
1018
-
1019
- if (entry.tryLoc === "root") {
1020
- // Exception thrown outside of any try block that could handle
1021
- // it, so set the completion value of the entire function to
1022
- // throw the exception.
1023
- return handle("end");
1024
- }
1025
-
1026
- if (entry.tryLoc <= this.prev) {
1027
- var hasCatch = hasOwn.call(entry, "catchLoc");
1028
- var hasFinally = hasOwn.call(entry, "finallyLoc");
1029
-
1030
- if (hasCatch && hasFinally) {
1031
- if (this.prev < entry.catchLoc) {
1032
- return handle(entry.catchLoc, true);
1033
- } else if (this.prev < entry.finallyLoc) {
1034
- return handle(entry.finallyLoc);
1035
- }
1036
-
1037
- } else if (hasCatch) {
1038
- if (this.prev < entry.catchLoc) {
1039
- return handle(entry.catchLoc, true);
1040
- }
1041
-
1042
- } else if (hasFinally) {
1043
- if (this.prev < entry.finallyLoc) {
1044
- return handle(entry.finallyLoc);
1045
- }
1046
-
1047
- } else {
1048
- throw new Error("try statement without catch or finally");
1049
- }
1050
- }
1051
- }
1052
- },
1053
-
1054
- abrupt: function(type, arg) {
1055
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
1056
- var entry = this.tryEntries[i];
1057
- if (entry.tryLoc <= this.prev &&
1058
- hasOwn.call(entry, "finallyLoc") &&
1059
- this.prev < entry.finallyLoc) {
1060
- var finallyEntry = entry;
1061
- break;
1062
- }
1063
- }
1064
-
1065
- if (finallyEntry &&
1066
- (type === "break" ||
1067
- type === "continue") &&
1068
- finallyEntry.tryLoc <= arg &&
1069
- arg <= finallyEntry.finallyLoc) {
1070
- // Ignore the finally entry if control is not jumping to a
1071
- // location outside the try/catch block.
1072
- finallyEntry = null;
1073
- }
1074
-
1075
- var record = finallyEntry ? finallyEntry.completion : {};
1076
- record.type = type;
1077
- record.arg = arg;
1078
-
1079
- if (finallyEntry) {
1080
- this.method = "next";
1081
- this.next = finallyEntry.finallyLoc;
1082
- return ContinueSentinel;
1083
- }
1084
-
1085
- return this.complete(record);
1086
- },
1087
-
1088
- complete: function(record, afterLoc) {
1089
- if (record.type === "throw") {
1090
- throw record.arg;
1091
- }
1092
-
1093
- if (record.type === "break" ||
1094
- record.type === "continue") {
1095
- this.next = record.arg;
1096
- } else if (record.type === "return") {
1097
- this.rval = this.arg = record.arg;
1098
- this.method = "return";
1099
- this.next = "end";
1100
- } else if (record.type === "normal" && afterLoc) {
1101
- this.next = afterLoc;
1102
- }
1103
-
1104
- return ContinueSentinel;
1105
- },
1106
-
1107
- finish: function(finallyLoc) {
1108
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
1109
- var entry = this.tryEntries[i];
1110
- if (entry.finallyLoc === finallyLoc) {
1111
- this.complete(entry.completion, entry.afterLoc);
1112
- resetTryEntry(entry);
1113
- return ContinueSentinel;
1114
- }
1115
- }
1116
- },
1117
-
1118
- "catch": function(tryLoc) {
1119
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
1120
- var entry = this.tryEntries[i];
1121
- if (entry.tryLoc === tryLoc) {
1122
- var record = entry.completion;
1123
- if (record.type === "throw") {
1124
- var thrown = record.arg;
1125
- resetTryEntry(entry);
1126
- }
1127
- return thrown;
1128
- }
1129
- }
1130
-
1131
- // The context.catch method must only be called with a location
1132
- // argument that corresponds to a known catch block.
1133
- throw new Error("illegal catch attempt");
1134
- },
1135
-
1136
- delegateYield: function(iterable, resultName, nextLoc) {
1137
- this.delegate = {
1138
- iterator: values(iterable),
1139
- resultName: resultName,
1140
- nextLoc: nextLoc
1141
- };
1142
-
1143
- if (this.method === "next") {
1144
- // Deliberately forget the last sent value so that we don't
1145
- // accidentally pass it on to the delegate.
1146
- this.arg = undefined$1;
1147
- }
1148
-
1149
- return ContinueSentinel;
1150
- }
1151
- };
1152
-
1153
- // Regardless of whether this script is executing as a CommonJS module
1154
- // or not, return the runtime object so that we can declare the variable
1155
- // regeneratorRuntime in the outer scope, which allows this module to be
1156
- // injected easily by `bin/regenerator --include-runtime script.js`.
1157
- return exports;
1158
-
1159
- }(
1160
- // If this script is executing as a CommonJS module, use module.exports
1161
- // as the regeneratorRuntime namespace. Otherwise create a new empty
1162
- // object. Either way, the resulting object will be used to initialize
1163
- // the regeneratorRuntime variable at the top of this file.
1164
- module.exports
1165
- ));
1166
-
1167
- try {
1168
- regeneratorRuntime = runtime;
1169
- } catch (accidentalStrictMode) {
1170
- // This module should not be running in strict mode, so the above
1171
- // assignment should always work unless something is misconfigured. Just
1172
- // in case runtime.js accidentally runs in strict mode, in modern engines
1173
- // we can explicitly access globalThis. In older engines we can escape
1174
- // strict mode using a global Function call. This could conceivably fail
1175
- // if a Content Security Policy forbids using Function, but in that case
1176
- // the proper solution is to fix the accidental strict mode problem. If
1177
- // you've misconfigured your bundler to force strict mode and applied a
1178
- // CSP to forbid Function, and you're not willing to fix either of those
1179
- // problems, please detail your unique predicament in a GitHub issue.
1180
- if (typeof globalThis === "object") {
1181
- globalThis.regeneratorRuntime = runtime;
1182
- } else {
1183
- Function("r", "regeneratorRuntime = r")(runtime);
1184
- }
1185
- }
1186
- }(runtime));
1187
-
1188
- var regenerator = runtime.exports;
1189
-
1190
- function normalizeStringPasswordToMap(password) {
1191
- return typeof password === 'string' ? {
1192
- 1: password
1193
- } : password;
1194
- }
1195
-
1196
- var FronteggConfig = /*#__PURE__*/function () {
1197
- function FronteggConfig() {
1198
- _classCallCheck(this, FronteggConfig);
1199
-
1200
- var _a, _b, _c;
1201
-
1202
- this.authRoutes = {};
1203
- this.fronteggAppOptions = {};
1204
- this._clientId = (_a = process.env['FRONTEGG_CLIENT_ID']) !== null && _a !== void 0 ? _a : '';
1205
- this._cookieName = (_b = process.env['FRONTEGG_COOKIE_NAME']) !== null && _b !== void 0 ? _b : "fe_next_session";
1206
- this._password = (_c = process.env['FRONTEGG_ENCRYPTION_PASSWORD']) !== null && _c !== void 0 ? _c : '';
1207
- this._passwordsAsMap = normalizeStringPasswordToMap(this._password);
1208
- }
1209
-
1210
- _createClass(FronteggConfig, [{
1211
- key: "cookieName",
1212
- get: function get() {
1213
- return "".concat(this._cookieName, "-").concat(this._clientId.replace(/-/g, ''));
1214
- }
1215
- }, {
1216
- key: "password",
1217
- get: function get() {
1218
- return this._password;
1219
- }
1220
- }, {
1221
- key: "clientId",
1222
- get: function get() {
1223
- return this._clientId;
1224
- }
1225
- }, {
1226
- key: "baseUrlHost",
1227
- get: function get() {
1228
- var _a;
1229
-
1230
- return new URL((_a = process.env['FRONTEGG_BASE_URL']) !== null && _a !== void 0 ? _a : '').hostname;
1231
- }
1232
- }, {
1233
- key: "getEnvAppUrl",
1234
- value: function getEnvAppUrl() {
1235
- var url = undefined;
1236
-
1237
- if (process.env['FRONTEGG_APP_URL']) {
1238
- url = process.env['FRONTEGG_APP_URL'];
1239
- } else if (process.env['VERCEL'] && process.env['VERCEL_URL']) {
1240
- url = process.env['VERCEL_URL'];
1241
- }
1242
-
1243
- if (url && !url.startsWith('http')) {
1244
- var protocol = url.startsWith('localhost') ? 'http://' : 'https://';
1245
- url = "".concat(protocol).concat(url);
1246
- }
1247
-
1248
- return url;
1249
- }
1250
- }, {
1251
- key: "appUrl",
1252
- get: function get() {
1253
- var _a;
1254
-
1255
- return (_a = this.getEnvAppUrl()) !== null && _a !== void 0 ? _a : 'http://localhost:3000';
1256
- }
1257
- }, {
1258
- key: "appEnvConfig",
1259
- get: function get() {
1260
- return {
1261
- envAppUrl: this.getEnvAppUrl(),
1262
- envBaseUrl: process.env['FRONTEGG_BASE_URL'],
1263
- envClientId: process.env['FRONTEGG_CLIENT_ID']
1264
- };
1265
- }
1266
- }, {
1267
- key: "cookieDomain",
1268
- get: function get() {
1269
- var _a;
1270
-
1271
- return new URL((_a = this.getEnvAppUrl()) !== null && _a !== void 0 ? _a : '').hostname.replace(/:(\d)+$/, '');
1272
- }
1273
- }, {
1274
- key: "getJwtPublicKey",
1275
- value: function getJwtPublicKey() {
1276
- return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
1277
- var response, data, publicKey;
1278
- return regenerator.wrap(function _callee$(_context) {
1279
- while (1) {
1280
- switch (_context.prev = _context.next) {
1281
- case 0:
1282
- if (this._jwtPublicKey) {
1283
- _context.next = 11;
1284
- break;
1285
- }
1286
-
1287
- _context.next = 3;
1288
- return fetch("".concat(process.env['FRONTEGG_BASE_URL'], "/.well-known/jwks.json"));
1289
-
1290
- case 3:
1291
- response = _context.sent;
1292
- _context.next = 6;
1293
- return response.json();
1294
-
1295
- case 6:
1296
- data = _context.sent;
1297
- publicKey = data.keys.find(function (key) {
1298
- return key.kty === 'RSA';
1299
- });
1300
- _context.next = 10;
1301
- return importJWK(publicKey);
1302
-
1303
- case 10:
1304
- this._jwtPublicKey = _context.sent;
1305
-
1306
- case 11:
1307
- return _context.abrupt("return", this._jwtPublicKey);
1308
-
1309
- case 12:
1310
- case "end":
1311
- return _context.stop();
1312
- }
1313
- }
1314
- }, _callee, this);
1315
- }));
1316
- }
1317
- }, {
1318
- key: "passwordsAsMap",
1319
- get: function get() {
1320
- return this._passwordsAsMap;
1321
- }
1322
- }]);
1323
-
1324
- return FronteggConfig;
1325
- }();
1326
-
1327
- var fronteggConfig = new FronteggConfig();
1328
-
1329
- function _arrayLikeToArray$1(arr, len) {
1330
- if (len == null || len > arr.length) len = arr.length;
1331
-
1332
- for (var i = 0, arr2 = new Array(len); i < len; i++) {
1333
- arr2[i] = arr[i];
1334
- }
1335
-
1336
- return arr2;
1337
- }
1338
-
1339
- function _arrayWithoutHoles(arr) {
1340
- if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
1341
- }
1342
-
1343
- function _iterableToArray(iter) {
1344
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1345
- }
1346
-
1347
- function _unsupportedIterableToArray$1(o, minLen) {
1348
- if (!o) return;
1349
- if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
1350
- var n = Object.prototype.toString.call(o).slice(8, -1);
1351
- if (n === "Object" && o.constructor) n = o.constructor.name;
1352
- if (n === "Map" || n === "Set") return Array.from(o);
1353
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
1354
- }
1355
-
1356
- function _nonIterableSpread() {
1357
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1358
- }
1359
-
1360
- function _toConsumableArray(arr) {
1361
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread();
1362
- }
1363
-
1364
- function FronteggRouter() {
1365
- var app = useContext(AppContext);
1366
-
1367
- var _useRouter = useRouter(),
1368
- query = _useRouter.query,
1369
- replace = _useRouter.replace;
1370
-
1371
- var loginWithRedirect = useLoginWithRedirect();
1372
-
1373
- var _useLoginActions = useLoginActions(),
1374
- logout = _useLoginActions.logout;
1375
-
1376
- useEffect(function () {
1377
- if (!app) {
1378
- return;
1379
- }
1380
-
1381
- if (app.options.hostedLoginBox) {
1382
- var routesObj = Object.assign(Object.assign({}, authInitialState.routes), fronteggConfig.authRoutes);
1383
-
1384
- var _a = query,
1385
- pathArr = _a['frontegg-router'],
1386
- queryParams = __rest(_a, ['frontegg-router']);
1387
-
1388
- var pathname = "/".concat(pathArr.join('/'));
1389
-
1390
- if (pathname === routesObj.loginUrl) {
1391
- if (queryParams.redirectUrl) {
1392
- localStorage.setItem('FRONTEGG_AFTER_AUTH_REDIRECT_URL', "".concat(window.location.origin).concat(queryParams.redirectUrl));
1393
- }
1394
-
1395
- loginWithRedirect();
1396
- } else if (pathname === routesObj.logoutUrl) {
1397
- var _baseUrl = app.options.contextOptions.baseUrl;
1398
- var baseUrl = typeof _baseUrl === 'string' ? _baseUrl : _baseUrl('');
1399
- logout(function () {
1400
- window.location.href = "".concat(baseUrl, "/oauth/logout?post_logout_redirect_uri=").concat(encodeURIComponent(window.location.origin));
1401
- });
1402
- }
1403
- }
1404
- }, [app, query, loginWithRedirect, logout, replace]);
1405
- return '';
1406
- }
1407
- function FronteggRouterProps(context) {
1408
- var _a;
1409
-
1410
- var routesObj = Object.assign(Object.assign({}, authInitialState.routes), fronteggConfig.authRoutes);
1411
- var routesArr = Object.keys(routesObj).reduce(function (p, key) {
1412
- return [].concat(_toConsumableArray(p), [routesObj[key]]);
1413
- }, []);
1414
-
1415
- var _parse = parse((_a = context.resolvedUrl) !== null && _a !== void 0 ? _a : context.req.url, true),
1416
- pathname = _parse.pathname;
1417
-
1418
- if (!pathname || pathname.startsWith('/_next/data')) {
1419
- var query = context.req.query[Object.keys(context.req.query)[0]];
1420
- pathname = "/".concat(Array.isArray(query) ? query.join('/') : query);
1421
- }
1422
-
1423
- var notFound = routesArr.indexOf(pathname) === -1;
1424
-
1425
- if (fronteggConfig.fronteggAppOptions.hostedLoginBox) {
1426
- var _notFound = !(routesObj.loginUrl === pathname || routesObj.logoutUrl === pathname || routesObj.hostedLoginRedirectUrl === pathname);
1427
-
1428
- return {
1429
- notFound: _notFound,
1430
- props: {}
1431
- };
1432
- }
1433
-
1434
- return {
1435
- notFound: notFound,
1436
- props: {}
1437
- };
1438
- }
1439
-
1440
- function _arrayWithHoles(arr) {
1441
- if (Array.isArray(arr)) return arr;
1442
- }
1443
-
1444
- function _iterableToArrayLimit(arr, i) {
1445
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
1446
-
1447
- if (_i == null) return;
1448
- var _arr = [];
1449
- var _n = true;
1450
- var _d = false;
1451
-
1452
- var _s, _e;
1453
-
1454
- try {
1455
- for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
1456
- _arr.push(_s.value);
1457
-
1458
- if (i && _arr.length === i) break;
1459
- }
1460
- } catch (err) {
1461
- _d = true;
1462
- _e = err;
1463
- } finally {
1464
- try {
1465
- if (!_n && _i["return"] != null) _i["return"]();
1466
- } finally {
1467
- if (_d) throw _e;
1468
- }
1469
- }
1470
-
1471
- return _arr;
1472
- }
1473
-
1474
- function _nonIterableRest() {
1475
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1476
- }
1477
-
1478
- function _slicedToArray(arr, i) {
1479
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest();
1480
- }
1481
-
1482
- function _defineProperty(obj, key, value) {
1483
- if (key in obj) {
1484
- Object.defineProperty(obj, key, {
1485
- value: value,
1486
- enumerable: true,
1487
- configurable: true,
1488
- writable: true
1489
- });
1490
- } else {
1491
- obj[key] = value;
1492
- }
1493
-
1494
- return obj;
1495
- }
1496
-
1497
- function getHostedLoginRefreshToken(req) {
1498
- return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
1499
- var cookieStr, sealFromCookies, compressedJwt, _JSON$parse, refreshToken;
1500
-
1501
- return regenerator.wrap(function _callee$(_context) {
1502
- while (1) {
1503
- switch (_context.prev = _context.next) {
1504
- case 0:
1505
- _context.prev = 0;
1506
- cookieStr = 'credentials' in req ? req.headers.get('cookie') || '' : req.headers.cookie || '';
1507
- sealFromCookies = parseCookie(cookieStr);
1508
-
1509
- if (sealFromCookies) {
1510
- _context.next = 5;
1511
- break;
1512
- }
1513
-
1514
- return _context.abrupt("return", undefined);
1515
-
1516
- case 5:
1517
- _context.next = 7;
1518
- return unsealData(sealFromCookies, {
1519
- password: fronteggConfig.passwordsAsMap
1520
- });
1521
-
1522
- case 7:
1523
- compressedJwt = _context.sent;
1524
- _context.t0 = JSON;
1525
- _context.next = 11;
1526
- return uncompress(compressedJwt);
1527
-
1528
- case 11:
1529
- _context.t1 = _context.sent;
1530
- _JSON$parse = _context.t0.parse.call(_context.t0, _context.t1);
1531
- refreshToken = _JSON$parse.refreshToken;
1532
- return _context.abrupt("return", refreshToken);
1533
-
1534
- case 17:
1535
- _context.prev = 17;
1536
- _context.t2 = _context["catch"](0);
1537
- return _context.abrupt("return", undefined);
1538
-
1539
- case 20:
1540
- case "end":
1541
- return _context.stop();
1542
- }
1543
- }
1544
- }, _callee, null, [[0, 17]]);
1545
- }));
1546
- }
1547
- function getSession(req) {
1548
- return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee2() {
1549
- var cookieStr, sealFromCookies, compressedJwt, uncompressedJwt, _JSON$parse2, accessToken, refreshToken, publicKey, _yield$jwtVerify, payload, session;
1550
-
1551
- return regenerator.wrap(function _callee2$(_context2) {
1552
- while (1) {
1553
- switch (_context2.prev = _context2.next) {
1554
- case 0:
1555
- _context2.prev = 0;
1556
- cookieStr = 'credentials' in req ? req.headers.get('cookie') || '' : req.headers.cookie || '';
1557
- sealFromCookies = parseCookie(cookieStr);
1558
-
1559
- if (sealFromCookies) {
1560
- _context2.next = 5;
1561
- break;
1562
- }
1563
-
1564
- return _context2.abrupt("return", undefined);
1565
-
1566
- case 5:
1567
- _context2.next = 7;
1568
- return unsealData(sealFromCookies, {
1569
- password: fronteggConfig.passwordsAsMap
1570
- });
1571
-
1572
- case 7:
1573
- compressedJwt = _context2.sent;
1574
- _context2.next = 10;
1575
- return uncompress(compressedJwt);
1576
-
1577
- case 10:
1578
- uncompressedJwt = _context2.sent;
1579
- _JSON$parse2 = JSON.parse(uncompressedJwt), accessToken = _JSON$parse2.accessToken, refreshToken = _JSON$parse2.refreshToken;
1580
-
1581
- if (accessToken) {
1582
- _context2.next = 14;
1583
- break;
1584
- }
1585
-
1586
- return _context2.abrupt("return", undefined);
1587
-
1588
- case 14:
1589
- _context2.next = 16;
1590
- return fronteggConfig.getJwtPublicKey();
1591
-
1592
- case 16:
1593
- publicKey = _context2.sent;
1594
- _context2.next = 19;
1595
- return jwtVerify(accessToken, publicKey);
1596
-
1597
- case 19:
1598
- _yield$jwtVerify = _context2.sent;
1599
- payload = _yield$jwtVerify.payload;
1600
- session = {
1601
- accessToken: accessToken,
1602
- user: payload,
1603
- refreshToken: refreshToken
1604
- };
1605
-
1606
- if (!(session.user.exp * 1000 < Date.now())) {
1607
- _context2.next = 24;
1608
- break;
1609
- }
1610
-
1611
- return _context2.abrupt("return", undefined);
1612
-
1613
- case 24:
1614
- return _context2.abrupt("return", session);
1615
-
1616
- case 27:
1617
- _context2.prev = 27;
1618
- _context2.t0 = _context2["catch"](0);
1619
- console.error(_context2.t0);
1620
- return _context2.abrupt("return", undefined);
1621
-
1622
- case 31:
1623
- case "end":
1624
- return _context2.stop();
1625
- }
1626
- }
1627
- }, _callee2, null, [[0, 27]]);
1628
- }));
1629
- }
1630
- function withSSRSession(handler) {
1631
- var _this = this;
1632
-
1633
- return function (context) {
1634
- return __awaiter(_this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee3() {
1635
- var _a, _b, session, loginUrl;
1636
-
1637
- return regenerator.wrap(function _callee3$(_context3) {
1638
- while (1) {
1639
- switch (_context3.prev = _context3.next) {
1640
- case 0:
1641
- _context3.next = 2;
1642
- return getSession(context.req);
1643
-
1644
- case 2:
1645
- session = _context3.sent;
1646
-
1647
- if (!session) {
1648
- _context3.next = 7;
1649
- break;
1650
- }
1651
-
1652
- return _context3.abrupt("return", handler(context, session));
1653
-
1654
- case 7:
1655
- loginUrl = (_a = fronteggConfig.authRoutes.loginUrl) !== null && _a !== void 0 ? _a : authInitialState.routes.loginUrl;
1656
-
1657
- if (!loginUrl.startsWith('/')) {
1658
- loginUrl = "/".concat(loginUrl);
1659
- }
1660
-
1661
- return _context3.abrupt("return", {
1662
- redirect: {
1663
- permanent: false,
1664
- destination: "".concat(loginUrl, "?redirectUrl=").concat(encodeURIComponent((_b = context.resolvedUrl) !== null && _b !== void 0 ? _b : context.req.url))
1665
- },
1666
- props: {}
1667
- });
1668
-
1669
- case 10:
1670
- case "end":
1671
- return _context3.stop();
1672
- }
1673
- }
1674
- }, _callee3);
1675
- }));
1676
- };
1677
- }
1678
-
1679
- var BASE_URL = "".concat(process.env['FRONTEGG_BASE_URL'], "/frontegg");
1680
-
1681
- var Get = function Get(_ref) {
1682
- var url = _ref.url,
1683
- _ref$credentials = _ref.credentials,
1684
- credentials = _ref$credentials === void 0 ? 'include' : _ref$credentials,
1685
- headers = _ref.headers;
1686
- return fetch(url, {
1687
- method: 'GET',
1688
- credentials: credentials,
1689
- headers: headers
1690
- });
1691
- };
1692
-
1693
- var extractHeaders = function extractHeaders(headers) {
1694
- return {
1695
- 'accept-encoding': headers['accept-encoding'],
1696
- 'accept-language': headers['accept-language'],
1697
- cookie: headers['cookie'],
1698
- accept: headers['accept'],
1699
- 'user-agent': headers['user-agent'],
1700
- connection: headers['connection'],
1701
- 'cache-control': headers['cache-control'],
1702
- 'Authorization': headers['Authorization']
1703
- };
1704
- };
1705
-
1706
- var parseResponse = function parseResponse(res) {
1707
- return __awaiter(void 0, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
1708
- var resText;
1709
- return regenerator.wrap(function _callee$(_context) {
1710
- while (1) {
1711
- switch (_context.prev = _context.next) {
1712
- case 0:
1713
- if (res.ok) {
1714
- _context.next = 2;
1715
- break;
1716
- }
1717
-
1718
- return _context.abrupt("return", undefined);
1719
-
1720
- case 2:
1721
- _context.next = 4;
1722
- return res.text();
1723
-
1724
- case 4:
1725
- resText = _context.sent;
1726
- return _context.abrupt("return", JSON.parse(resText));
1727
-
1728
- case 6:
1729
- case "end":
1730
- return _context.stop();
1731
- }
1732
- }
1733
- }, _callee);
1734
- }));
1735
- };
1736
-
1737
- var getUsers = function getUsers(headers) {
1738
- return __awaiter(void 0, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee2() {
1739
- var res;
1740
- return regenerator.wrap(function _callee2$(_context2) {
1741
- while (1) {
1742
- switch (_context2.prev = _context2.next) {
1743
- case 0:
1744
- _context2.next = 2;
1745
- return Get({
1746
- url: "".concat(BASE_URL).concat(fronteggUsersUrl),
1747
- headers: extractHeaders(headers)
1748
- });
1749
-
1750
- case 2:
1751
- res = _context2.sent;
1752
- return _context2.abrupt("return", parseResponse(res));
1753
-
1754
- case 4:
1755
- case "end":
1756
- return _context2.stop();
1757
- }
1758
- }
1759
- }, _callee2);
1760
- }));
1761
- };
1762
- var getTenants = function getTenants(headers) {
1763
- return __awaiter(void 0, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee3() {
1764
- var res;
1765
- return regenerator.wrap(function _callee3$(_context3) {
1766
- while (1) {
1767
- switch (_context3.prev = _context3.next) {
1768
- case 0:
1769
- _context3.next = 2;
1770
- return Get({
1771
- url: "".concat(BASE_URL).concat(fronteggTenantsUrl),
1772
- headers: extractHeaders(headers)
1773
- });
1774
-
1775
- case 2:
1776
- res = _context3.sent;
1777
- return _context3.abrupt("return", parseResponse(res));
1778
-
1779
- case 4:
1780
- case "end":
1781
- return _context3.stop();
1782
- }
1783
- }
1784
- }, _callee3);
1785
- }));
1786
- };
1787
-
1788
- function rewriteCookieProperty(header, config, property) {
1789
- if (Array.isArray(header)) {
1790
- return header.map(function (headerElement) {
1791
- return rewriteCookieProperty(headerElement, config, property);
1792
- });
1793
- }
1794
-
1795
- return header.replace(new RegExp('(;\\s*' + property + '=)([^;]+)', 'i'), function (match, prefix, previousValue) {
1796
- var newValue;
1797
-
1798
- if (previousValue in config) {
1799
- newValue = config[previousValue];
1800
- } else if ('*' in config) {
1801
- newValue = config['*'];
1802
- } else {
1803
- // no match, return previous value
1804
- return match;
1805
- }
1806
-
1807
- if (newValue) {
1808
- // replace value
1809
- return prefix + newValue;
1810
- } else {
1811
- // remove value
1812
- return '';
1813
- }
1814
- });
1815
- }
1816
-
1817
- function refreshTokenHostedLogin(ctx, headers) {
1818
- return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
1819
- var refreshToken;
1820
- return regenerator.wrap(function _callee$(_context) {
1821
- while (1) {
1822
- switch (_context.prev = _context.next) {
1823
- case 0:
1824
- _context.next = 2;
1825
- return getHostedLoginRefreshToken(ctx.req);
1826
-
1827
- case 2:
1828
- refreshToken = _context.sent;
1829
-
1830
- if (refreshToken) {
1831
- _context.next = 5;
1832
- break;
1833
- }
1834
-
1835
- return _context.abrupt("return", null);
1836
-
1837
- case 5:
1838
- _context.next = 7;
1839
- return fetch("".concat(process.env['FRONTEGG_BASE_URL'], "/frontegg").concat(fronteggSilentRefreshTokenUrl), {
1840
- method: 'POST',
1841
- credentials: 'include',
1842
- body: JSON.stringify({
1843
- grant_type: 'refresh_token',
1844
- refresh_token: refreshToken
1845
- }),
1846
- headers: {
1847
- 'accept-encoding': headers['accept-encoding'],
1848
- 'accept-language': headers['accept-language'],
1849
- cookie: headers['cookie'],
1850
- accept: headers['accept'],
1851
- 'user-agent': headers['user-agent'],
1852
- connection: headers['connection'],
1853
- 'cache-control': headers['cache-control']
1854
- }
1855
- });
1856
-
1857
- case 7:
1858
- return _context.abrupt("return", _context.sent);
1859
-
1860
- case 8:
1861
- case "end":
1862
- return _context.stop();
1863
- }
1864
- }
1865
- }, _callee);
1866
- }));
1867
- }
1868
-
1869
- function refreshTokenEmbedded(ctx, headers, cookies) {
1870
- return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee2() {
1871
- var refreshTokenKey, cookieKey;
1872
- return regenerator.wrap(function _callee2$(_context2) {
1873
- while (1) {
1874
- switch (_context2.prev = _context2.next) {
1875
- case 0:
1876
- refreshTokenKey = "fe_refresh_".concat(fronteggConfig.clientId).replace(/-/g, '');
1877
- cookieKey = Object.keys(cookies).find(function (cookie) {
1878
- return cookie.replace(/-/g, '') === refreshTokenKey;
1879
- });
1880
-
1881
- if (cookieKey) {
1882
- _context2.next = 4;
1883
- break;
1884
- }
1885
-
1886
- return _context2.abrupt("return", null);
1887
-
1888
- case 4:
1889
- _context2.next = 6;
1890
- return fetch("".concat(process.env['FRONTEGG_BASE_URL'], "/frontegg").concat(fronteggRefreshTokenUrl), {
1891
- method: 'POST',
1892
- credentials: 'include',
1893
- body: '{}',
1894
- headers: {
1895
- 'accept-encoding': headers['accept-encoding'],
1896
- 'accept-language': headers['accept-language'],
1897
- cookie: headers['cookie'],
1898
- accept: headers['accept'],
1899
- 'user-agent': headers['user-agent'],
1900
- connection: headers['connection'],
1901
- 'cache-control': headers['cache-control']
1902
- }
1903
- });
1904
-
1905
- case 6:
1906
- return _context2.abrupt("return", _context2.sent);
1907
-
1908
- case 7:
1909
- case "end":
1910
- return _context2.stop();
1911
- }
1912
- }
1913
- }, _callee2);
1914
- }));
1915
- }
1916
-
1917
- function refreshToken(ctx) {
1918
- var _a;
1919
-
1920
- return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee3() {
1921
- var request, session, isSecured, headers, cookies, response, _newSetCookie, data, rewriteCookieDomainConfig, cookieHeader, newSetCookie, _yield$createSessionF, _yield$createSessionF2, _session, decodedJwt, _refreshToken, cookieValue;
1922
-
1923
- return regenerator.wrap(function _callee3$(_context3) {
1924
- while (1) {
1925
- switch (_context3.prev = _context3.next) {
1926
- case 0:
1927
- _context3.prev = 0;
1928
- request = ctx.req;
1929
-
1930
- if (request) {
1931
- _context3.next = 4;
1932
- break;
1933
- }
1934
-
1935
- return _context3.abrupt("return", null);
1936
-
1937
- case 4:
1938
- _context3.prev = 4;
1939
- _context3.next = 7;
1940
- return getSession(ctx.req);
1941
-
1942
- case 7:
1943
- session = _context3.sent;
1944
-
1945
- if (!session) {
1946
- _context3.next = 10;
1947
- break;
1948
- }
1949
-
1950
- return _context3.abrupt("return", session);
1951
-
1952
- case 10:
1953
- _context3.next = 14;
1954
- break;
1955
-
1956
- case 12:
1957
- _context3.prev = 12;
1958
- _context3.t0 = _context3["catch"](4);
1959
-
1960
- case 14:
1961
- isSecured = new URL(fronteggConfig.appUrl).protocol === 'https:';
1962
- headers = request.headers;
1963
- cookies = request.cookies;
1964
-
1965
- if (!ctx.req.url.startsWith('/oauth/callback')) {
1966
- _context3.next = 19;
1967
- break;
1968
- }
1969
-
1970
- return _context3.abrupt("return", null);
1971
-
1972
- case 19:
1973
- if (!fronteggConfig.fronteggAppOptions.hostedLoginBox) {
1974
- _context3.next = 25;
1975
- break;
1976
- }
1977
-
1978
- _context3.next = 22;
1979
- return refreshTokenHostedLogin(ctx, headers);
1980
-
1981
- case 22:
1982
- response = _context3.sent;
1983
- _context3.next = 28;
1984
- break;
1985
-
1986
- case 25:
1987
- _context3.next = 27;
1988
- return refreshTokenEmbedded(ctx, headers, cookies);
1989
-
1990
- case 27:
1991
- response = _context3.sent;
1992
-
1993
- case 28:
1994
- if (response) {
1995
- _context3.next = 31;
1996
- break;
1997
- }
1998
-
1999
- removeCookies(fronteggConfig.cookieName, isSecured, fronteggConfig.cookieDomain, ctx.res);
2000
- return _context3.abrupt("return", null);
2001
-
2002
- case 31:
2003
- if (!response.ok) {
2004
- _context3.next = 54;
2005
- break;
2006
- }
2007
-
2008
- _context3.next = 34;
2009
- return response.text();
2010
-
2011
- case 34:
2012
- data = _context3.sent;
2013
- rewriteCookieDomainConfig = _defineProperty({}, fronteggConfig.baseUrlHost, fronteggConfig.cookieDomain); // @ts-ignore
2014
-
2015
- cookieHeader = response.headers.raw()['set-cookie'];
2016
- newSetCookie = rewriteCookieProperty(cookieHeader, rewriteCookieDomainConfig, 'domain');
2017
- _context3.next = 40;
2018
- return createSessionFromAccessToken(data);
2019
-
2020
- case 40:
2021
- _yield$createSessionF = _context3.sent;
2022
- _yield$createSessionF2 = _slicedToArray(_yield$createSessionF, 3);
2023
- _session = _yield$createSessionF2[0];
2024
- decodedJwt = _yield$createSessionF2[1];
2025
- _refreshToken = _yield$createSessionF2[2];
2026
-
2027
- if (_session) {
2028
- _context3.next = 47;
2029
- break;
2030
- }
2031
-
2032
- return _context3.abrupt("return", null);
2033
-
2034
- case 47:
2035
- cookieValue = createCookie({
2036
- session: _session,
2037
- expires: new Date(decodedJwt.exp * 1000),
2038
- isSecured: isSecured
2039
- });
2040
-
2041
- if (typeof newSetCookie === 'string') {
2042
- newSetCookie = [newSetCookie];
2043
- }
2044
-
2045
- (_newSetCookie = newSetCookie).push.apply(_newSetCookie, _toConsumableArray(cookieValue));
2046
-
2047
- (_a = ctx.res) === null || _a === void 0 ? void 0 : _a.setHeader('set-cookie', newSetCookie);
2048
- return _context3.abrupt("return", {
2049
- accessToken: JSON.parse(data).accessToken,
2050
- user: decodedJwt,
2051
- refreshToken: _refreshToken
2052
- });
2053
-
2054
- case 54:
2055
- return _context3.abrupt("return", null);
2056
-
2057
- case 55:
2058
- _context3.next = 60;
2059
- break;
2060
-
2061
- case 57:
2062
- _context3.prev = 57;
2063
- _context3.t1 = _context3["catch"](0);
2064
- return _context3.abrupt("return", null);
2065
-
2066
- case 60:
2067
- case "end":
2068
- return _context3.stop();
2069
- }
2070
- }
2071
- }, _callee3, null, [[0, 57], [4, 12]]);
2072
- }));
2073
- }
2074
- var COOKIE_MAX_LENGTH = 4096;
2075
- function createCookie(_ref) {
2076
- var _ref$cookieName = _ref.cookieName,
2077
- cookieName = _ref$cookieName === void 0 ? fronteggConfig.cookieName : _ref$cookieName,
2078
- session = _ref.session,
2079
- expires = _ref.expires,
2080
- isSecured = _ref.isSecured,
2081
- _ref$cookieDomain = _ref.cookieDomain,
2082
- cookieDomain = _ref$cookieDomain === void 0 ? fronteggConfig.cookieDomain : _ref$cookieDomain,
2083
- _ref$httpOnly = _ref.httpOnly,
2084
- httpOnly = _ref$httpOnly === void 0 ? true : _ref$httpOnly,
2085
- _ref$path = _ref.path,
2086
- path = _ref$path === void 0 ? '/' : _ref$path;
2087
- var options = {
2088
- expires: expires,
2089
- httpOnly: httpOnly,
2090
- domain: cookieDomain,
2091
- path: path,
2092
- sameSite: isSecured ? 'none' : undefined,
2093
- secure: isSecured
2094
- };
2095
- var cookieValue = cookie.serialize(cookieName, session, options);
2096
-
2097
- if (cookieValue.length < COOKIE_MAX_LENGTH) {
2098
- return [cookieValue];
2099
- }
2100
-
2101
- return createSplitCookie(cookieName, session, options, cookieValue.length);
2102
- }
2103
-
2104
- function createSplitCookie(cookieName, session, options, cookieLength) {
2105
- var numberOfCookies = Math.ceil(cookieLength / COOKIE_MAX_LENGTH);
2106
- var splitSession = chunkString(session, numberOfCookies);
2107
- var allCookies = [];
2108
-
2109
- for (var i = 1; i <= numberOfCookies; i++) {
2110
- allCookies.push(cookie.serialize("".concat(cookieName, "-").concat(i), splitSession[i - 1], options));
2111
- }
2112
-
2113
- return allCookies;
2114
- }
2115
-
2116
- function chunkString(str, numChunks) {
2117
- var chunkSize = Math.ceil(str.length / numChunks);
2118
- var chunks = [];
2119
-
2120
- for (var i = 0; i < numChunks; i + chunkSize) {
2121
- var limit = i + chunkSize;
2122
- chunks.push(str.substring(i, limit < str.length ? limit : str.length));
2123
- }
2124
-
2125
- return chunks;
2126
- }
2127
-
2128
- function parseCookie(cookieStr) {
2129
- var sealFromCookies = '';
2130
-
2131
- if (cookie.parse(cookieStr)[fronteggConfig.cookieName]) {
2132
- sealFromCookies = cookie.parse(cookieStr)[fronteggConfig.cookieName];
2133
- } else {
2134
- var i = 1;
2135
-
2136
- while (cookie.parse(cookieStr)["".concat(fronteggConfig.cookieName, "-").concat(i)]) {
2137
- sealFromCookies += cookie.parse(cookieStr)["".concat(fronteggConfig.cookieName, "-").concat(i)];
2138
- i++;
2139
- }
2140
- }
2141
-
2142
- return sealFromCookies !== '' ? sealFromCookies : undefined;
2143
- }
2144
- function addToCookies(newCookies, res) {
2145
- var _a;
2146
-
2147
- var existingSetCookie = (_a = res.getHeader('set-cookie')) !== null && _a !== void 0 ? _a : [];
2148
-
2149
- if (typeof existingSetCookie === 'string') {
2150
- existingSetCookie = [existingSetCookie];
2151
- }
2152
-
2153
- res.setHeader('set-cookie', [].concat(_toConsumableArray(existingSetCookie), _toConsumableArray(newCookies)));
2154
- }
2155
- function removeCookies(cookieName, isSecured, cookieDomain, res) {
2156
- var _a;
2157
-
2158
- var cookieValue = createCookie({
2159
- cookieName: cookieName,
2160
- session: '',
2161
- expires: new Date(),
2162
- isSecured: isSecured,
2163
- cookieDomain: cookieDomain
2164
- });
2165
- var existingSetCookie = (_a = res.getHeader('set-cookie')) !== null && _a !== void 0 ? _a : [];
2166
-
2167
- if (typeof existingSetCookie === 'string') {
2168
- existingSetCookie = [existingSetCookie];
2169
- }
2170
-
2171
- res.setHeader('set-cookie', [].concat(_toConsumableArray(existingSetCookie), _toConsumableArray(cookieValue)));
2172
- }
2173
- function compress(input) {
2174
- return new Promise(function (resolve, reject) {
2175
- zlib.brotliCompress(input, function (error, result) {
2176
- if (error) {
2177
- reject(error);
2178
- } else {
2179
- resolve(result.toString('base64'));
2180
- }
2181
- });
2182
- });
2183
- }
2184
- function uncompress(input) {
2185
- return new Promise(function (resolve, reject) {
2186
- zlib.brotliDecompress(Buffer.from(input, 'base64'), function (error, result) {
2187
- if (error) {
2188
- reject(error);
2189
- } else {
2190
- resolve(result.toString('utf-8'));
2191
- }
2192
- });
2193
- });
2194
- }
2195
- function createSessionFromAccessToken(output) {
2196
- var _a, _b;
2197
-
2198
- return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee4() {
2199
- var data, accessToken, _refreshToken2, decodedJwt, uncompressedSession, compressedAccessToken, session;
2200
-
2201
- return regenerator.wrap(function _callee4$(_context4) {
2202
- while (1) {
2203
- switch (_context4.prev = _context4.next) {
2204
- case 0:
2205
- _context4.prev = 0;
2206
- data = JSON.parse(output);
2207
- accessToken = (_a = data === null || data === void 0 ? void 0 : data.accessToken) !== null && _a !== void 0 ? _a : data.access_token;
2208
- _refreshToken2 = (_b = data === null || data === void 0 ? void 0 : data.refreshToken) !== null && _b !== void 0 ? _b : data.refresh_token;
2209
- decodedJwt = decodeJwt(accessToken);
2210
- decodedJwt.expiresIn = Math.floor((decodedJwt.exp * 1000 - Date.now()) / 1000);
2211
- uncompressedSession = JSON.stringify({
2212
- accessToken: accessToken,
2213
- refreshToken: _refreshToken2
2214
- });
2215
- _context4.next = 9;
2216
- return compress(uncompressedSession);
2217
-
2218
- case 9:
2219
- compressedAccessToken = _context4.sent;
2220
- _context4.next = 12;
2221
- return sealData(compressedAccessToken, {
2222
- password: fronteggConfig.passwordsAsMap,
2223
- ttl: decodedJwt.exp
2224
- });
2225
-
2226
- case 12:
2227
- session = _context4.sent;
2228
- return _context4.abrupt("return", [session, decodedJwt, _refreshToken2]);
2229
-
2230
- case 16:
2231
- _context4.prev = 16;
2232
- _context4.t0 = _context4["catch"](0);
2233
- return _context4.abrupt("return", []);
2234
-
2235
- case 19:
2236
- case "end":
2237
- return _context4.stop();
2238
- }
2239
- }
2240
- }, _callee4, null, [[0, 16]]);
2241
- }));
2242
- }
2243
- var modifySetCookieIfUnsecure = function modifySetCookieIfUnsecure(setCookieValue, isSecured) {
2244
- if (!setCookieValue) {
2245
- return setCookieValue;
2246
- }
2247
-
2248
- if (setCookieValue.length > 0) {
2249
- return setCookieValue.map(function (c) {
2250
- var cookie = c.split('; ');
2251
-
2252
- if (isSecured) {
2253
- return c;
2254
- }
2255
-
2256
- return cookie.filter(function (property) {
2257
- return property !== 'Secure' && property !== 'SameSite=None';
2258
- }).join('; ');
2259
- });
2260
- }
2261
-
2262
- return setCookieValue;
2263
- };
2264
- function meAndTenants(ctx, accessToken) {
2265
- return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee5() {
2266
- var request, headers, _yield$Promise$all, _yield$Promise$all2, user, tenants;
2267
-
2268
- return regenerator.wrap(function _callee5$(_context5) {
2269
- while (1) {
2270
- switch (_context5.prev = _context5.next) {
2271
- case 0:
2272
- request = ctx.req;
2273
-
2274
- if (!(!request || !accessToken)) {
2275
- _context5.next = 3;
2276
- break;
2277
- }
2278
-
2279
- return _context5.abrupt("return", {});
2280
-
2281
- case 3:
2282
- headers = Object.assign(Object.assign({}, request.headers), {
2283
- Authorization: "Bearer ".concat(accessToken)
2284
- });
2285
- _context5.next = 6;
2286
- return Promise.all([getUsers(headers), getTenants(headers)]);
2287
-
2288
- case 6:
2289
- _yield$Promise$all = _context5.sent;
2290
- _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
2291
- user = _yield$Promise$all2[0];
2292
- tenants = _yield$Promise$all2[1];
2293
- return _context5.abrupt("return", {
2294
- user: user,
2295
- tenants: tenants
2296
- });
2297
-
2298
- case 11:
2299
- case "end":
2300
- return _context5.stop();
2301
- }
2302
- }
2303
- }, _callee5);
2304
- }));
2305
- }
2306
-
2307
- var envError = function envError(varName) {
2308
- return "@frontegg/nextjs: .env.local must contain ".concat(varName);
2309
- };
2310
-
2311
- var fronteggErrors = {
2312
- envAppUrl: envError('FRONTEGG_APP_URL'),
2313
- envBaseUrl: envError('FRONTEGG_BASE_URL'),
2314
- envClientId: envError('FRONTEGG_CLIENT_ID')
2315
- };
2316
-
2317
- var withFronteggApp = function withFronteggApp(app, options) {
2318
- var _a, _b;
2319
-
2320
- var originalGetInitialProps = app.getInitialProps;
2321
-
2322
- app.getInitialProps = function (appContext) {
2323
- return __awaiter(void 0, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
2324
- var ctx, Component, session, _yield$meAndTenants, user, tenants, _fronteggConfig$appEn, envAppUrl, envBaseUrl, envClientId;
2325
-
2326
- return regenerator.wrap(function _callee$(_context) {
2327
- while (1) {
2328
- switch (_context.prev = _context.next) {
2329
- case 0:
2330
- ctx = appContext.ctx, Component = appContext.Component;
2331
-
2332
- if (!ctx.req) {
2333
- _context.next = 47;
2334
- break;
2335
- }
2336
-
2337
- _context.next = 4;
2338
- return refreshToken(ctx);
2339
-
2340
- case 4:
2341
- session = _context.sent;
2342
- _context.next = 7;
2343
- return meAndTenants(ctx, session === null || session === void 0 ? void 0 : session.accessToken);
2344
-
2345
- case 7:
2346
- _yield$meAndTenants = _context.sent;
2347
- user = _yield$meAndTenants.user;
2348
- tenants = _yield$meAndTenants.tenants;
2349
- appContext.session = session;
2350
- appContext.user = user;
2351
- appContext.tenants = tenants;
2352
- _fronteggConfig$appEn = fronteggConfig.appEnvConfig, envAppUrl = _fronteggConfig$appEn.envAppUrl, envBaseUrl = _fronteggConfig$appEn.envBaseUrl, envClientId = _fronteggConfig$appEn.envClientId;
2353
-
2354
- if (envAppUrl) {
2355
- _context.next = 16;
2356
- break;
2357
- }
2358
-
2359
- throw Error(fronteggErrors.envAppUrl);
2360
-
2361
- case 16:
2362
- if (envBaseUrl) {
2363
- _context.next = 18;
2364
- break;
2365
- }
2366
-
2367
- throw Error(fronteggErrors.envBaseUrl);
2368
-
2369
- case 18:
2370
- if (envClientId) {
2371
- _context.next = 20;
2372
- break;
2373
- }
2374
-
2375
- throw Error(fronteggErrors.envClientId);
2376
-
2377
- case 20:
2378
- _context.t0 = Object;
2379
- _context.t1 = Object;
2380
- _context.t2 = Object;
2381
- _context.t3 = {};
2382
-
2383
- if (!originalGetInitialProps) {
2384
- _context.next = 30;
2385
- break;
2386
- }
2387
-
2388
- _context.next = 27;
2389
- return originalGetInitialProps(appContext);
2390
-
2391
- case 27:
2392
- _context.t4 = _context.sent;
2393
- _context.next = 31;
2394
- break;
2395
-
2396
- case 30:
2397
- _context.t4 = {};
2398
-
2399
- case 31:
2400
- _context.t5 = _context.t4;
2401
- _context.t6 = _context.t2.assign.call(_context.t2, _context.t3, _context.t5);
2402
-
2403
- if (!Component.getInitialProps) {
2404
- _context.next = 39;
2405
- break;
2406
- }
2407
-
2408
- _context.next = 36;
2409
- return Component.getInitialProps(ctx);
2410
-
2411
- case 36:
2412
- _context.t7 = _context.sent;
2413
- _context.next = 40;
2414
- break;
2415
-
2416
- case 39:
2417
- _context.t7 = {};
2418
-
2419
- case 40:
2420
- _context.t8 = _context.t7;
2421
- _context.t9 = _context.t1.assign.call(_context.t1, _context.t6, _context.t8);
2422
- _context.t10 = {
2423
- session: session,
2424
- user: user,
2425
- tenants: tenants,
2426
- envAppUrl: envAppUrl,
2427
- envBaseUrl: process.env['FRONTEGG_BASE_URL'],
2428
- envClientId: process.env['FRONTEGG_CLIENT_ID']
2429
- };
2430
- _context.t11 = _context.t0.assign.call(_context.t0, _context.t9, _context.t10);
2431
- return _context.abrupt("return", {
2432
- pageProps: _context.t11
2433
- });
2434
-
2435
- case 47:
2436
- appContext.session = null;
2437
- _context.t12 = Object;
2438
- _context.t13 = Object;
2439
- _context.t14 = {};
2440
-
2441
- if (!originalGetInitialProps) {
2442
- _context.next = 57;
2443
- break;
2444
- }
2445
-
2446
- _context.next = 54;
2447
- return originalGetInitialProps(appContext);
2448
-
2449
- case 54:
2450
- _context.t15 = _context.sent;
2451
- _context.next = 58;
2452
- break;
2453
-
2454
- case 57:
2455
- _context.t15 = {};
2456
-
2457
- case 58:
2458
- _context.t16 = _context.t15;
2459
- _context.t17 = _context.t13.assign.call(_context.t13, _context.t14, _context.t16);
2460
-
2461
- if (!Component.getInitialProps) {
2462
- _context.next = 66;
2463
- break;
2464
- }
2465
-
2466
- _context.next = 63;
2467
- return Component.getInitialProps(ctx);
2468
-
2469
- case 63:
2470
- _context.t18 = _context.sent;
2471
- _context.next = 67;
2472
- break;
2473
-
2474
- case 66:
2475
- _context.t18 = {};
2476
-
2477
- case 67:
2478
- _context.t19 = _context.t18;
2479
- _context.t20 = _context.t12.assign.call(_context.t12, _context.t17, _context.t19);
2480
- return _context.abrupt("return", {
2481
- pageProps: _context.t20
2482
- });
2483
-
2484
- case 70:
2485
- case "end":
2486
- return _context.stop();
2487
- }
2488
- }
2489
- }, _callee);
2490
- }));
2491
- };
2492
-
2493
- 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 : {};
2494
- fronteggConfig.fronteggAppOptions = options !== null && options !== void 0 ? options : {};
2495
-
2496
- function CustomFronteggApp(appProps) {
2497
- var _appProps$pageProps = appProps.pageProps,
2498
- user = _appProps$pageProps.user,
2499
- tenants = _appProps$pageProps.tenants,
2500
- session = _appProps$pageProps.session,
2501
- envAppUrl = _appProps$pageProps.envAppUrl,
2502
- envBaseUrl = _appProps$pageProps.envBaseUrl,
2503
- envClientId = _appProps$pageProps.envClientId;
2504
- return jsx(FronteggProvider, Object.assign({}, options, {
2505
- user: user,
2506
- tenants: tenants,
2507
- session: session,
2508
- envAppUrl: envAppUrl,
2509
- envBaseUrl: envBaseUrl,
2510
- envClientId: envClientId
2511
- }, {
2512
- children: app(appProps)
2513
- }));
2514
- }
2515
-
2516
- CustomFronteggApp.getInitialProps = app.getInitialProps;
2517
- return CustomFronteggApp;
2518
- };
2519
-
2520
- 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; } } }; }
2521
-
2522
- 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); }
2523
-
2524
- 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; }
2525
- /**
2526
- * @see https://www.npmjs.com/package/http-proxy
2527
- */
2528
-
2529
- var proxy = httpProxy.createProxyServer({
2530
- target: process.env['FRONTEGG_BASE_URL']
2531
- });
2532
- /**
2533
- * Please refer to the following links for the specification document for HTTP.
2534
- * @see https://tools.ietf.org/html/rfc7231
2535
- * @see https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
2536
- */
2537
-
2538
- var hasRequestBodyMethods = ['HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'PATCH'];
2539
- /**
2540
- * If pattern information matching the input url information is found in the `pathRewrite` array,
2541
- * the url value is partially replaced with the `pathRewrite.replaceStr` value.
2542
- * @param url
2543
- * @param pathRewrite
2544
- */
2545
-
2546
- var rewritePath = function rewritePath(url, pathRewrite) {
2547
- if (Array.isArray(pathRewrite)) {
2548
- var _iterator = _createForOfIteratorHelper(pathRewrite),
2549
- _step;
2550
-
2551
- try {
2552
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2553
- var item = _step.value;
2554
- var patternStr = item.patternStr,
2555
- replaceStr = item.replaceStr;
2556
- var pattern = RegExp(patternStr);
2557
-
2558
- if (pattern.test(url)) {
2559
- return url.replace(pattern, replaceStr);
2560
- }
2561
- }
2562
- } catch (err) {
2563
- _iterator.e(err);
2564
- } finally {
2565
- _iterator.f();
2566
- }
2567
- } else {
2568
- // tslint:disable-next-line:forin
2569
- for (var _patternStr in pathRewrite) {
2570
- var _pattern = RegExp(_patternStr);
2571
-
2572
- var path = pathRewrite[_patternStr];
2573
-
2574
- if (_pattern.test(url)) {
2575
- return url.replace(_pattern, path);
2576
- }
2577
- }
2578
- }
2579
-
2580
- return url;
2581
- };
2582
- /**
2583
- * Next.js HTTP Proxy Middleware
2584
- * @see https://nextjs.org/docs/api-routes/api-middlewares
2585
- * @param {NextApiRequest} req
2586
- * @param {NextApiResponse} res
2587
- */
2588
-
2589
- function fronteggMiddleware(req, res) {
2590
- var _this = this;
2591
-
2592
- return new Promise(function (resolve, reject) {
2593
- var pathRewrite = [{
2594
- patternStr: '^/api/',
2595
- replaceStr: '/'
2596
- }];
2597
-
2598
- if (pathRewrite) {
2599
- req.url = rewritePath(req.url, pathRewrite);
2600
- }
2601
-
2602
- if (hasRequestBodyMethods.indexOf(req.method) >= 0 && typeof req.body === 'object') {
2603
- req.body = JSON.stringify(req.body);
2604
- }
2605
-
2606
- var isSecured = new URL(fronteggConfig.appUrl).protocol === 'https:';
2607
- proxy.once('proxyReq', function (proxyReq, req) {
2608
- if (hasRequestBodyMethods.indexOf(req.method) >= 0 && typeof req.body === 'string') {
2609
- proxyReq.write(req.body);
2610
- proxyReq.end();
2611
- }
2612
- }).once('proxyRes', function (proxyRes, req, serverResponse) {
2613
- proxyRes.headers['set-cookie'] = modifySetCookieIfUnsecure(proxyRes.headers['set-cookie'], isSecured);
2614
- var _end = res.end;
2615
- var buffer = new Buffer('');
2616
- proxyRes.on('data', function (chunk) {
2617
- buffer = Buffer.concat([buffer, chunk]);
2618
- }).on('end', function () {
2619
- return __awaiter(_this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
2620
- var _a, _b, output, isLogout, _yield$createSessionF, _yield$createSessionF2, session, decodedJwt, sessionCookie;
2621
-
2622
- return regenerator.wrap(function _callee$(_context) {
2623
- while (1) {
2624
- switch (_context.prev = _context.next) {
2625
- case 0:
2626
- output = buffer.toString('utf-8');
2627
- isLogout = (_a = req === null || req === void 0 ? void 0 : req.url) === null || _a === void 0 ? void 0 : _a.endsWith((_b = fronteggAuthApiRoutes.find(function (path) {
2628
- return path.endsWith('/logout');
2629
- })) !== null && _b !== void 0 ? _b : '/logout');
2630
-
2631
- if (!isLogout) {
2632
- _context.next = 6;
2633
- break;
2634
- }
2635
-
2636
- removeCookies(fronteggConfig.cookieName, isSecured, fronteggConfig.cookieDomain, serverResponse);
2637
- _context.next = 13;
2638
- break;
2639
-
2640
- case 6:
2641
- _context.next = 8;
2642
- return createSessionFromAccessToken(output);
2643
-
2644
- case 8:
2645
- _yield$createSessionF = _context.sent;
2646
- _yield$createSessionF2 = _slicedToArray(_yield$createSessionF, 2);
2647
- session = _yield$createSessionF2[0];
2648
- decodedJwt = _yield$createSessionF2[1];
2649
-
2650
- if (session) {
2651
- sessionCookie = createCookie({
2652
- session: session,
2653
- expires: new Date(decodedJwt.exp * 1000),
2654
- isSecured: isSecured
2655
- });
2656
- addToCookies(sessionCookie, serverResponse);
2657
- }
2658
-
2659
- case 13:
2660
- res.setHeader('content-length', output.length);
2661
- res.setHeader('content-encoding', ''); // @ts-ignore
2662
-
2663
- _end.apply(res, [output]);
2664
-
2665
- case 16:
2666
- case "end":
2667
- return _context.stop();
2668
- }
2669
- }
2670
- }, _callee);
2671
- }));
2672
- }); // disable default behavior to read jwt
2673
- // @ts-ignore
2674
-
2675
- serverResponse.write = function () {
2676
- return undefined;
2677
- }; // @ts-ignore
2678
-
2679
-
2680
- serverResponse.end = function () {
2681
- return undefined;
2682
- };
2683
- }).once('error', reject).web(req, res, {
2684
- changeOrigin: true,
2685
- cookieDomainRewrite: _defineProperty({}, fronteggConfig.baseUrlHost, fronteggConfig.cookieDomain) // ...serverOptions
2686
-
2687
- });
2688
- });
2689
- }
2690
-
2691
- export { AuthorizedContent, fronteggConfig as FronteggConfig, FronteggProvider, FronteggProviderNoSSR, FronteggRouter, FronteggRouterProps, fronteggMiddleware, getHostedLoginRefreshToken, getSession, rewritePath, withFronteggApp, withSSRSession };