@clicktap/state 0.2.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.esm.js ADDED
@@ -0,0 +1,996 @@
1
+ import _toConsumableArray from '@babel/runtime/helpers/esm/toConsumableArray';
2
+ import _regeneratorRuntime from '@babel/runtime/regenerator';
3
+ import { setup, assign, fromPromise, createActor, fromCallback, sendTo } from 'xstate';
4
+ import axios from 'axios';
5
+ import { jsx } from 'react/jsx-runtime';
6
+ import { createContext, useContext, useState, useEffect, cloneElement } from 'react';
7
+ import crypto from 'crypto';
8
+
9
+ /******************************************************************************
10
+ Copyright (c) Microsoft Corporation.
11
+
12
+ Permission to use, copy, modify, and/or distribute this software for any
13
+ purpose with or without fee is hereby granted.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
+ PERFORMANCE OF THIS SOFTWARE.
22
+ ***************************************************************************** */
23
+
24
+ function __awaiter(thisArg, _arguments, P, generator) {
25
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
26
+ return new (P || (P = Promise))(function (resolve, reject) {
27
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
28
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
29
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
30
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
31
+ });
32
+ }
33
+
34
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
35
+ var e = new Error(message);
36
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
37
+ };
38
+
39
+ function request(url, options) {
40
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
41
+ var response;
42
+ return _regeneratorRuntime.wrap(function _callee$(_context) {
43
+ while (1) {
44
+ switch (_context.prev = _context.next) {
45
+ case 0:
46
+ _context.next = 2;
47
+ return fetch(url, options);
48
+ case 2:
49
+ response = _context.sent;
50
+ if (!(response.status === 200)) {
51
+ _context.next = 5;
52
+ break;
53
+ }
54
+ return _context.abrupt("return", response.json());
55
+ case 5:
56
+ return _context.abrupt("return", Promise.resolve({
57
+ message: response.statusText,
58
+ success: false
59
+ }));
60
+ case 6:
61
+ case "end":
62
+ return _context.stop();
63
+ }
64
+ }
65
+ }, _callee);
66
+ }));
67
+ }
68
+ /**
69
+ * still need a factory pattern to pass context and state
70
+ * until xstate supports both
71
+ */
72
+ // export const authMachine = (
73
+ // initialContext: Partial<AuthMachineContext> = {},
74
+ // initialState = 'refreshing'
75
+ // ) => {
76
+ var authMachine = setup({
77
+ types: {
78
+ context: {},
79
+ events: {},
80
+ input: {}
81
+ },
82
+ actions: {
83
+ setUserContext: assign(function (_ref) {
84
+ var context = _ref.context,
85
+ event = _ref.event;
86
+ if (!event.type.includes('xstate.done.actor')) return context;
87
+ var e = event;
88
+ if (e.output.type !== 'AUTHENTICATE_SUCCESS') return context;
89
+ return {
90
+ accessToken: e.output.accessToken,
91
+ ignoreRefreshToken: false
92
+ };
93
+ }),
94
+ unsetUserContext: assign(function () {
95
+ return {
96
+ user: null,
97
+ accessToken: '',
98
+ refreshToken: '',
99
+ ignoreRefreshToken: false
100
+ };
101
+ }),
102
+ setAccessToken: assign(function (_ref2) {
103
+ var context = _ref2.context,
104
+ event = _ref2.event;
105
+ if (!event.type.includes('xstate.done.actor')) return context;
106
+ var e = event;
107
+ if (e.output.type !== 'REFRESH_TOKEN_SUCCESS') return context;
108
+ return {
109
+ accessToken: e.output.accessToken,
110
+ ignoreRefreshToken: false
111
+ };
112
+ }),
113
+ unsetRefreshToken: assign(function () {
114
+ // there shouldn't be a problem with not checking event here
115
+ // since we can only hit this action from the refresh actor
116
+ // onDone or onError
117
+ return {
118
+ refreshToken: ''
119
+ };
120
+ }),
121
+ setIgnoreRefreshToken: assign(function () {
122
+ return {
123
+ ignoreRefreshToken: true
124
+ };
125
+ }),
126
+ addError: assign(function (_ref3) {
127
+ var context = _ref3.context,
128
+ event = _ref3.event;
129
+ if (!event.type.includes('xstate.error.actor')) return context;
130
+ var e = event;
131
+ return {
132
+ errors: [].concat(_toConsumableArray(context.errors), [String(e.error).replace('Error: ', '')])
133
+ };
134
+ }),
135
+ clearErrors: assign(function () {
136
+ return {
137
+ errors: []
138
+ };
139
+ })
140
+ // onLogin: ({ event, self }) => {
141
+ // console.log('onLogin', event, self);
142
+ // return raise({ type: 'AFTER_LOGGED_IN' });
143
+ // if (!event.type.includes('xstate.done.actor')) return;
144
+ // const e = event as DoneActorEvent<AuthenticateSuccessEvent>;
145
+ // if (
146
+ // e.output.type !== 'AUTHENTICATE_SUCCESS' ||
147
+ // self.getSnapshot().value !== 'loggedIn'
148
+ // )
149
+ // return;
150
+ // // eslint-disable-next-line consistent-return
151
+ // return raise({ type: 'AFTER_LOGGED_IN' });
152
+ // // if (!params) return context;
153
+ // // if (!('callback' in params) || typeof params.callback !== 'function')
154
+ // // return context;
155
+ // // params.callback();
156
+ // // return context;
157
+ // },
158
+ },
159
+
160
+ actors: {
161
+ refreshAccessToken: fromPromise(function (_ref4) {
162
+ var input = _ref4.input;
163
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
164
+ var response, res, data, _data;
165
+ return _regeneratorRuntime.wrap(function _callee2$(_context2) {
166
+ while (1) {
167
+ switch (_context2.prev = _context2.next) {
168
+ case 0:
169
+ if (!(typeof window === 'undefined')) {
170
+ _context2.next = 18;
171
+ break;
172
+ }
173
+ if (!(input.context.refreshToken === '')) {
174
+ _context2.next = 3;
175
+ break;
176
+ }
177
+ throw new Error('Unauthorized.');
178
+ case 3:
179
+ _context2.prev = 3;
180
+ _context2.next = 6;
181
+ return axios.post(input.context.endpoints.ssrRefresh, {
182
+ grant_type: 'refresh_token'
183
+ }, {
184
+ headers: {
185
+ Cookie: "refresh_token=".concat(input.context.refreshToken),
186
+ 'Content-Type': 'application/json'
187
+ },
188
+ withCredentials: true
189
+ });
190
+ case 6:
191
+ res = _context2.sent;
192
+ data = res.data;
193
+ if (!(typeof data.accessToken === 'undefined')) {
194
+ _context2.next = 10;
195
+ break;
196
+ }
197
+ throw new Error('Unauthorized.');
198
+ case 10:
199
+ return _context2.abrupt("return", {
200
+ type: 'REFRESH_TOKEN_SUCCESS',
201
+ accessToken: data.accessToken
202
+ });
203
+ case 13:
204
+ _context2.prev = 13;
205
+ _context2.t0 = _context2["catch"](3);
206
+ throw new Error('Could not complete refresh request (server)');
207
+ case 16:
208
+ _context2.next = 25;
209
+ break;
210
+ case 18:
211
+ _context2.next = 20;
212
+ return request(input.context.endpoints.refresh, {
213
+ method: 'POST',
214
+ mode: 'cors',
215
+ credentials: 'include',
216
+ headers: {
217
+ 'Content-Type': 'application/json'
218
+ },
219
+ body: JSON.stringify({
220
+ grant_type: 'refresh_token'
221
+ // client_id: 'default',
222
+ // client_secret: 'Password123!',
223
+ // scope: 'default',
224
+ }).toString()
225
+ });
226
+ case 20:
227
+ response = _context2.sent;
228
+ _data = response;
229
+ if (!(typeof _data.accessToken === 'undefined')) {
230
+ _context2.next = 24;
231
+ break;
232
+ }
233
+ throw new Error('Unauthorized.');
234
+ case 24:
235
+ return _context2.abrupt("return", {
236
+ type: 'REFRESH_TOKEN_SUCCESS',
237
+ accessToken: _data.accessToken
238
+ });
239
+ case 25:
240
+ case "end":
241
+ return _context2.stop();
242
+ }
243
+ }
244
+ }, _callee2, null, [[3, 13]]);
245
+ }));
246
+ }),
247
+ authenticate: fromPromise(function (_ref5) {
248
+ var input = _ref5.input;
249
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
250
+ var _a, _b, response, data;
251
+ return _regeneratorRuntime.wrap(function _callee3$(_context3) {
252
+ while (1) {
253
+ switch (_context3.prev = _context3.next) {
254
+ case 0:
255
+ _context3.next = 2;
256
+ return request(input.context.endpoints.login, {
257
+ method: 'POST',
258
+ mode: 'cors',
259
+ credentials: 'include',
260
+ headers: {
261
+ 'Content-Type': 'application/json'
262
+ },
263
+ body: JSON.stringify({
264
+ username: input.username,
265
+ password: input.password
266
+ }).toString()
267
+ });
268
+ case 2:
269
+ response = _context3.sent;
270
+ /** @todo do we need to handle different status codes here...like what if the service is down? */
271
+ data = response;
272
+ if (data.success) {
273
+ _context3.next = 6;
274
+ break;
275
+ }
276
+ throw new Error((_b = (_a = data.message) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : 'Sign in failed. Please try again.');
277
+ case 6:
278
+ return _context3.abrupt("return", {
279
+ type: 'AUTHENTICATE_SUCCESS',
280
+ // user: data.user,
281
+ accessToken: data.accessToken
282
+ });
283
+ case 7:
284
+ case "end":
285
+ return _context3.stop();
286
+ }
287
+ }
288
+ }, _callee3);
289
+ }));
290
+ }),
291
+ unauthenticate: fromPromise(function (_ref6) {
292
+ var input = _ref6.input;
293
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
294
+ return _regeneratorRuntime.wrap(function _callee4$(_context4) {
295
+ while (1) {
296
+ switch (_context4.prev = _context4.next) {
297
+ case 0:
298
+ _context4.next = 2;
299
+ return fetch(input.context.endpoints.logout, {
300
+ method: 'POST',
301
+ mode: 'cors',
302
+ credentials: 'include'
303
+ // headers: {
304
+ // 'Access-Control-Allow-Origin': 'https://middleware-clicktap.local-rmgmedia.com',
305
+ // 'Access-Control-Allow-Credentials': 'true',
306
+ // },
307
+ });
308
+ case 2:
309
+ return _context4.abrupt("return", {
310
+ type: 'UNAUTHENTICATE'
311
+ });
312
+ case 3:
313
+ case "end":
314
+ return _context4.stop();
315
+ }
316
+ }
317
+ }, _callee4);
318
+ }));
319
+ })
320
+ }
321
+ }).createMachine({
322
+ id: 'auth',
323
+ context: function context(_ref7) {
324
+ var input = _ref7.input;
325
+ var _a, _b, _c, _d;
326
+ return {
327
+ user: null,
328
+ accessToken: '',
329
+ refreshToken: (_b = (_a = input === null || input === void 0 ? void 0 : input.initialContext) === null || _a === void 0 ? void 0 : _a.refreshToken) !== null && _b !== void 0 ? _b : '',
330
+ /**
331
+ * If unauthenticating fails, we need a way to ignore the refresh token on subsequent access token refresh.
332
+ * This would be set to true done/error of unauthenticate service, and false on done of authenticate service
333
+ */
334
+ ignoreRefreshToken: false,
335
+ endpoints: (_d = (_c = input === null || input === void 0 ? void 0 : input.initialContext) === null || _c === void 0 ? void 0 : _c.endpoints) !== null && _d !== void 0 ? _d : {
336
+ login: '',
337
+ logout: '',
338
+ refresh: '',
339
+ ssrRefresh: ''
340
+ },
341
+ errors: []
342
+ };
343
+ },
344
+ initial: 'refreshing',
345
+ states: {
346
+ authenticating: {
347
+ invoke: {
348
+ src: 'authenticate',
349
+ input: function input(_ref8) {
350
+ var context = _ref8.context,
351
+ event = _ref8.event;
352
+ if (event.type !== 'LOGIN') {
353
+ /** @todo how to use error handling here? */
354
+ return {
355
+ context: context,
356
+ username: '',
357
+ password: ''
358
+ };
359
+ }
360
+ return {
361
+ context: context,
362
+ username: event.username,
363
+ password: event.password
364
+ };
365
+ },
366
+ onDone: [{
367
+ actions: 'setUserContext',
368
+ target: 'loggedIn'
369
+ }],
370
+ onError: [{
371
+ actions: 'addError',
372
+ target: 'loggedOut'
373
+ }]
374
+ }
375
+ },
376
+ unauthenticating: {
377
+ invoke: {
378
+ src: 'unauthenticate',
379
+ input: function input(_ref9) {
380
+ var context = _ref9.context;
381
+ return {
382
+ context: context
383
+ };
384
+ },
385
+ onDone: [{
386
+ actions: 'unsetUserContext',
387
+ target: 'loggedOut'
388
+ }],
389
+ onError: [{
390
+ actions: ['unsetUserContext', 'setIgnoreRefreshToken'],
391
+ target: 'loggedOut'
392
+ }]
393
+ }
394
+ },
395
+ refreshing: {
396
+ invoke: {
397
+ src: 'refreshAccessToken',
398
+ input: function input(_ref10) {
399
+ var context = _ref10.context;
400
+ return {
401
+ context: context
402
+ };
403
+ },
404
+ onDone: [{
405
+ actions: ['unsetRefreshToken', 'setAccessToken'],
406
+ target: 'loggedIn'
407
+ }],
408
+ onError: [{
409
+ actions: 'unsetRefreshToken',
410
+ target: 'unauthenticating'
411
+ }]
412
+ }
413
+ },
414
+ loggedOut: {
415
+ on: {
416
+ LOGIN: {
417
+ target: 'authenticating'
418
+ },
419
+ CLEAR_ERRORS: {
420
+ actions: 'clearErrors'
421
+ }
422
+ }
423
+ },
424
+ loggedIn: {
425
+ after: {
426
+ // 14min (840000ms), jwt access token expires in 15min
427
+ 840000: {
428
+ guard: function guard() {
429
+ return typeof window !== 'undefined';
430
+ },
431
+ target: 'refreshing'
432
+ }
433
+ },
434
+ on: {
435
+ LOGOUT: {
436
+ target: 'unauthenticating'
437
+ },
438
+ CLEAR_ERRORS: {
439
+ actions: 'clearErrors'
440
+ }
441
+ // AFTER_LOGGED_IN: {
442
+ // target: 'afterLoggedIn',
443
+ // },
444
+ }
445
+ }
446
+ // onLogin: {
447
+ // always: {
448
+ // target: 'loggedIn',
449
+ // },
450
+ // },
451
+ // afterLoggedOut: {
452
+ // always: {
453
+ // target: 'loggedOut',
454
+ // },
455
+ // },
456
+ }
457
+ });
458
+
459
+ var AuthContext = /*#__PURE__*/createContext({});
460
+ var useAuth = function useAuth() {
461
+ var actor = useContext(AuthContext);
462
+ var _useState = useState(actor.getSnapshot().value === 'loggedIn'),
463
+ isLoggedIn = _useState[0],
464
+ setILoggedIn = _useState[1];
465
+ useEffect(function () {
466
+ var subscription = actor.subscribe(function (observer) {
467
+ if (observer.value === 'loggedIn' || observer.value === 'loggedOut') {
468
+ setILoggedIn(observer.value === 'loggedIn');
469
+ }
470
+ });
471
+ return function () {
472
+ subscription.unsubscribe();
473
+ };
474
+ }, [actor]);
475
+ return {
476
+ authActor: actor,
477
+ isLoggedIn: isLoggedIn
478
+ };
479
+ };
480
+ var useUser = function useUser() {
481
+ return useContext(AuthContext).getSnapshot().context.user;
482
+ };
483
+ /**
484
+ * runs on server side as part of withAuth HOF
485
+ *
486
+ * @todo should probably update signature to pass Partial<AuthContext> and
487
+ * Options, endpoints should probably be moved into context
488
+ */
489
+ var getAuth = function getAuth() {
490
+ var refreshToken = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
491
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
492
+ inspect: undefined,
493
+ endpoints: {
494
+ login: '',
495
+ logout: '',
496
+ refresh: '',
497
+ ssrRefresh: ''
498
+ }
499
+ };
500
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
501
+ return _regeneratorRuntime.wrap(function _callee$(_context) {
502
+ while (1) {
503
+ switch (_context.prev = _context.next) {
504
+ case 0:
505
+ if (!(typeof window !== 'undefined')) {
506
+ _context.next = 3;
507
+ break;
508
+ }
509
+ // eslint-disable-next-line no-console
510
+ console.warn('App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page.');
511
+ return _context.abrupt("return", createActor(authMachine, {
512
+ inspect: options.inspect
513
+ }).start());
514
+ case 3:
515
+ return _context.abrupt("return", createActor(authMachine, {
516
+ input: {
517
+ initialContext: {
518
+ endpoints: options.endpoints,
519
+ refreshToken: refreshToken
520
+ }
521
+ },
522
+ inspect: options.inspect
523
+ }).start());
524
+ case 4:
525
+ case "end":
526
+ return _context.stop();
527
+ }
528
+ }
529
+ }, _callee);
530
+ }));
531
+ };
532
+ function AuthProvider(_ref) {
533
+ var actor = _ref.actor,
534
+ children = _ref.children;
535
+ return jsx(AuthContext.Provider, {
536
+ value: actor,
537
+ children: children
538
+ });
539
+ }
540
+
541
+ var timerMachine = setup({
542
+ types: {
543
+ context: {},
544
+ events: {},
545
+ input: {}
546
+ }
547
+ }).createMachine({
548
+ id: 'timer',
549
+ initial: 'running',
550
+ context: function context(_ref) {
551
+ var input = _ref.input;
552
+ var _a;
553
+ return {
554
+ elapsed: 0,
555
+ duration: (_a = input.initialContext.duration) !== null && _a !== void 0 ? _a : 3000,
556
+ interval: 100,
557
+ intervalId: null
558
+ };
559
+ },
560
+ states: {
561
+ paused: {
562
+ on: {
563
+ // START_TIMER: {
564
+ // target: 'running',
565
+ // cond: (context) => context.elapsed < context.duration,
566
+ // },
567
+ RESUME_TIMER: {
568
+ target: 'running',
569
+ guard: function guard(_ref2) {
570
+ var context = _ref2.context;
571
+ return context.elapsed < context.duration;
572
+ }
573
+ }
574
+ }
575
+ },
576
+ running: {
577
+ // invoke: {
578
+ // src:
579
+ // ({ context }) =>
580
+ // (send) => {
581
+ // // eslint-disable-next-line no-console
582
+ // // console.log('context.interval: ', context.interval);
583
+ // const interval = setInterval(() => {
584
+ // send('TICK');
585
+ // }, context.interval);
586
+ // return () => {
587
+ // clearInterval(interval);
588
+ // };
589
+ // },
590
+ // },
591
+ invoke: {
592
+ input: function input(_ref3) {
593
+ var context = _ref3.context;
594
+ return {
595
+ interval: context.interval
596
+ };
597
+ },
598
+ src: fromCallback(function (_ref4) {
599
+ var sendBack = _ref4.sendBack,
600
+ input = _ref4.input;
601
+ var interval = setInterval(function () {
602
+ sendBack({
603
+ type: 'TICK'
604
+ });
605
+ }, input.interval);
606
+ return function () {
607
+ clearInterval(interval);
608
+ };
609
+ }
610
+ // eslint-disable-next-line @typescript-eslint/require-await
611
+ // async ({ input }) => {
612
+ // console.log('interval: ', input.interval);
613
+ // return { type: 'TICK' };
614
+ // // console.log('in running invoke');
615
+ // // const interval = setInterval(() => {
616
+ // // raise({ type: 'TICK' });
617
+ // // }, input.interval);
618
+ // // return () => {
619
+ // // clearInterval(interval);
620
+ // // };
621
+ // }
622
+ )
623
+ },
624
+
625
+ always: [{
626
+ target: 'completed',
627
+ guard: function guard(_ref5) {
628
+ var context = _ref5.context;
629
+ return context.elapsed >= context.duration;
630
+ }
631
+ }],
632
+ on: {
633
+ TICK: {
634
+ actions: assign(function (_ref6) {
635
+ var context = _ref6.context,
636
+ event = _ref6.event;
637
+ if (event.type !== 'TICK') return context;
638
+ return {
639
+ elapsed: context.elapsed + context.interval
640
+ };
641
+ })
642
+ },
643
+ PAUSE_TIMER: {
644
+ target: 'paused'
645
+ }
646
+ }
647
+ },
648
+ completed: {
649
+ type: 'final'
650
+ }
651
+ }
652
+ });
653
+
654
+ // circular reference, don't want library depending on UI component specific to one app
655
+ // import { Notification } from "@waytrade/components/app/Toast/Notification";
656
+ var toastMachine = setup({
657
+ types: {
658
+ context: {},
659
+ events: {},
660
+ input: {}
661
+ },
662
+ actions: {
663
+ addItem: assign(function (_ref) {
664
+ var context = _ref.context,
665
+ event = _ref.event;
666
+ var _a, _b;
667
+ if (event.type !== 'ADD_ITEM') return context;
668
+ var id = "notification-".concat(crypto.randomBytes(16).toString('hex'));
669
+ var duration = (_a = event.duration) !== null && _a !== void 0 ? _a : context.duration;
670
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
671
+ var notification = /*#__PURE__*/cloneElement(event.item, Object.assign({
672
+ duration: duration,
673
+ id: id,
674
+ key: (_b = event.item.key) !== null && _b !== void 0 ? _b : id
675
+ }, event.item.props));
676
+ var item = {
677
+ duration: duration,
678
+ id: id,
679
+ element: notification
680
+ };
681
+ var updatedItems = context.items;
682
+ if (context.order === 'desc') {
683
+ updatedItems.push(item);
684
+ } else {
685
+ updatedItems.unshift(item);
686
+ }
687
+ return {
688
+ items: updatedItems,
689
+ activeItem: id
690
+ };
691
+ }),
692
+ removeItem: assign(function (_ref2) {
693
+ var context = _ref2.context,
694
+ event = _ref2.event;
695
+ // console.log('toast removeItem event: ', event);
696
+ if (event.type !== 'REMOVE_ITEM' && event.type !== 'xstate.done.actor.timer'
697
+ // event.type !== 'REMOVE_ITEM' &&
698
+ // event.type !== 'xstate.after(ITEM_TIMEOUT)#toast.active' &&
699
+ // event.type !== 'done.invoke.timer'
700
+ ) return context;
701
+ var updatedItems = context.items;
702
+ if (context.order === 'desc') {
703
+ updatedItems.pop();
704
+ return {
705
+ items: updatedItems,
706
+ activeItem: updatedItems.length > 0 ? updatedItems[updatedItems.length - 1].id : null
707
+ };
708
+ }
709
+ updatedItems.shift();
710
+ return {
711
+ items: updatedItems,
712
+ activeItem: updatedItems.length > 0 ? updatedItems[0].id : null
713
+ };
714
+ })
715
+ },
716
+ delays: {
717
+ ITEM_TIMEOUT: function ITEM_TIMEOUT(_ref3) {
718
+ var context = _ref3.context;
719
+ var _a;
720
+ return (_a = context.items[context.items.length - 1].duration) !== null && _a !== void 0 ? _a : context.duration;
721
+ }
722
+ },
723
+ guards: {
724
+ itemHasTimeout: function itemHasTimeout(_ref4) {
725
+ var context = _ref4.context;
726
+ return context.items[context.items.length - 1].duration > 0 || context.duration > 0;
727
+ }
728
+ }
729
+ }).createMachine({
730
+ id: 'toast',
731
+ context: {
732
+ items: [],
733
+ order: 'desc',
734
+ duration: 0,
735
+ activeItem: null
736
+ },
737
+ initial: 'idle',
738
+ states: {
739
+ idle: {
740
+ on: {
741
+ ADD_ITEM: {
742
+ target: 'adding'
743
+ }
744
+ }
745
+ },
746
+ active: {
747
+ invoke: {
748
+ id: 'timer',
749
+ src: timerMachine,
750
+ input: function input(_ref5) {
751
+ var context = _ref5.context;
752
+ var _a;
753
+ return {
754
+ initialContext: {
755
+ duration: (_a = context.items[context.items.length - 1].duration) !== null && _a !== void 0 ? _a : context.duration
756
+ }
757
+ };
758
+ },
759
+ onDone: {
760
+ target: 'removing',
761
+ guard: 'itemHasTimeout'
762
+ }
763
+ // data: Object.assign(timerMachine.context, {
764
+ // duration: (context: ToastMachineContext) =>
765
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return
766
+ // context.items[context.items.length - 1].duration ??
767
+ // context.duration,
768
+ // }),
769
+ },
770
+
771
+ on: {
772
+ ADD_ITEM: {
773
+ // actions: sendTo('timer', 'PAUSE_TIMER'),
774
+ target: 'adding'
775
+ },
776
+ REMOVE_ITEM: {
777
+ target: 'removing'
778
+ },
779
+ SET_IDLE: {
780
+ target: 'idle'
781
+ },
782
+ RESUME_TIMER: {
783
+ actions: sendTo('timer', {
784
+ type: 'RESUME_TIMER'
785
+ })
786
+ // cond: (context) => context.duration > 0,
787
+ },
788
+
789
+ PAUSE_TIMER: {
790
+ actions: sendTo('timer', {
791
+ type: 'PAUSE_TIMER'
792
+ })
793
+ // cond: (context) => context.duration > 0,
794
+ }
795
+ }
796
+ // after: {
797
+ // ITEM_TIMEOUT: {
798
+ // target: 'removing',
799
+ // cond: 'itemHasTimeout',
800
+ // },
801
+ // },
802
+ },
803
+
804
+ adding: {
805
+ entry: ['addItem'],
806
+ on: {
807
+ SET_IDLE: {
808
+ target: 'idle'
809
+ },
810
+ SET_ACTIVE: {
811
+ target: 'active'
812
+ }
813
+ }
814
+ },
815
+ removing: {
816
+ entry: 'removeItem',
817
+ on: {
818
+ SET_IDLE: {
819
+ target: 'idle'
820
+ },
821
+ SET_ACTIVE: {
822
+ target: 'active'
823
+ }
824
+ }
825
+ }
826
+ }
827
+ });
828
+ // export const toastMachine =
829
+ // /** @xstate-layout N4IgpgJg5mDOIC5QBcD2BDWyB0BLCANmAMQCCAIuQPoCSAKgKICyA2gAwC6ioADqrLmS5UAO24gAHogCMAZgCs2AGzS2SgBxKA7AE4lO2ToAsAGhABPRAFoj6gL52zaTDnQBjIQDcSEUWDwinqgA1v5CALZgAE7sXEggfAJCouJSCEpsOspaOQay0kqyAExKZpYIReps2LY6mmxG+kUKWkYOThhY2O5eJBTU9Myx4omCwmLxabKF2NKN8kpFbPls8gpl1vLqykXyasaNhdJFWu0gzl09uN7EAErMAPIAagy0jKycI-xjKZOIi9sDPI9EZgYV1LItBsEIYlNg9NIdGxKki1jkzhdXB5riQAMoMOi0cgAGQYw3io2SE1AaTkWS0RQOSKWEK0c2hzWkNUWJy0Skah1sGM6WN6dwYuIAqkxXnQaDLbuTeN8qakZPIuXylhktAppgUitDilpsJpQeo9KsVOoCsKXN1sTcAAqkSX4qhyhVKhIq8ZqirSbaZeTyLRbVnqVqyaHSaQm45mtirKo6Eo6O2XCAQXAiKDEfGEmgksmfCm+340xC2bCh3XGrTLfR8+TQqxFJbYTIoow6HStBshjOuLM5vMFqikADCcpe3spfr+MKMmsZbDmFvU6jBRtW8I3IcMBT7Q+wUTA4VQnlH+YJRNJc-L1MkiHURiKps0DIWKhyIZjehqfc1h0I8GyUE8zwvK9cxvQkpxnEs4mVJIF0rBBU1kWZVw1WtgSMUwLHVIxsEqIxjVDIF5CFM4RFQCA4HETEvhQitnwQKxYxNOoDFjbQ2RtfRW1kfJO1THjA1sVRZBPfAiGYn4nzSKx9D3cS+MDI9-zhWot2A0C1BPK5vHk1VF1kIwuOZPICmKYEtMAuoDxAptlkMkdcxM1C2MMYjKhKXUlH5DUimkVsijImsxMMcLpjDUMIPPS9R081i0i3OE10afI42XcKW0ImFgRrYE5FBWx1F2cyHAcIA */
830
+ // createMachine<ToastMachineContext, ToastMachineEvents>(
831
+ // {
832
+ // context: { items: [], order: 'desc', duration: 0, activeItem: null },
833
+ // predictableActionArguments: true,
834
+ // id: 'toast',
835
+ // initial: 'idle',
836
+ // states: {
837
+ // idle: {
838
+ // on: {
839
+ // ADD_ITEM: {
840
+ // target: 'adding',
841
+ // },
842
+ // },
843
+ // },
844
+ // active: {
845
+ // invoke: {
846
+ // id: 'timer',
847
+ // src: timerMachine,
848
+ // onDone: {
849
+ // target: 'removing',
850
+ // cond: 'itemHasTimeout',
851
+ // },
852
+ // data: Object.assign(timerMachine.context, {
853
+ // duration: (context: ToastMachineContext) =>
854
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return
855
+ // context.items[context.items.length - 1].duration ??
856
+ // context.duration,
857
+ // }),
858
+ // },
859
+ // on: {
860
+ // ADD_ITEM: {
861
+ // // actions: sendTo('timer', 'PAUSE_TIMER'),
862
+ // target: 'adding',
863
+ // },
864
+ // REMOVE_ITEM: {
865
+ // target: 'removing',
866
+ // },
867
+ // SET_IDLE: {
868
+ // target: 'idle',
869
+ // },
870
+ // RESUME_TIMER: {
871
+ // actions: sendTo('timer', 'RESUME_TIMER'),
872
+ // // cond: (context) => context.duration > 0,
873
+ // },
874
+ // PAUSE_TIMER: {
875
+ // actions: sendTo('timer', 'PAUSE_TIMER'),
876
+ // // cond: (context) => context.duration > 0,
877
+ // },
878
+ // },
879
+ // // after: {
880
+ // // ITEM_TIMEOUT: {
881
+ // // target: 'removing',
882
+ // // cond: 'itemHasTimeout',
883
+ // // },
884
+ // // },
885
+ // },
886
+ // adding: {
887
+ // entry: ['addItem'],
888
+ // on: {
889
+ // SET_IDLE: {
890
+ // target: 'idle',
891
+ // },
892
+ // SET_ACTIVE: {
893
+ // target: 'active',
894
+ // },
895
+ // },
896
+ // },
897
+ // removing: {
898
+ // entry: 'removeItem',
899
+ // on: {
900
+ // SET_IDLE: {
901
+ // target: 'idle',
902
+ // },
903
+ // SET_ACTIVE: {
904
+ // target: 'active',
905
+ // },
906
+ // },
907
+ // },
908
+ // },
909
+ // },
910
+ // {
911
+ // actions: {
912
+ // addItem: assign((context, event) => {
913
+ // if (event.type !== 'ADD_ITEM') return;
914
+ // const id = `notification-${crypto.randomBytes(16).toString('hex')}`;
915
+ // const duration = event.duration ?? context.duration;
916
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
917
+ // const notification = cloneElement(event.item, {
918
+ // duration,
919
+ // id,
920
+ // key: event.item.key ?? id,
921
+ // ...event.item.props,
922
+ // });
923
+ // const item = {
924
+ // duration,
925
+ // id,
926
+ // element: notification,
927
+ // };
928
+ // if (context.order === 'desc') {
929
+ // context.items.push(item);
930
+ // } else {
931
+ // context.items.unshift(item);
932
+ // }
933
+ // context.activeItem = id;
934
+ // }),
935
+ // removeItem: assign((context, event) => {
936
+ // if (
937
+ // event.type !== 'REMOVE_ITEM' &&
938
+ // event.type !== 'xstate.after(ITEM_TIMEOUT)#toast.active' &&
939
+ // event.type !== 'done.invoke.timer'
940
+ // )
941
+ // return;
942
+ // if (context.order === 'desc') {
943
+ // context.items.pop();
944
+ // context.activeItem =
945
+ // context.items.length > 0
946
+ // ? context.items[context.items.length - 1].id
947
+ // : null;
948
+ // } else {
949
+ // context.items.shift();
950
+ // context.activeItem =
951
+ // context.items.length > 0 ? context.items[0].id : null;
952
+ // }
953
+ // }),
954
+ // // startTimer: sendTo('timer', { type: 'START' }),
955
+ // },
956
+ // delays: {
957
+ // ITEM_TIMEOUT: (context) => {
958
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-return
959
+ // return (
960
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
961
+ // context.items[context.items.length - 1].duration ?? context.duration
962
+ // );
963
+ // },
964
+ // },
965
+ // guards: {
966
+ // itemHasTimeout: (context) => {
967
+ // return (
968
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
969
+ // context.items[context.items.length - 1].duration > 0 ||
970
+ // context.duration > 0
971
+ // );
972
+ // },
973
+ // },
974
+ // }
975
+ // );
976
+
977
+ var ToastContext = /*#__PURE__*/createContext({});
978
+ var useToast = function useToast() {
979
+ return useContext(ToastContext);
980
+ };
981
+ function ToastProvider(_ref) {
982
+ var children = _ref.children,
983
+ actor = _ref.actor;
984
+ // const toastService = interpret(toastMachine, {
985
+ // devTools: options.devTools,
986
+ // }).start(state);
987
+ // toastService.subscribe((s) => {
988
+ // setState(s);
989
+ // });
990
+ return jsx(ToastContext.Provider, {
991
+ value: actor,
992
+ children: children
993
+ });
994
+ }
995
+
996
+ export { AuthContext, AuthProvider, ToastContext, ToastProvider, authMachine, getAuth, timerMachine, toastMachine, useAuth, useToast, useUser };