-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
1453 lines (1453 loc) · 76.7 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
// NOTE: GENERATED by github.com/mjl-/sherpats, DO NOT MODIFY
var api;
(function (api) {
// How often a user wants to receive update notification email messages.
let Interval;
(function (Interval) {
Interval["IntervalImmediate"] = "immediate";
Interval["IntervalHour"] = "hour";
Interval["IntervalDay"] = "day";
Interval["IntervalWeek"] = "week";
})(Interval = api.Interval || (api.Interval = {}));
api.structTypes = { "Home": true, "Hook": true, "HookConfig": true, "HookResult": true, "ModuleUpdate": true, "ModuleUpdateURLs": true, "Overview": true, "Recent": true, "Subscription": true, "SubscriptionImport": true, "UpdateHook": true, "UserLog": true };
api.stringsTypes = { "Interval": true };
api.intsTypes = {};
api.types = {
"Overview": { "Name": "Overview", "Docs": "", "Fields": [{ "Name": "Email", "Docs": "", "Typewords": ["string"] }, { "Name": "UpdateInterval", "Docs": "", "Typewords": ["Interval"] }, { "Name": "MetaUnsubscribed", "Docs": "", "Typewords": ["bool"] }, { "Name": "UpdatesUnsubscribed", "Docs": "", "Typewords": ["bool"] }, { "Name": "Backoff", "Docs": "", "Typewords": ["string"] }, { "Name": "BackoffUntil", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "SkipModulePaths", "Docs": "", "Typewords": ["[]", "string"] }, { "Name": "Subscriptions", "Docs": "", "Typewords": ["[]", "Subscription"] }, { "Name": "ModuleUpdates", "Docs": "", "Typewords": ["[]", "ModuleUpdateURLs"] }, { "Name": "HookConfigs", "Docs": "", "Typewords": ["[]", "HookConfig"] }, { "Name": "RecentHooks", "Docs": "", "Typewords": ["[]", "UpdateHook"] }, { "Name": "UserLogs", "Docs": "", "Typewords": ["[]", "UserLog"] }] },
"Subscription": { "Name": "Subscription", "Docs": "", "Fields": [{ "Name": "ID", "Docs": "", "Typewords": ["int64"] }, { "Name": "Module", "Docs": "", "Typewords": ["string"] }, { "Name": "BelowModule", "Docs": "", "Typewords": ["bool"] }, { "Name": "OlderVersions", "Docs": "", "Typewords": ["bool"] }, { "Name": "Prerelease", "Docs": "", "Typewords": ["bool"] }, { "Name": "Pseudo", "Docs": "", "Typewords": ["bool"] }, { "Name": "Comment", "Docs": "", "Typewords": ["string"] }, { "Name": "HookConfigID", "Docs": "", "Typewords": ["int64"] }] },
"ModuleUpdateURLs": { "Name": "ModuleUpdateURLs", "Docs": "", "Fields": [{ "Name": "ID", "Docs": "", "Typewords": ["int64"] }, { "Name": "UserID", "Docs": "", "Typewords": ["int64"] }, { "Name": "SubscriptionID", "Docs": "", "Typewords": ["int64"] }, { "Name": "LogRecordID", "Docs": "", "Typewords": ["int64"] }, { "Name": "Discovered", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "Module", "Docs": "", "Typewords": ["string"] }, { "Name": "Version", "Docs": "", "Typewords": ["string"] }, { "Name": "MessageID", "Docs": "", "Typewords": ["int64"] }, { "Name": "HookID", "Docs": "", "Typewords": ["int64"] }, { "Name": "HookConfigID", "Docs": "", "Typewords": ["int64"] }, { "Name": "RepoURL", "Docs": "", "Typewords": ["string"] }, { "Name": "TagURL", "Docs": "", "Typewords": ["string"] }, { "Name": "DocURL", "Docs": "", "Typewords": ["string"] }] },
"HookConfig": { "Name": "HookConfig", "Docs": "", "Fields": [{ "Name": "ID", "Docs": "", "Typewords": ["int64"] }, { "Name": "UserID", "Docs": "", "Typewords": ["int64"] }, { "Name": "Name", "Docs": "", "Typewords": ["string"] }, { "Name": "URL", "Docs": "", "Typewords": ["string"] }, { "Name": "Headers", "Docs": "", "Typewords": ["[]", "[]", "string"] }, { "Name": "Disabled", "Docs": "", "Typewords": ["bool"] }] },
"UpdateHook": { "Name": "UpdateHook", "Docs": "", "Fields": [{ "Name": "Update", "Docs": "", "Typewords": ["ModuleUpdate"] }, { "Name": "Hook", "Docs": "", "Typewords": ["Hook"] }] },
"ModuleUpdate": { "Name": "ModuleUpdate", "Docs": "", "Fields": [{ "Name": "ID", "Docs": "", "Typewords": ["int64"] }, { "Name": "UserID", "Docs": "", "Typewords": ["int64"] }, { "Name": "SubscriptionID", "Docs": "", "Typewords": ["int64"] }, { "Name": "LogRecordID", "Docs": "", "Typewords": ["int64"] }, { "Name": "Discovered", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "Module", "Docs": "", "Typewords": ["string"] }, { "Name": "Version", "Docs": "", "Typewords": ["string"] }, { "Name": "MessageID", "Docs": "", "Typewords": ["int64"] }, { "Name": "HookID", "Docs": "", "Typewords": ["int64"] }, { "Name": "HookConfigID", "Docs": "", "Typewords": ["int64"] }] },
"Hook": { "Name": "Hook", "Docs": "", "Fields": [{ "Name": "ID", "Docs": "", "Typewords": ["int64"] }, { "Name": "UserID", "Docs": "", "Typewords": ["int64"] }, { "Name": "HookConfigID", "Docs": "", "Typewords": ["int64"] }, { "Name": "URL", "Docs": "", "Typewords": ["string"] }, { "Name": "Queued", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "LastResult", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "Attempts", "Docs": "", "Typewords": ["int32"] }, { "Name": "NextAttempt", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "Done", "Docs": "", "Typewords": ["bool"] }, { "Name": "Results", "Docs": "", "Typewords": ["[]", "HookResult"] }] },
"HookResult": { "Name": "HookResult", "Docs": "", "Fields": [{ "Name": "StatusCode", "Docs": "", "Typewords": ["int32"] }, { "Name": "Error", "Docs": "", "Typewords": ["string"] }, { "Name": "Response", "Docs": "", "Typewords": ["string"] }, { "Name": "Start", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "DurationMS", "Docs": "", "Typewords": ["int64"] }] },
"UserLog": { "Name": "UserLog", "Docs": "", "Fields": [{ "Name": "ID", "Docs": "", "Typewords": ["int64"] }, { "Name": "UserID", "Docs": "", "Typewords": ["int64"] }, { "Name": "Time", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "Text", "Docs": "", "Typewords": ["string"] }] },
"SubscriptionImport": { "Name": "SubscriptionImport", "Docs": "", "Fields": [{ "Name": "GoMod", "Docs": "", "Typewords": ["string"] }, { "Name": "BelowModule", "Docs": "", "Typewords": ["bool"] }, { "Name": "OlderVersions", "Docs": "", "Typewords": ["bool"] }, { "Name": "Prerelease", "Docs": "", "Typewords": ["bool"] }, { "Name": "Pseudo", "Docs": "", "Typewords": ["bool"] }, { "Name": "Comment", "Docs": "", "Typewords": ["string"] }, { "Name": "HookConfigID", "Docs": "", "Typewords": ["int64"] }, { "Name": "Indirect", "Docs": "", "Typewords": ["bool"] }] },
"Home": { "Name": "Home", "Docs": "", "Fields": [{ "Name": "Version", "Docs": "", "Typewords": ["string"] }, { "Name": "GoVersion", "Docs": "", "Typewords": ["string"] }, { "Name": "GoOS", "Docs": "", "Typewords": ["string"] }, { "Name": "GoArch", "Docs": "", "Typewords": ["string"] }, { "Name": "ServiceName", "Docs": "", "Typewords": ["string"] }, { "Name": "AdminName", "Docs": "", "Typewords": ["string"] }, { "Name": "AdminEmail", "Docs": "", "Typewords": ["string"] }, { "Name": "Note", "Docs": "", "Typewords": ["string"] }, { "Name": "SignupNote", "Docs": "", "Typewords": ["string"] }, { "Name": "SkipModulePrefixes", "Docs": "", "Typewords": ["[]", "string"] }, { "Name": "SignupEmailDisabled", "Docs": "", "Typewords": ["bool"] }, { "Name": "SignupWebsiteDisabled", "Docs": "", "Typewords": ["bool"] }, { "Name": "SignupAddress", "Docs": "", "Typewords": ["string"] }, { "Name": "Recents", "Docs": "", "Typewords": ["[]", "Recent"] }] },
"Recent": { "Name": "Recent", "Docs": "", "Fields": [{ "Name": "Module", "Docs": "", "Typewords": ["string"] }, { "Name": "Version", "Docs": "", "Typewords": ["string"] }, { "Name": "Discovered", "Docs": "", "Typewords": ["timestamp"] }, { "Name": "RepoURL", "Docs": "", "Typewords": ["string"] }, { "Name": "TagURL", "Docs": "", "Typewords": ["string"] }, { "Name": "DocURL", "Docs": "", "Typewords": ["string"] }] },
"Interval": { "Name": "Interval", "Docs": "", "Values": [{ "Name": "IntervalImmediate", "Value": "immediate", "Docs": "" }, { "Name": "IntervalHour", "Value": "hour", "Docs": "" }, { "Name": "IntervalDay", "Value": "day", "Docs": "" }, { "Name": "IntervalWeek", "Value": "week", "Docs": "" }] },
};
api.parser = {
Overview: (v) => api.parse("Overview", v),
Subscription: (v) => api.parse("Subscription", v),
ModuleUpdateURLs: (v) => api.parse("ModuleUpdateURLs", v),
HookConfig: (v) => api.parse("HookConfig", v),
UpdateHook: (v) => api.parse("UpdateHook", v),
ModuleUpdate: (v) => api.parse("ModuleUpdate", v),
Hook: (v) => api.parse("Hook", v),
HookResult: (v) => api.parse("HookResult", v),
UserLog: (v) => api.parse("UserLog", v),
SubscriptionImport: (v) => api.parse("SubscriptionImport", v),
Home: (v) => api.parse("Home", v),
Recent: (v) => api.parse("Recent", v),
Interval: (v) => api.parse("Interval", v),
};
// API holds functions for the frontend.
let defaultOptions = { slicesNullable: true, mapsNullable: true, nullableOptional: true };
class Client {
baseURL;
authState;
options;
constructor() {
this.authState = {};
this.options = { ...defaultOptions };
this.baseURL = this.options.baseURL || api.defaultBaseURL;
}
withAuthToken(token) {
const c = new Client();
c.authState.token = token;
c.options = this.options;
return c;
}
withOptions(options) {
const c = new Client();
c.authState = this.authState;
c.options = { ...this.options, ...options };
return c;
}
// Signup registers a new account. We send an email for users to verify they
// control the email address. If we already have a verified account, we send a
// password reset instead.
async Signup(prepToken, email) {
const fn = "Signup";
const paramTypes = [["string"], ["string"]];
const returnTypes = [];
const params = [prepToken, email];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SignupEmail returns the email address for a verify token. So we can show it, and
// the user can get prompted for saving full full login credentials by a password
// manager after verifying the signup.
async SignupEmail(prepToken, verifyToken) {
const fn = "SignupEmail";
const paramTypes = [["string"], ["string"]];
const returnTypes = [["string"]];
const params = [prepToken, verifyToken];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// VerifySignup verifies a new account by checking the token. The token was in the
// URL in the signup email.
async VerifySignup(prepToken, verifyToken, email, password) {
const fn = "VerifySignup";
const paramTypes = [["string"], ["string"], ["string"], ["string"]];
const returnTypes = [["string"]];
const params = [prepToken, verifyToken, email, password];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// UserRemove lets a user remove their account.
async UserRemove() {
const fn = "UserRemove";
const paramTypes = [];
const returnTypes = [];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Redeem turns a login token, as used in login-links in notification emails, into
// a session by returning a csrf token and setting a session cookie.
async Redeem(prepToken, loginToken) {
const fn = "Redeem";
const paramTypes = [["string"], ["string"]];
const returnTypes = [["string"]];
const params = [prepToken, loginToken];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// RequestPasswordReset requests a password reset. We send an email with a link
// with a password reset token.
async RequestPasswordReset(prepToken, email) {
const fn = "RequestPasswordReset";
const paramTypes = [["string"], ["string"]];
const returnTypes = [];
const params = [prepToken, email];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// ResetPassword resets a password for an account based on a token.
async ResetPassword(prepToken, email, password, resetToken) {
const fn = "ResetPassword";
const paramTypes = [["string"], ["string"], ["string"], ["string"]];
const returnTypes = [];
const params = [prepToken, email, password, resetToken];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Prep helps prevent CSRF calls. It must be called before calling functions like
// Login, Subscribe. It returns a token, which it also sets as a samesite cookie.
// The subsequent call must pass in the token, and the request must have the cookie
// set.
async Prep() {
const fn = "Prep";
const paramTypes = [];
const returnTypes = [["string"]];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Login verifies the accounts password and creates a new session, returning a csrf
// token that must be present in an x-csrf header in subsequent calls. A same-site
// cookie is set too.
async Login(prepToken, email, password) {
const fn = "Login";
const paramTypes = [["string"], ["string"], ["string"]];
const returnTypes = [["string"]];
const params = [prepToken, email, password];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Logout clears the session cookie. It does not invalidate the session.
async Logout() {
const fn = "Logout";
const paramTypes = [];
const returnTypes = [];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Overview returns data needed for the overview page, after logging in.
async Overview() {
const fn = "Overview";
const paramTypes = [];
const returnTypes = [["Overview"]];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SubscribeSet changes either meta (service messages) or module updates
// subscriptions. If not subscribed, no messages are sent.
async SubscribeSet(meta, subscribed) {
const fn = "SubscribeSet";
const paramTypes = [["bool"], ["bool"]];
const returnTypes = [];
const params = [meta, subscribed];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SetInterval sets a new minimum interval between update messages.
async IntervalSet(interval) {
const fn = "IntervalSet";
const paramTypes = [["Interval"]];
const returnTypes = [];
const params = [interval];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SubscriptionCreate adds a new subscription to a module.
async SubscriptionCreate(sub) {
const fn = "SubscriptionCreate";
const paramTypes = [["Subscription"]];
const returnTypes = [["Subscription"]];
const params = [sub];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SubscriptionImport parses a go.mod file and subscribes to all direct and
// optionally indirect dependencies.
async SubscriptionImport(imp) {
const fn = "SubscriptionImport";
const paramTypes = [["SubscriptionImport"]];
const returnTypes = [["[]", "Subscription"]];
const params = [imp];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SubscriptionSave updates an existing subscription to a module.
async SubscriptionSave(sub) {
const fn = "SubscriptionSave";
const paramTypes = [["Subscription"]];
const returnTypes = [];
const params = [sub];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// SubscriptionRemove removes an existing subscription.
async SubscriptionRemove(subID) {
const fn = "SubscriptionRemove";
const paramTypes = [["int64"]];
const returnTypes = [];
const params = [subID];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Home returns data for the home page.
async Home() {
const fn = "Home";
const paramTypes = [];
const returnTypes = [["Home"]];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Recents returns more recent packages, currently 150.
async Recents() {
const fn = "Recents";
const paramTypes = [];
const returnTypes = [["[]", "Recent"]];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
// Forward tries a bit harder to forward the transparency log. While we
// periodically fetch the /latest database tree state and forward the log, at
// least sum.golang.org only returns new values about once every 10 minutes.
// But we can look at the latest additions to index.golang.org and get the most
// recently added module from it, then look it up to get the associated tree
// state and forward based on that.
async Forward() {
const fn = "Forward";
const paramTypes = [];
const returnTypes = [];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
async TestSend(secret, kind, email) {
const fn = "TestSend";
const paramTypes = [["string"], ["string"], ["string"]];
const returnTypes = [];
const params = [secret, kind, email];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
async HookConfigAdd(hc) {
const fn = "HookConfigAdd";
const paramTypes = [["HookConfig"]];
const returnTypes = [["HookConfig"]];
const params = [hc];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
async HookConfigSave(hc) {
const fn = "HookConfigSave";
const paramTypes = [["HookConfig"]];
const returnTypes = [];
const params = [hc];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
async HookConfigRemove(hcID) {
const fn = "HookConfigRemove";
const paramTypes = [["int64"]];
const returnTypes = [];
const params = [hcID];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
async HookCancel(hID) {
const fn = "HookCancel";
const paramTypes = [["int64"]];
const returnTypes = [["Hook"]];
const params = [hID];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
async HookKick(hID) {
const fn = "HookKick";
const paramTypes = [["int64"]];
const returnTypes = [["Hook"]];
const params = [hID];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
}
}
api.Client = Client;
api.defaultBaseURL = (function () {
let p = location.pathname;
if (p && p[p.length - 1] !== '/') {
let l = location.pathname.split('/');
l = l.slice(0, l.length - 1);
p = '/' + l.join('/') + '/';
}
return location.protocol + '//' + location.host + p + 'api/';
})();
// NOTE: code below is shared between github.com/mjl-/sherpaweb and github.com/mjl-/sherpats.
// KEEP IN SYNC.
api.supportedSherpaVersion = 1;
// verifyArg typechecks "v" against "typewords", returning a new (possibly modified) value for JSON-encoding.
// toJS indicate if the data is coming into JS. If so, timestamps are turned into JS Dates. Otherwise, JS Dates are turned into strings.
// allowUnknownKeys configures whether unknown keys in structs are allowed.
// types are the named types of the API.
api.verifyArg = (path, v, typewords, toJS, allowUnknownKeys, types, opts) => {
return new verifier(types, toJS, allowUnknownKeys, opts).verify(path, v, typewords);
};
api.parse = (name, v) => api.verifyArg(name, v, [name], true, false, api.types, defaultOptions);
class verifier {
types;
toJS;
allowUnknownKeys;
opts;
constructor(types, toJS, allowUnknownKeys, opts) {
this.types = types;
this.toJS = toJS;
this.allowUnknownKeys = allowUnknownKeys;
this.opts = opts;
}
verify(path, v, typewords) {
typewords = typewords.slice(0);
const ww = typewords.shift();
const error = (msg) => {
if (path != '') {
msg = path + ': ' + msg;
}
throw new Error(msg);
};
if (typeof ww !== 'string') {
error('bad typewords');
return; // should not be necessary, typescript doesn't see error always throws an exception?
}
const w = ww;
const ensure = (ok, expect) => {
if (!ok) {
error('got ' + JSON.stringify(v) + ', expected ' + expect);
}
return v;
};
switch (w) {
case 'nullable':
if (v === null || v === undefined && this.opts.nullableOptional) {
return v;
}
return this.verify(path, v, typewords);
case '[]':
if (v === null && this.opts.slicesNullable || v === undefined && this.opts.slicesNullable && this.opts.nullableOptional) {
return v;
}
ensure(Array.isArray(v), "array");
return v.map((e, i) => this.verify(path + '[' + i + ']', e, typewords));
case '{}':
if (v === null && this.opts.mapsNullable || v === undefined && this.opts.mapsNullable && this.opts.nullableOptional) {
return v;
}
ensure(v !== null || typeof v === 'object', "object");
const r = {};
for (const k in v) {
r[k] = this.verify(path + '.' + k, v[k], typewords);
}
return r;
}
ensure(typewords.length == 0, "empty typewords");
const t = typeof v;
switch (w) {
case 'any':
return v;
case 'bool':
ensure(t === 'boolean', 'bool');
return v;
case 'int8':
case 'uint8':
case 'int16':
case 'uint16':
case 'int32':
case 'uint32':
case 'int64':
case 'uint64':
ensure(t === 'number' && Number.isInteger(v), 'integer');
return v;
case 'float32':
case 'float64':
ensure(t === 'number', 'float');
return v;
case 'int64s':
case 'uint64s':
ensure(t === 'number' && Number.isInteger(v) || t === 'string', 'integer fitting in float without precision loss, or string');
return '' + v;
case 'string':
ensure(t === 'string', 'string');
return v;
case 'timestamp':
if (this.toJS) {
ensure(t === 'string', 'string, with timestamp');
const d = new Date(v);
if (d instanceof Date && !isNaN(d.getTime())) {
return d;
}
error('invalid date ' + v);
}
else {
ensure(t === 'object' && v !== null, 'non-null object');
ensure(v.__proto__ === Date.prototype, 'Date');
return v.toISOString();
}
}
// We're left with named types.
const nt = this.types[w];
if (!nt) {
error('unknown type ' + w);
}
if (v === null) {
error('bad value ' + v + ' for named type ' + w);
}
if (api.structTypes[nt.Name]) {
const t = nt;
if (typeof v !== 'object') {
error('bad value ' + v + ' for struct ' + w);
}
const r = {};
for (const f of t.Fields) {
r[f.Name] = this.verify(path + '.' + f.Name, v[f.Name], f.Typewords);
}
// If going to JSON also verify no unknown fields are present.
if (!this.allowUnknownKeys) {
const known = {};
for (const f of t.Fields) {
known[f.Name] = true;
}
Object.keys(v).forEach((k) => {
if (!known[k]) {
error('unknown key ' + k + ' for struct ' + w);
}
});
}
return r;
}
else if (api.stringsTypes[nt.Name]) {
const t = nt;
if (typeof v !== 'string') {
error('mistyped value ' + v + ' for named strings ' + t.Name);
}
if (!t.Values || t.Values.length === 0) {
return v;
}
for (const sv of t.Values) {
if (sv.Value === v) {
return v;
}
}
error('unknown value ' + v + ' for named strings ' + t.Name);
}
else if (api.intsTypes[nt.Name]) {
const t = nt;
if (typeof v !== 'number' || !Number.isInteger(v)) {
error('mistyped value ' + v + ' for named ints ' + t.Name);
}
if (!t.Values || t.Values.length === 0) {
return v;
}
for (const sv of t.Values) {
if (sv.Value === v) {
return v;
}
}
error('unknown value ' + v + ' for named ints ' + t.Name);
}
else {
throw new Error('unexpected named type ' + nt);
}
}
}
const _sherpaCall = async (baseURL, authState, options, paramTypes, returnTypes, name, params) => {
if (!options.skipParamCheck) {
if (params.length !== paramTypes.length) {
return Promise.reject({ message: 'wrong number of parameters in sherpa call, saw ' + params.length + ' != expected ' + paramTypes.length });
}
params = params.map((v, index) => api.verifyArg('params[' + index + ']', v, paramTypes[index], false, false, api.types, options));
}
const simulate = async (json) => {
const config = JSON.parse(json || 'null') || {};
const waitMinMsec = config.waitMinMsec || 0;
const waitMaxMsec = config.waitMaxMsec || 0;
const wait = Math.random() * (waitMaxMsec - waitMinMsec);
const failRate = config.failRate || 0;
return new Promise((resolve, reject) => {
if (options.aborter) {
options.aborter.abort = () => {
reject({ message: 'call to ' + name + ' aborted by user', code: 'sherpa:aborted' });
reject = resolve = () => { };
};
}
setTimeout(() => {
const r = Math.random();
if (r < failRate) {
reject({ message: 'injected failure on ' + name, code: 'server:injected' });
}
else {
resolve();
}
reject = resolve = () => { };
}, waitMinMsec + wait);
});
};
// Only simulate when there is a debug string. Otherwise it would always interfere
// with setting options.aborter.
let json = '';
try {
json = window.localStorage.getItem('sherpats-debug') || '';
}
catch (err) { }
if (json) {
await simulate(json);
}
const fn = (resolve, reject) => {
let resolve1 = (v) => {
resolve(v);
resolve1 = () => { };
reject1 = () => { };
};
let reject1 = (v) => {
if ((v.code === 'user:noAuth' || v.code === 'user:badAuth') && options.login) {
const login = options.login;
if (!authState.loginPromise) {
authState.loginPromise = new Promise((aresolve, areject) => {
login(v.code === 'user:badAuth' ? (v.message || '') : '')
.then((token) => {
authState.token = token;
authState.loginPromise = undefined;
aresolve();
}, (err) => {
authState.loginPromise = undefined;
areject(err);
});
});
}
authState.loginPromise
.then(() => {
fn(resolve, reject);
}, (err) => {
reject(err);
});
return;
}
reject(v);
resolve1 = () => { };
reject1 = () => { };
};
const url = baseURL + name;
const req = new window.XMLHttpRequest();
if (options.aborter) {
options.aborter.abort = () => {
req.abort();
reject1({ code: 'sherpa:aborted', message: 'request aborted' });
};
}
req.open('POST', url, true);
if (options.csrfHeader && authState.token) {
req.setRequestHeader(options.csrfHeader, authState.token);
}
if (options.timeoutMsec) {
req.timeout = options.timeoutMsec;
}
req.onload = () => {
if (req.status !== 200) {
if (req.status === 404) {
reject1({ code: 'sherpa:badFunction', message: 'function does not exist' });
}
else {
reject1({ code: 'sherpa:http', message: 'error calling function, HTTP status: ' + req.status });
}
return;
}
let resp;
try {
resp = JSON.parse(req.responseText);
}
catch (err) {
reject1({ code: 'sherpa:badResponse', message: 'bad JSON from server' });
return;
}
if (resp && resp.error) {
const err = resp.error;
reject1({ code: err.code, message: err.message });
return;
}
else if (!resp || !resp.hasOwnProperty('result')) {
reject1({ code: 'sherpa:badResponse', message: "invalid sherpa response object, missing 'result'" });
return;
}
if (options.skipReturnCheck) {
resolve1(resp.result);
return;
}
let result = resp.result;
try {
if (returnTypes.length === 0) {
if (result) {
throw new Error('function ' + name + ' returned a value while prototype says it returns "void"');
}
}
else if (returnTypes.length === 1) {
result = api.verifyArg('result', result, returnTypes[0], true, true, api.types, options);
}
else {
if (result.length != returnTypes.length) {
throw new Error('wrong number of values returned by ' + name + ', saw ' + result.length + ' != expected ' + returnTypes.length);
}
result = result.map((v, index) => api.verifyArg('result[' + index + ']', v, returnTypes[index], true, true, api.types, options));
}
}
catch (err) {
let errmsg = 'bad types';
if (err instanceof Error) {
errmsg = err.message;
}
reject1({ code: 'sherpa:badTypes', message: errmsg });
}
resolve1(result);
};
req.onerror = () => {
reject1({ code: 'sherpa:connection', message: 'connection failed' });
};
req.ontimeout = () => {
reject1({ code: 'sherpa:timeout', message: 'request timeout' });
};
req.setRequestHeader('Content-Type', 'application/json');
try {
req.send(JSON.stringify({ params: params }));
}
catch (err) {
reject1({ code: 'sherpa:badData', message: 'cannot marshal to JSON' });
}
};
return await new Promise(fn);
};
})(api || (api = {}));
// Javascript is generated from typescript, do not modify generated javascript because changes will be overwritten.
const [dom, style, attr, prop] = (function () {
// Start of unicode block (rough approximation of script), from https://www.unicode.org/Public/UNIDATA/Blocks.txt
const scriptblocks = [0x0000, 0x0080, 0x0100, 0x0180, 0x0250, 0x02B0, 0x0300, 0x0370, 0x0400, 0x0500, 0x0530, 0x0590, 0x0600, 0x0700, 0x0750, 0x0780, 0x07C0, 0x0800, 0x0840, 0x0860, 0x0870, 0x08A0, 0x0900, 0x0980, 0x0A00, 0x0A80, 0x0B00, 0x0B80, 0x0C00, 0x0C80, 0x0D00, 0x0D80, 0x0E00, 0x0E80, 0x0F00, 0x1000, 0x10A0, 0x1100, 0x1200, 0x1380, 0x13A0, 0x1400, 0x1680, 0x16A0, 0x1700, 0x1720, 0x1740, 0x1760, 0x1780, 0x1800, 0x18B0, 0x1900, 0x1950, 0x1980, 0x19E0, 0x1A00, 0x1A20, 0x1AB0, 0x1B00, 0x1B80, 0x1BC0, 0x1C00, 0x1C50, 0x1C80, 0x1C90, 0x1CC0, 0x1CD0, 0x1D00, 0x1D80, 0x1DC0, 0x1E00, 0x1F00, 0x2000, 0x2070, 0x20A0, 0x20D0, 0x2100, 0x2150, 0x2190, 0x2200, 0x2300, 0x2400, 0x2440, 0x2460, 0x2500, 0x2580, 0x25A0, 0x2600, 0x2700, 0x27C0, 0x27F0, 0x2800, 0x2900, 0x2980, 0x2A00, 0x2B00, 0x2C00, 0x2C60, 0x2C80, 0x2D00, 0x2D30, 0x2D80, 0x2DE0, 0x2E00, 0x2E80, 0x2F00, 0x2FF0, 0x3000, 0x3040, 0x30A0, 0x3100, 0x3130, 0x3190, 0x31A0, 0x31C0, 0x31F0, 0x3200, 0x3300, 0x3400, 0x4DC0, 0x4E00, 0xA000, 0xA490, 0xA4D0, 0xA500, 0xA640, 0xA6A0, 0xA700, 0xA720, 0xA800, 0xA830, 0xA840, 0xA880, 0xA8E0, 0xA900, 0xA930, 0xA960, 0xA980, 0xA9E0, 0xAA00, 0xAA60, 0xAA80, 0xAAE0, 0xAB00, 0xAB30, 0xAB70, 0xABC0, 0xAC00, 0xD7B0, 0xD800, 0xDB80, 0xDC00, 0xE000, 0xF900, 0xFB00, 0xFB50, 0xFE00, 0xFE10, 0xFE20, 0xFE30, 0xFE50, 0xFE70, 0xFF00, 0xFFF0, 0x10000, 0x10080, 0x10100, 0x10140, 0x10190, 0x101D0, 0x10280, 0x102A0, 0x102E0, 0x10300, 0x10330, 0x10350, 0x10380, 0x103A0, 0x10400, 0x10450, 0x10480, 0x104B0, 0x10500, 0x10530, 0x10570, 0x10600, 0x10780, 0x10800, 0x10840, 0x10860, 0x10880, 0x108E0, 0x10900, 0x10920, 0x10980, 0x109A0, 0x10A00, 0x10A60, 0x10A80, 0x10AC0, 0x10B00, 0x10B40, 0x10B60, 0x10B80, 0x10C00, 0x10C80, 0x10D00, 0x10E60, 0x10E80, 0x10EC0, 0x10F00, 0x10F30, 0x10F70, 0x10FB0, 0x10FE0, 0x11000, 0x11080, 0x110D0, 0x11100, 0x11150, 0x11180, 0x111E0, 0x11200, 0x11280, 0x112B0, 0x11300, 0x11400, 0x11480, 0x11580, 0x11600, 0x11660, 0x11680, 0x11700, 0x11800, 0x118A0, 0x11900, 0x119A0, 0x11A00, 0x11A50, 0x11AB0, 0x11AC0, 0x11B00, 0x11C00, 0x11C70, 0x11D00, 0x11D60, 0x11EE0, 0x11F00, 0x11FB0, 0x11FC0, 0x12000, 0x12400, 0x12480, 0x12F90, 0x13000, 0x13430, 0x14400, 0x16800, 0x16A40, 0x16A70, 0x16AD0, 0x16B00, 0x16E40, 0x16F00, 0x16FE0, 0x17000, 0x18800, 0x18B00, 0x18D00, 0x1AFF0, 0x1B000, 0x1B100, 0x1B130, 0x1B170, 0x1BC00, 0x1BCA0, 0x1CF00, 0x1D000, 0x1D100, 0x1D200, 0x1D2C0, 0x1D2E0, 0x1D300, 0x1D360, 0x1D400, 0x1D800, 0x1DF00, 0x1E000, 0x1E030, 0x1E100, 0x1E290, 0x1E2C0, 0x1E4D0, 0x1E7E0, 0x1E800, 0x1E900, 0x1EC70, 0x1ED00, 0x1EE00, 0x1F000, 0x1F030, 0x1F0A0, 0x1F100, 0x1F200, 0x1F300, 0x1F600, 0x1F650, 0x1F680, 0x1F700, 0x1F780, 0x1F800, 0x1F900, 0x1FA00, 0x1FA70, 0x1FB00, 0x20000, 0x2A700, 0x2B740, 0x2B820, 0x2CEB0, 0x2F800, 0x30000, 0x31350, 0xE0000, 0xE0100, 0xF0000, 0x100000];
// Find block code belongs in.
const findBlock = (code) => {
let s = 0;
let e = scriptblocks.length;
while (s < e - 1) {
let i = Math.floor((s + e) / 2);
if (code < scriptblocks[i]) {
e = i;
}
else {
s = i;
}
}
return s;
};
// formatText adds s to element e, in a way that makes switching unicode scripts
// clear, with alternating DOM TextNode and span elements with a "switchscript"
// class. Useful for highlighting look alikes, e.g. a (ascii 0x61) and а (cyrillic
// 0x430).
//
// This is only called one string at a time, so the UI can still display strings
// without highlighting switching scripts, by calling formatText on the parts.
const formatText = (e, s) => {
// Handle some common cases quickly.
if (!s) {
return;
}
let ascii = true;
for (const c of s) {
const cp = c.codePointAt(0); // For typescript, to check for undefined.
if (cp !== undefined && cp >= 0x0080) {
ascii = false;
break;
}
}
if (ascii) {
e.appendChild(document.createTextNode(s));
return;
}
// todo: handle grapheme clusters? wait for Intl.Segmenter?
let n = 0; // Number of text/span parts added.
let str = ''; // Collected so far.
let block = -1; // Previous block/script.
let mod = 1;
const put = (nextblock) => {
if (n === 0 && nextblock === 0) {
// Start was non-ascii, second block is ascii, we'll start marked as switched.
mod = 0;
}
if (n % 2 === mod) {
const x = document.createElement('span');
x.classList.add('scriptswitch');
x.appendChild(document.createTextNode(str));
e.appendChild(x);
}
else {
e.appendChild(document.createTextNode(str));
}
n++;
str = '';
};
for (const c of s) {
// Basic whitespace does not switch blocks. Will probably need to extend with more
// punctuation in the future. Possibly for digits too. But perhaps not in all
// scripts.
if (c === ' ' || c === '\t' || c === '\r' || c === '\n') {
str += c;
continue;
}
const code = c.codePointAt(0);
if (block < 0 || !(code >= scriptblocks[block] && (code < scriptblocks[block + 1] || block === scriptblocks.length - 1))) {
const nextblock = code < 0x0080 ? 0 : findBlock(code);
if (block >= 0) {
put(nextblock);
}
block = nextblock;
}
str += c;
}
put(-1);
};
const _domKids = (e, l) => {
l.forEach((c) => {
const xc = c;
if (typeof c === 'string') {
formatText(e, c);
}
else if (c instanceof String) {
// String is an escape-hatch for text that should not be formatted with
// unicode-block-change-highlighting, e.g. for textarea values.
e.appendChild(document.createTextNode('' + c));
}
else if (c instanceof Element) {
e.appendChild(c);
}
else if (c instanceof Function) {
if (!c.name) {
throw new Error('function without name');
}
e.addEventListener(c.name, c);
}
else if (Array.isArray(xc)) {
_domKids(e, c);
}
else if (xc._class) {
for (const s of xc._class) {
e.classList.toggle(s, true);
}
}
else if (xc._attrs) {
for (const k in xc._attrs) {
e.setAttribute(k, xc._attrs[k]);
}
}
else if (xc._styles) {
for (const k in xc._styles) {
const estyle = e.style;
estyle[k] = xc._styles[k];
}
}
else if (xc._props) {
for (const k in xc._props) {
const eprops = e;
eprops[k] = xc._props[k];
}
}
else if (xc.root) {
e.appendChild(xc.root);
}
else {
console.log('bad kid', c);
throw new Error('bad kid');
}
});
return e;
};
const dom = {
_kids: function (e, ...kl) {
while (e.firstChild) {
e.removeChild(e.firstChild);
}
_domKids(e, kl);
},
_attrs: (x) => { return { _attrs: x }; },
_class: (...x) => { return { _class: x }; },
// The createElement calls are spelled out so typescript can derive function
// signatures with a specific HTML*Element return type.
div: (...l) => _domKids(document.createElement('div'), l),
span: (...l) => _domKids(document.createElement('span'), l),
a: (...l) => _domKids(document.createElement('a'), l),
input: (...l) => _domKids(document.createElement('input'), l),
textarea: (...l) => _domKids(document.createElement('textarea'), l),
select: (...l) => _domKids(document.createElement('select'), l),
option: (...l) => _domKids(document.createElement('option'), l),
clickbutton: (...l) => _domKids(document.createElement('button'), [attr.type('button'), ...l]),
submitbutton: (...l) => _domKids(document.createElement('button'), [attr.type('submit'), ...l]),
form: (...l) => _domKids(document.createElement('form'), l),
fieldset: (...l) => _domKids(document.createElement('fieldset'), l),
table: (...l) => _domKids(document.createElement('table'), l),
thead: (...l) => _domKids(document.createElement('thead'), l),
tbody: (...l) => _domKids(document.createElement('tbody'), l),
tfoot: (...l) => _domKids(document.createElement('tfoot'), l),
tr: (...l) => _domKids(document.createElement('tr'), l),
td: (...l) => _domKids(document.createElement('td'), l),
th: (...l) => _domKids(document.createElement('th'), l),
datalist: (...l) => _domKids(document.createElement('datalist'), l),
h1: (...l) => _domKids(document.createElement('h1'), l),
h2: (...l) => _domKids(document.createElement('h2'), l),
h3: (...l) => _domKids(document.createElement('h3'), l),
br: (...l) => _domKids(document.createElement('br'), l),
hr: (...l) => _domKids(document.createElement('hr'), l),
pre: (...l) => _domKids(document.createElement('pre'), l),
label: (...l) => _domKids(document.createElement('label'), l),
ul: (...l) => _domKids(document.createElement('ul'), l),
li: (...l) => _domKids(document.createElement('li'), l),
iframe: (...l) => _domKids(document.createElement('iframe'), l),
b: (...l) => _domKids(document.createElement('b'), l),
img: (...l) => _domKids(document.createElement('img'), l),
style: (...l) => _domKids(document.createElement('style'), l),
search: (...l) => _domKids(document.createElement('search'), l),
p: (...l) => _domKids(document.createElement('p'), l),
dl: (...l) => _domKids(document.createElement('dl'), l),
dt: (...l) => _domKids(document.createElement('dt'), l),
dd: (...l) => _domKids(document.createElement('dd'), l),
};
const _attr = (k, v) => { const o = {}; o[k] = v; return { _attrs: o }; };
const attr = {
title: (s) => _attr('title', s),
value: (s) => _attr('value', s),
type: (s) => _attr('type', s),
tabindex: (s) => _attr('tabindex', s),
src: (s) => _attr('src', s),
placeholder: (s) => _attr('placeholder', s),
href: (s) => _attr('href', s),
checked: (s) => _attr('checked', s),
selected: (s) => _attr('selected', s),
id: (s) => _attr('id', s),
datalist: (s) => _attr('datalist', s),
rows: (s) => _attr('rows', s),
target: (s) => _attr('target', s),
rel: (s) => _attr('rel', s),
required: (s) => _attr('required', s),
multiple: (s) => _attr('multiple', s),
download: (s) => _attr('download', s),
disabled: (s) => _attr('disabled', s),
draggable: (s) => _attr('draggable', s),
rowspan: (s) => _attr('rowspan', s),
colspan: (s) => _attr('colspan', s),
for: (s) => _attr('for', s),
role: (s) => _attr('role', s),
arialabel: (s) => _attr('aria-label', s),
arialive: (s) => _attr('aria-live', s),
name: (s) => _attr('name', s),
min: (s) => _attr('min', s),
max: (s) => _attr('max', s),
action: (s) => _attr('action', s),
method: (s) => _attr('method', s),
autocomplete: (s) => _attr('autocomplete', s),
};
const style = (x) => { return { _styles: x }; };
const prop = (x) => { return { _props: x }; };
return [dom, style, attr, prop];
})();
const errmsg = (err) => '' + (err.message || '(no error message)');
const zindexes = {
popup: '1',
login: '2',
};
const check = async (elem, fn) => {
elem.disabled = true;
document.body.classList.toggle('loading', true);
try {
return await fn();
}
catch (err) {
console.log('error', err);
window.alert('Error: ' + errmsg(err));
throw err;
}
finally {
document.body.classList.toggle('loading', false);
elem.disabled = false;
}
};
let popupOpen = false;
const popup = (...kids) => {
const origFocus = document.activeElement;
const close = () => {
if (!root.parentNode) {
return;
}
popupOpen = false;
root.remove();
if (origFocus && origFocus instanceof HTMLElement && origFocus.parentNode) {
origFocus.focus();
}
};
let content;
const root = dom.div(style({ position: 'fixed', top: 0, right: 0, bottom: 0, left: 0, backgroundColor: 'rgba(0, 0, 0, 0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: zindexes.popup }), function keydown(e) {
if (e.key === 'Escape') {
e.stopPropagation();
close();
}
}, function click(e) {
e.stopPropagation();
close();
}, content = dom.div(attr.tabindex('0'), style({ backgroundColor: 'white', borderRadius: '.25em', padding: '1em', boxShadow: '0 0 20px rgba(0, 0, 0, 0.1)', border: '1px solid #ddd', maxWidth: '95vw', overflowX: 'auto', maxHeight: '95vh', overflowY: 'auto' }), function click(e) {
e.stopPropagation();
}, kids));
popupOpen = true;
document.body.appendChild(root);
content.focus();
return close;
};
let loginOpen = false;
const login = async (reason) => {
return new Promise((resolve, _) => {
const origFocus = document.activeElement;
let reasonElem;
let fieldset;
let autosize;
let username;
let password;
const root = dom.div(style({ position: 'fixed', top: 0, right: 0, bottom: 0, left: 0, backgroundColor: '#eee', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: zindexes.login, animation: 'fadein .15s ease-in' }), dom.div(reasonElem = reason ? dom.div(style({ marginBottom: '2ex', textAlign: 'center' }), reason) : dom.div(), dom.div(style({ backgroundColor: 'white', borderRadius: '.25em', padding: '1em', boxShadow: '0 0 20px rgba(0, 0, 0, 0.1)', border: '1px solid #ddd', maxWidth: '95vw', overflowX: 'auto', maxHeight: '95vh', overflowY: 'auto', marginBottom: '20vh' }), dom.form(async function submit(e) {
e.preventDefault();
e.stopPropagation();
reasonElem.remove();
await check(fieldset, async () => {
const prepToken = await client.Prep();
const csrftoken = await client.Login(prepToken, username.value, password.value);
localStorageSet("gopherwatchcsrftoken", csrftoken);
root.remove();
loginOpen = false;
if (origFocus && origFocus instanceof HTMLElement && origFocus.parentNode) {
origFocus.focus();
}
resolve(csrftoken);
});
}, fieldset = dom.fieldset(dom.h1('Login'), dom.label(style({ display: 'block', marginBottom: '2ex' }), dom.div('Email address', style({ marginBottom: '.5ex' })), autosize = dom.span(dom._class('autosize'), username = dom.input(attr.required(''), function change() { autosize.dataset.value = username.value; }, function input() { autosize.dataset.value = username.value; }))), dom.label(style({ display: 'block', marginBottom: '2ex' }), dom.div('Password', style({ marginBottom: '.5ex' })), password = dom.input(attr.type('password'), attr.required(''))), dom.div(style({ textAlign: 'center' }), dom.submitbutton('Login')), dom.br(), dom.div(style({ fontSize: '.85em' }), dom.a(attr.href('#'), 'Forgot password?', function click(e) {
e.preventDefault();
requestPasswordReset();
})))))));
document.body.appendChild(root);
document.body.classList.toggle('loading', false);
username.focus();
loginOpen = true;
});
};
const passwordResetRequested = () => {
dom._kids(document.body, dom.div(dom._class('page'), dom.h1('Password reset requested!'), dom.p("We've sent you an email with a link for a password reset."), dom.p("Unless we've received too many request to send email to your address recently. Or if there is no account for your email address."), dom.p(dom.a(attr.href('#'), 'To home', function click() {
// Reload to get rid of the login window that may still be capturing auth api errors.
window.location.hash = '#';
window.location.reload();
}))));
};
const requestPasswordReset = () => {
let fieldset;
let email;
dom._kids(document.body, dom.div(dom._class('page'), dom.h1('Request password reset'), dom.p("We'll send you an email with a link with which you can set a new password."), dom.form(async function submit(e) {
e.preventDefault();
e.stopPropagation();
await check(fieldset, async () => {
const prepToken = await client.Prep();
await client.RequestPasswordReset(prepToken, email.value);
passwordResetRequested();
});
}, fieldset = dom.fieldset(dom.label('Email address', dom.div(email = dom.input(attr.type('email'), attr.required('')))), dom.br(), dom.div(dom.submitbutton('Request password reset'))))));
email.focus();
};
// localstorage that ignores errors (e.g. in private mode).
const localStorageGet = (k) => {
try {
return JSON.parse(window.localStorage.getItem(k) || '');
}
catch (err) {
return '';
}
};
const localStorageSet = (k, v) => {
try {
window.localStorage.setItem(k, JSON.stringify(v));
}
catch (err) { }
};
let client;
const reinitClient = () => {
client = new api.Client().withOptions({ csrfHeader: 'x-csrf', login: login }).withAuthToken(localStorageGet('gopherwatchcsrftoken') || '');
};
reinitClient();
const subscriptionPopup = (sub, subscriptions, hookconfigs, render) => {
let fieldset;
let module;
let gomod;
let modulegomod;
let indirect;
let belowModule;