-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloudflare_as_name.js
1324 lines (1255 loc) · 62.6 KB
/
cloudflare_as_name.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";
export async function fetch (a1,a2,a3) {
return fCB(a1,a2,a3);
};
let v8start;
let textEnc = new TextEncoder();
let curTime;
const lirr_headers = {
headers: {
'accept-version': '3.0'
}
};
//https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304
//says include Content-Location, I am leaving it out
const copy_res_headers = ["age", "cache-control", "date", "etag", "expires", "last-modified", "vary"];
/*html-minifier will remove spaces and extra "s, DONT change tags, this station list is injected*/
/*STARTINSERT*/
var s={"0AR":"Ardsley-on-Hudson","0BC":"Beacon","0BK":"Breakneck Ridge","0CS":"Cold Spring","0CT":"Cortlandt","0DF":"Dobbs Ferry","0DV":"Spuyten Duyvil","0GA":"Garrison","0GD":"Glenwood","0GY":"Greystone","0HB":"Highbridge-Employees","0HL":"Harlem-125 St","0HM":"Croton-Harmon","0HS":"Hastings-on-Hudson","0IV":"Irvington","0LU":"Ludlow","0MB":"Marble Hill","0MH":"Morris Heights","0MN":"Manitou","0NM":"New Hamburg","0NY":"Grand Central","0OS":"Ossining","0PE":"Peekskill","0PM":"Philipse Manor","0PO":"Poughkeepsie","0RV":"Riverdale","0SB":"Scarborough","0TT":"Tarrytown","0UH":"University Heights","0YK":"Yonkers","0YS":"Yankees-E 153 St","1AT":"Appalachian Trail","1BG":"Botanical Garden","1BH":"Bedford Hills","1BR":"Southeast","1BW":"Brewster","1BX":"Bronxville","1CF":"Croton Falls","1CQ":"Chappaqua","1CW":"Crestwood","1DO":"Dover Plains","1FO":"Fordham","1FW":"Fleetwood","1GO":"Goldens Bridge","1HA":"Hartsdale","1HN":"Hawthorne","1KA":"Katonah","1MK":"Mt Kisco","1ML":"Melrose","1MP":"Mt Pleasant","1MW":"Mt Vernon West","1NW":"North White Plains","1PA":"Patterson","1PV":"Pleasantville","1PW":"Pawling","1PY":"Purdy's","1SC":"Scarsdale","1TK":"Tuckahoe","1TM":"Tenmile River","1TR":"Tremont","1VA":"Valhalla","1WA":"Wassaic","1WF":"Wakefield","1WG":"Williams Bridge","1WI":"Harlem Valley-Wingdale","1WN":"Woodlawn","1WP":"White Plains","2BP":"Bridgeport","2CC":"Cos Cob","2DA":"Darien","2EN":"East Norwalk","2FF":"Fairfield","2FM":"Fairfield Metro","2GF":"Green's Farms","2GN":"Greenwich","2HS":"Harrison","2LA":"Larchmont","2MA":"Mamaroneck","2ME":"Mt Vernon East","2MI":"Milford","2NH":"New Haven","2NO":"Noroton Heights","2NR":"New Rochelle","2OG":"Old Greenwich","2PC":"Port Chester","2PH":"Pelham","2RO":"Rowayton","2RS":"Riverside","2RY":"Rye","2SM":"Stamford","2SN":"South Norwalk","2SP":"Southport","2SR":"Stratford","2SS":"New Haven-State St","2WH":"West Haven","2WP":"Westport","3GB":"Glenbrook","3NC":"New Canaan","3SD":"Springdale","3TH":"Talmadge Hill","4BE":"Bethel","4BV":"Branchville","4CA":"Cannondale","4DN":"Danbury","4M7":"Merritt 7","4RD":"Redding","4WI":"Wilton","5AN":"Ansonia","5BF":"Beacon Falls","5DB":"Derby-Shelton","5NG":"Naugatuck","5SY":"Seymour","5WB":"Waterbury","ABT":"Albertson","ADL":"Auburndale","AGT":"Amagansett","ATL":"Atlantic Terminal","AVL":"Amityville","BDY":"Broadway","BHN":"Bridgehampton","BK":"Stony Brook","BMR":"Bellmore","BOL":"Bolands-Employees","BPG":"Bethpage","BPT":"Bellport","BRS":"Bellerose","BRT":"Belmont Park","BSD":"Bayside","BSR":"Bay Shore","BTA":"Babylon","BWD":"Brentwood","BWN":"Baldwin","CAV":"Centre Av","CHT":"Cedarhurst","CI":"Central Islip","CLP":"Country Life Press","CPG":"Copiague","CPL":"Carle Place","CSH":"Cold Spring Harbor","DGL":"Douglaston","DPK":"Deer Park","EHN":"East Hampton","EMT":"Elmont-UBS Arena","ENY":"East New York","ERY":"East Rockaway","EWN":"East Williston","FHL":"Forest Hills","FLS":"Flushing Main Street","FMD":"Farmingdale","FPK":"Floral Park","FPT":"Freeport","FRY":"Far Rockaway","GBN":"Gibson","GCT":"Grand Central","GCV":"Glen Cove","GCY":"Garden City","GHD":"Glen Head","GNK":"Great Neck","GPT":"Greenport","GRV":"Great River","GST":"Glen Street","GVL":"Greenvale","GWN":"Greenlawn","HBY":"Hampton Bays","HEM":"Hempstead","HGN":"Hempstead Gardens","HIL":"Hillside-Employees","HOL":"Hollis","HPA":"Hunterspoint Av","HUN":"Huntington","HVL":"Hicksville","HWT":"Hewlett","IPK":"Island Park","ISP":"Islip","IWD":"Inwood","JAM":"Jamaica","KGN":"Kew Gardens","KPK":"Kings Park","LBH":"Long Beach","LCE":"Lawrence","LHT":"Lindenhurst","LIC":"Long Island City","LMR":"Locust Manor","LNK":"Little Neck","LTN":"Laurelton","LVL":"Locust Valley","LVW":"Lakeview","LYN":"Lynbrook","MAK":"Mattituck","MAV":"Merillon Av","MFD":"Medford","MHL":"Murray Hill","MHT":"Manhasset","MIN":"Mineola","MPK":"Massapequa Park","MQA":"Massapequa","MRK":"Merrick","MSY":"Mastic-Shirley","MTK":"Montauk","MVN":"Malverne","NAV":"Nostrand Av","NBD":"Nassau Blvd","NHP":"New Hyde Park","NPT":"Northport","NYK":"Penn Station","OBY":"Oyster Bay","ODE":"Oceanside","ODL":"Oakdale","PDM":"Plandome","PGE":"Patchogue","PJN":"Port Jefferson","PLN":"Pinelawn","PWS":"Port Washington","QVG":"Queens Village","RHD":"Riverhead","RON":"Ronkonkoma","ROS":"Rosedale","RSN":"Roslyn","RVC":"Rockville Centre","SAB":"St. Albans","SCF":"Sea Cliff","SFD":"Seaford","SHD":"Southold","SHN":"Southampton","SJM":"St. James","SMR":"Stewart Manor","SPK":"Speonk","SSM":"Mets-Willets Point","STN":"Smithtown","SVL":"Sayville","SYT":"Syosset","VSM":"Valley Stream","WBY":"Westbury","WDD":"Woodside","WGH":"Wantagh","WHD":"West Hempstead","WHN":"Westhampton","WMR":"Woodmere","WWD":"Westwood","WYD":"Wyandanch","YPK":"Yaphank","_GC":"Grand Central"};
/*ENDINSERT*/
/*STARTSUBCOLOR*/
var colorStrsSUB = ["00933c","ff6319","6d6e71","fccc0a","ee352e","286ded","b933ad","0078c6","996633"];
var colorRoutesSUB = {/*"6X":0,*//*"5":0,*//*"4":0,*//*"5X":0,*//*"6":0,*/"B":1,"FX":1,"F":1,"M":1,"D":1,"FS":2,"S":2,"H":2,"GS":2,"Q":3,"W":3,"N":3,"R":3,"1":4,"3":4,"2":4,"A":5,"E":5,"C":5,"7X":6,"7":6,"SI":7,"SIR":7,"J":8,"Z":8,"G":"6cbe45","L":"a7a9ac"};
/*ENDSUBCOLOR*/
/*STARTRAILCOLOR*/
var colorStrsRAIL = ["ee0034","4d5357","006ec7"];
var colorRoutesRAIL = {/*"NH":0,*//*"DN":0,*//*"NC":0,*//*"WB":0,*/"12":1,"CI":1,"HH":2,"PJ":2,"BY":"00985f","HU":"009b3a","WH":"00a1de","OB":"00af3f","MK":"00b2a9","HA":"066afe","11":"60269e","S":"6d6e71","FR":"6e3219","RK":"a626aa","PW":"c60c30","HM":"ce8e00","LB":"ff6319"};
/*ENDRAILCOLOR*/
/*
//src for as.js, I manually send thru mini, careful, do not let isTM var optimize away!!!!
//verified that addASname() is local var/not global, this a func exp, not func decl in JS
var R;
!function addASname() {
if (this.y) {
//note pSib executes for body tag's last el/tag, but
//our empty div never last element
for (var e = document.body.lastChild; e = e.previousSibling; )
if ("DIV" === e.nodeName && !e.firstChild) {
e.style.minHeight = '';
e.appendChild(document.createTextNode("Your ISP: 72.229.160.32 | AS12271 | US | arin | 2000-06-09 | TWC-12271-NYC, US"));
//let UA do batched paint cycles, 1000/30fps=33 ms
(this.requestIdleCallback || this.requestAnimationFrame || function(callback){setTimeout(callback, 40)})(function() {
try {
//note actual height of AS Name div, is .1 to .9px bigger
//clientHeight is rounded down upto .9999 px
//my testing with devtools shows fav DIV does not move at all
//during rmv minHeight+add Text Node even with minHeight being .1 px smaller than
//final height of AS Name div
//https://stackoverflow.com/questions/4106538/difference-between-offsetheight-and-clientheight
localStorage.setItem("as",e.clientHeight + "px");
} catch (err) {
}
});
//wipe mem
return;
}
} else {
R = addASname;
}
//undef is returned per JS std
}();
*/
/* ASN/ISP lookup cloudflare worker script */
function mkJSResp(str,etag) {
// escape/prevent double quotes code injection
// never optimize to .parentNode.innerText, not FF1-FF44 compat, all other yes
return new Response(
'var R;!function e(){if(this.y){for(var t=document.body.lastChild;t=t.previousSibling;)if("DIV"===t.nodeName&&!t.firstChild)return t.style.minHeight="",t.appendChild(document.createTextNode('
+JSON.stringify(str)+
')),void(this.requestIdleCallback||this.requestAnimationFrame||function(e){setTimeout(e,40)})(function(){try{localStorage.setItem("as",t.clientHeight+"px")}catch(e){}})}else R=e}()'
, {
headers: {
"content-type": "text/javascript",
"cache-control":"no-cache",
...etag
}
})
}
async function fCB(request, env, ctx) {
if (!v8start) {
v8start = Date.now()
};
console.log('v8start ' + v8start);
try {
return handleRequest(request, env, ctx).catch(e => console.log(e));
} catch (e) {
console.log(e + ' ' + e.stack + ' ' + e.columnNumber + e.fileName + e.lineNumber);
//event.respondWith(new Response(e))
}
}
//typ a .replace() CB, but manual call sometimes
function mkSubFontTag(tag_unused, route) {
tag_unused = colorRoutesSUB[route];
if(typeof tag_unused !== 'string') {
tag_unused = colorRoutesSUB[route] = colorStrsSUB[tag_unused|0]; //undef to 0
}
return '<font color='+tag_unused+'>['+route+']</font>';
}
/* from status.htm not rstop.htm, slighly bigger */
function noPTag(str) {
if(typeof str == 'string') {
//some notices include these at the end, after the global P tag we are trying to remove
str = str.replace(/(<p style="min-height:10px"><\/p>|<p><\/p>)+$/g,'');
if (str.indexOf('<p>') === 0 && str.indexOf('</p>', str.length - 4) !== -1) {
return str.slice(3, -4);
}
}
return str;
}
//t = "2021-05-11T18:58:08-04:00" getFormattedTime
/* unused since switch from abs time to Mins
function getFormattedTime(t) {
var e = parseIsoDatetime(t),
h = e.getHours(),
m = e.getMinutes(),
a = h > 12 ? h - 12 : h;
return (0 === a ? "12" : a)+ ":"+(m < 10 ? "0" + m : m)+" "+(h > 11 ? "PM" : "AM");
}
*/
/* mislabeled now */
function parseIsoDatetime(dt,i) {
dt = dt.split(/[: T-]/);
for(i in dt)
dt[i] = parseFloat(dt[i]);
//return //modified by bulk88 to be mins away instead of parse, Math.floor->0|
//factoring out Math.abs to x < 0 ? -x : x primative increased gz 4 bytes
return 'Min '+(0|(Math.abs((
new Date(dt[0], dt[1] - 1, dt[2], dt[3] || 0, dt[4] || 0, dt[5] || 0, 0)
- curTime) / 1e3) / 60));
}
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request, env, ctx) {
var url = new URL(request.url)
,pathname_callback = url.pathname
,resp, str;
//console.log(pathname_callback);
if (pathname_callback === '/jsp') {
var headers = {}, str2, rheaders, i = 0;
if((pathname_callback = url.searchParams.get('url')) !== null) {
pathname_callback = decodeURIComponent(pathname_callback);
if(pathname_callback.startsWith('//')) {
pathname_callback = 'http:'+pathname_callback; //perf
}
str = new URL(pathname_callback);
} else {
return new Response(null, {
status: 400
});
}
//anti-abuse
if((str = str.host) === 'otp-mta-prod.camsys-apps.com'
|| str === 'collector-otp-prod.camsys-apps.com'
|| str === 'api.weather.com'
|| str === 'backend-unified.mylirr.org') {
if(str = (rheaders = request.headers).get('if-none-match')) {
headers['if-none-match'] = str;
}
if(str = rheaders.get('if-modified-since')) {
headers['if-modified-since'] = str;
}
if(str = url.searchParams.get('headers')) {
//add anti-abuse header name checks against blacklist in CORS spec if 3rd party use
Object.assign(headers, JSON.parse(decodeURIComponent(str)));
}
resp = fetch(pathname_callback,{headers: headers});
//from express, but guarenteed JSONP no CORS
pathname_callback = (url.searchParams.get('callback') || '_xcallback').replace(/[^\[\]\w$.]/g, '');
pathname_callback = '/**/ typeof ' + pathname_callback + ' === \'function\' && ' + pathname_callback + '({http_code:';
headers = {
'content-type': 'text/javascript',
//from express
"x-content-type-options": 'nosniff',
};
resp = await resp;
//no-store and IE 6, script file downloaded over the wire
//but never executes, default to no-cache if server omits
headers['cache-control'] = (str = (rheaders = resp.headers).get('cache-control')) ? str : 'no-cache';
while(str = copy_res_headers[i++]) {
if(str2 = rheaders.get(str)) {
headers[str] = str2;
}
}
if(resp.status !== 304) {
str = resp.headers.get('content-type');
pathname_callback += resp.status + ',content_type:\'' + str + '\',contents:';
resp = await resp.text();
return new Response(pathname_callback
+ (url.searchParams.get('type') !== 'text'
&& str.startsWith('application/json')
// from express
? resp.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')
: JSON.stringify(resp))
+ '});'
, {headers: headers}
);
} else {
return new Response(null, {
status: 304,
headers: headers,
});
}
} else {
return new Response(null, {
status: 403
});
}
}
else if (pathname_callback.startsWith('/s/')) {
pathname_callback = pathname_callback.substr(('/s/'.length), 3);
if (/^\w+$/.test(pathname_callback)) {
var url_headsign = "http://otp-mta-prod.camsys-apps.com/otp/routers/default/nearby?timerange=1800&apikey=Z276E3rCeTzOQEoBPPN4JCEc6GfvdnYE&stops=MTASBWY:" + pathname_callback;
resp = fetch(url_headsign);
var h = '<meta content=0 name=mobileoptimized>[1][<a accesskey=1 href=' + pathname_callback + '>Refresh</a>] <a href=' + url_headsign + '>Raw</a><br>';
var hotkeys = [2,3,4,5,6,7,8,9,0];
resp = await resp;
if (resp.status == 200) {
resp = resp.json();
var hotkey_timestamp = 0;
resp = await resp;
/*h=html*/
var i, route, trip, alerts, o = {}, r = resp;
if (r.length) {
//initial array is for a geosearch with multiple stations, not exact sta
r = r[0];
alerts = r.alerts;
//server returns sorted by route, we want sort by dir
for (i in r.groups) {
route = r.groups[i];
/*h=headsign*/
//less lines/better UI on phone
url_headsign = route.headsign.replace('Downtown & Brooklyn', 'Downtown & Bklyn');
for (i in route.times) {
trip = route.times[i];
trip.shortRouteName = route.route.shortName;
trip.timestamp > hotkey_timestamp && (hotkey_timestamp = trip.timestamp);
(o[url_headsign] = o[url_headsign] || []).push(trip);
}
}
for (i in o) //object keys
//alpha sort ISO 8601 timestamps
o[i].sort(function(a, b) {
return a.departureFmt < b.departureFmt ? -1 :
a.departureFmt > b.departureFmt ? 1 :
0;
});
/* departureFmt becomes UI time eventually
return _.each(t.times, function(t) {
e.times.push({
stopId: t.stopId,
realtime: t.realtime,
status: t.realtimeState,
departure: t.departureFmt,
pattern: t.pattern ? t.pattern.id : null,
tripHeadsign: t.tripHeadsign ? t.tripHeadsign.toLowerCase() : "",
tripId: t.tripId,
serviceDay: t.serviceDay,
directionId: t.directionId
})
}), e
*/
h += new Date(hotkey_timestamp*1000).toLocaleTimeString('en-US', { timeZone: 'America/New_York' })
+ " via CFW<br>"
+ 'CurSta:' + r.stop.name + "<br>";
curTime = (new Date(new Date().toLocaleString('en-US', { timeZone: 'America/New_York' })));
for (i in o) { //object keys
h += '<a accesskey='+(hotkey_timestamp=hotkeys.shift())+' name='+hotkey_timestamp+' href=#'+hotkey_timestamp+'>'+i+"</a><br>";
//route is dir really
route = o[i];
for (i in route) {
//if departureDelay > 0
//todo (49620-49080)/60 = 9 mins late
//MN/LIR algo, NYCT reports also
//realtimeDeparture: 49620
//scheduledDeparture: 49080
trip = route[i];
h += parseIsoDatetime(trip.departureFmt) +
'-' + mkSubFontTag(0,trip.shortRouteName) +
'-' + trip.tripHeadsign +
//disable track numbers, nobody cares, this isn't Commuter rail
//'-Tk' + (trip.track === void 0 ? '?' : ' ' + trip.track ) +
(trip.track === void 0 ? '-Tk?' : '') +
(trip.realtime ? '-' : '-NRT-') +
(function(rts) {
switch (rts) {
case "SCHEDULED":
return "SCH";
case "UPDATED":
return "UPD";
case "CANCELED":
return "CNX";
case "ADDED":
return "ADD";
case "MODIFIED":
return "MOD";
default:
return "UNK";
}
})(trip.realtimeState)
/* delay can be neg, chop off fractional,
OTP overflow bug on "service day", scheduledDeparture is seconds
since midnight of yesterday, realtimeDeparture is seconds since
midnight of today, happens right after 1200AM */
+
((trip = ((((trip = trip.departureDelay) < -43200 ?
trip + 86400 : trip) / 60) | 0)) ? (trip > 0 ? '-L' : '-E') + Math.abs(trip) : '') + "<br>";
}
}
h += '<br>Key: E2 (early 2 min) L3 (late 3 min)<br>NRT (not realtime)<br><br>';
o = ''; // deferred UI alerts (ongoing (unsched) vs planned)
//alerts array sometimes missing
r = r.alerts || [];
//time sort alerts in the array
r.sort(function(a, b) {
return a.effectiveStartDate < b.effectiveStartDate ? -1 :
a.effectiveStartDate > b.effectiveStartDate ? 1 :
0;
});
for (i=0; i < r.length && i < 10; i++) {
trip = r[i];
if (trip.alertType) { //skip elevators, elevators are missing alertType field
hotkey_timestamp = hotkeys.shift();
route = (hotkey_timestamp === void 0 ? trip.alertType : '<a accesskey='+hotkey_timestamp+' href=#'+hotkey_timestamp+' name='+hotkey_timestamp+'>'+trip.alertType+"</a>")+"<br>" + (trip.humanReadableActivePeriod || 'Ongoing') + "<br>" + trip.alertHeaderText.replace(/\[(\w+)\]/g, mkSubFontTag) + (trip.alertDescriptionText?"<br>"+trip.alertDescriptionText.replace(/\[(\w+)\]/g, mkSubFontTag):'') + "<br><br>";
//delays dont have a time period, put them first in UI
trip.humanReadableActivePeriod ? o += route : h += route;
}
}
h += o;
} else
h = "station not found";
return new Response(h, {
headers: {
'content-type': 'text/html; charset=utf-8',
'cache-control': 'no-cache, no-store'
}
});
} else {
return resp
}
}}
else if (pathname_callback.startsWith('/li/s/')) {
pathname_callback = pathname_callback.substr(('/li/s/'.length), 3);
if (/^\w+$/.test(pathname_callback)) {
var url_headsign = "http://backend-unified.mylirr.org/arrivals/" + pathname_callback;
resp = fetch(url_headsign, lirr_headers);
var h = '<meta content=0 name=mobileoptimized>[1][<a accesskey=1 href=' + pathname_callback + '>Refresh</a>] <a href=' + url_headsign + '>Raw</a><br>'
+ new Date().toLocaleTimeString('en-US', { timeZone: 'America/New_York' })
+" via CFW<br>"
+'CurSta:' + s[pathname_callback] + "<br><a accesskey=2 name=2 href=#2>East</a><br>";
var w = "<a accesskey=3 name=3 href=#3>West</a><br>"; /*w=west*/
resp = await resp;
if (resp.status == 200) {
var r = await resp.json();
var i = 0, t, l, branch; /*t=train, l=lineofhtml, h=html*/
for (curTime = new Date(new Date().toLocaleString()) / 1000; i < r.arrivals.length; i++) {
t = r.arrivals[i];
//note to self, ceil is round up, |0 is round down
//console.log('x'+Math.ceil((t.time - ((new Date().getTime()/1000))) / 60)+' '+(((t.time - ((new Date().getTime()/1000))) / 60)|0));
l = new Date((l = t.time) * 1000).toLocaleTimeString('en-US', { timeZone: 'America/New_York' }).replace(':00 ', ' ') +
'-Min ' + Math.ceil((l-curTime) / 60)
/*
} else if (!_.isUndefined(train.status.otp)) {
const otpMin = Math.trunc(train.status.otp / 60)
const otpMinAbs = Math.abs(otpMin)
otpStr = 'On time'
if (otpMinAbs !== 0) {
const otpClass = otpMin < 0 ? 'late' : 'early'
const otpTerm = otpMinAbs === 1 ? 'minute' : 'minutes'
otpStr = `${otpMinAbs} ${otpTerm} ${otpClass}`
}
}
*/
+ ((l=t.status.otp) && (l=(l/60)|0) ? (l > 0 ? '-E'+l : '-L'+-l):'')
+ '-Tk' + (t.track || '?')
+ "-<font color=" + (
typeof (l = colorRoutesRAIL[branch = t.branch]) === 'string' ? l : (colorRoutesRAIL[branch] = colorStrsRAIL[l|0])
)+ ">" + s[(l=t.stops)[l.length - 1]]
+ "</font>"+(t.peak_code == 'O'?'':'-Pk')+"<br>"; //A or P are peak
t.direction == 'E' ? h += l : w += l;
}
/* add west trains to mega html string and reuse west var */
h += w;
w = '<br>';
for (i in r.banners) {
i = r.banners[i];
//always show banners, they aren't attached to all stations at once
//l = Number(location.hash.slice(1,2));
// if LIRR && is not numeric aka is LIRR sta code then draw, not in MTA UI code
// IDK abbrevation for MNRR in API but other railroad && numeric will draw
//if((i.railroad == 'LIRR') == (l !== +l)) {
w += i.title+'<br>'+i.text+'<br><br>';
//}
}
r = r.alerts;
//time sort alerts in the array
r.sort(function(a, b) {
return a.start_time < b.start_time ? -1 :
a.start_time > b.start_time ? 1 :
0;
});
for (i in r) {
i = r[i];
w += i.status+'<br>'+noPTag(i.header)+'<br>'+(i.human_duration?i.human_duration+'<br>':'')+noPTag(i.text)+'<br><br>';
}
h += w;
return new Response(h, {
headers: {
'content-type': 'text/html; charset=utf-8',
'cache-control': 'no-cache, no-store'
}
});
} else {
return resp
}
}
}
else if (pathname_callback === "/routes.js") {
function lc_rt_arr (arr) {
var i;
for(i in arr) {
if(typeof arr[i][1] === 'string') {
arr[i][1] = arr[i][1].toLowerCase();
}
}
}
function int_rt_arr (arr) {
var i;
for(i in arr) {
if(typeof arr[i][1] === 'string') {
arr[i][1] = parseInt(arr[i][1],16);
}
}
}
var clientEtag = request.headers.get("if-none-match");
if(clientEtag === routesEtag) {
resp = '';
} else {
resp = gRoutes;
//0x2 color tab
if(typeof (str = url.searchParams.get('type')) === 'string') {
var i, n, c, c_o = {}, c_a, a2;
str = str|0;
resp = resp.slice('!function(E){E=this.R,this.R='.length, -(',E&&E()}();'.length));
resp = resp.replace(/,,/g, ',null,');
resp = JSON.parse(resp);
//normalize colors, some subway shuttle busses are missing color fields
for (n=0; n<2; n++) {
a2 = resp[n];
for (i in a2) {
if(typeof a2[i][1] !== 'string'){
//mta.info says unknown subway/regional trains are pure black (all 0s)
//but it also says unknown local/express busses are 0F61A9 (med bright blue)
//for us, for a clear UI, all no-color, any mode, routes should be black
//which is browser default for text anyways
a2[i][1] = "000000";
}
}
}
/*
start b4 opts basic 1767/1772 , 7281
LC at rts, no tab, 1766, 7280
with tab, 1734, 4861
with tab lc tab, 1732, 4861
with tab, exclude single colors 1718, 4819
with tab, lc tab, exclude single colors 1714, 4819
with tab, exclude single colors, LC at RTS 1714, 4819
with tab, lc tab, exclude single colors, LC at RTS 1712, 4819
indv rts int colors, no tab 1752, 6773
with tab, int tab colors (50=x10+x2), 1707, 4816
with tab, int tab colors, int idv rts, no single rt colors in tab (58=0+0x10+0x20+0x2+0x8), 1682, 4774
no tab, raw hex ints everywhere 0x40=64 1763, 6972
with tab, no single RT colors in tab, HEX raw ints everywhere 0+0x40+0x2+0x8=74, 1708, 4799
post " Branch" remove, and missing shuttle bus colors (from MTA routes DB) fix
with tab, int tab colors, int idv rts, no single rt colors in tab (58=0+0x10+0x20+0x2+0x8), 1668, 4702
with tab, no single RT colors in tab, HEX raw ints everywhere 0+0x40+0x2+0x8=74, 1686, 4718
decimal ints win, sometimes 1 extra dec digit, shorter than mandatory "0x" 2 char digits
*/
//0x1 LC colors in tab, 0x2 make tab, 0x4, LC colors at idv rts
//0x8, dont add to tab single use colors
//0x10 int tab, 0x20 int indv rts
//0x40 raw hex JS ints everywhere
if(str & 0x2) {
for (n=0; n<2; n++) {
a2 = resp[n];
for (i in a2) {
c = a2[i][1];
c_o[c] ? c_o[c]++ : c_o[c] = 1;
}
}
//sort highest freq first, so 0 aka empty string, is most common, and single digit idx afterwards
c_a = Object.keys(c_o).sort(function (a, b) {
return c_o[b] - c_o[a];
});
//size experiment, dont idx single use colors
if(str & 0x8)
c_a = c_a.filter(function(e) {return c_o[e] > 1;});
for (n=0; n<2; n++) {
a2 = resp[n];
for (i in a2) {
c = a2[i][1];
//size experiment, dont idx single use colors
if((str & 0x8) && c_o[c] == 1) {
console.log('route: '+(a2[i][3] ? a2[i][3] : a2[i][0])+' has 1 use of its color '+c);
}
else {
a2[i][1] = c_a.indexOf(c);
}
}
}
resp.unshift(c_a);
if(str&0x4) {
lc_rt_arr(resp[1]);
lc_rt_arr(resp[2]);
}
if(str&0x20) {
int_rt_arr(resp[1]);
int_rt_arr(resp[2]);
}
if(str&0x1) {
a2 = resp[0];
for(i in a2) {
a2[i] = a2[i].toLowerCase();
}
}
if(str&0x10) {
a2 = resp[0];
for(i in a2) {
a2[i] = parseInt(a2[i],16);
}
}
} else {
if(str&0x4) {
lc_rt_arr(resp[0]);
lc_rt_arr(resp[1]);
}
if(str&0x20) {
int_rt_arr(resp[0]);
int_rt_arr(resp[1]);
}
}
resp = JSON.stringify(resp);
if(str&0x40) {
//must use cap X, not LC x, zero LC x chars in rts data
resp = resp.replace(/"([0-9A-Fa-f]{6})"/g, function(a,b) {return b.replace(/^0+/,'').length ? "0X"+b.replace(/^0+/,'') : '';});
}
//make JS obj literal notation, not JSON to save bytes, must eval() on client
resp = '!function(E){E=this.R,this.R='+resp.replace(/null/g, '').replace(/,0,/g, ',,').replace(/[,0]+\]/g, ']')+',E&&E()}();';
}
}
ctx.waitUntil(updateRoutes(env, ctx));
return new Response(
resp, {
status: clientEtag === routesEtag ? 304 : 200,
headers: {
'content-type': 'text/javascript',
'etag': routesEtag,
//don't double fetch with preload and fetch()
'cache-control': 'max-age=10, stale-while-revalidate=86400',
}
});
}
else if (pathname_callback === "/wea.js") {
return fetch("https://api.weather.com/v3/wx/forecast/hourly/1day?geocode=40.74,-73.91&format=json&units=e&language=en-us&apiKey=8de2d8b3a93542c9a2d8b3a935a2c909");
}
//old smart/flip phone browser debug tool
else if (
(pathname_callback === '/t' && (url.pathname = '/touch'))
|| pathname_callback.startsWith('/touch')
) {
//need to save THIS domain/prot in var url for later
pathname_callback = new URL(url);
pathname_callback.protocol = "https:";
pathname_callback.hostname = "patrickhlauke.github.io";
resp = await fetch(pathname_callback,request);
//3rd party GH Pages redirects if any, must be to THIS
//maybe http: cleartext, domain
if(pathname_callback = resp.headers.get('location')) {
pathname_callback = new URL(pathname_callback);
pathname_callback.protocol = url.protocol;
pathname_callback.hostname = url.hostname;
resp = new Response(resp.body, resp);
resp.headers.set('location', pathname_callback.href);
}
return resp;
}
/* Workers Preview has undef cf obj and cf prop is tested R/O
United Nations (AS676) is a very unique looking ISP */
var cf = request?.cf || {
asn: 676
};
var ip = request?.headers?.get('cf-connecting-ip') || '0.0.0.0';
var etag = 'W/"G'+ip+'.'+cf.asn+'"';
if(request?.headers?.get('if-none-match') == etag){
return new Response(null, {status: 304});
}
var asnqstr = "AS" + cf.asn;
//todo check len for 255 overflow
asnqstr = String.fromCharCode(asnqstr.length) + asnqstr +
"\x03\x61\x73\x6e\x05\x63\x79\x6d\x72\x75\x03\x63\x6f\x6d\x00\x00\x10\x00\x01";
/* Workers Preview bug doesn't allow IP addr hosts */
console.log("a",performance.now());
resp = fetch("https://" + (request?.cf ? "1.1.1.1" :
"cloudflare-dns.com") + "/dns-query", {
method: 'post',
body: "\x00\x02\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00" + asnqstr,
headers: {
"content-type": 'application/dns-message'
}
});
/* fit some CPU tast during I/O block */
asnqstr = new TextEncoder().encode(asnqstr);
/* Chop QTYPE 16b and QCLASS 16b off end, to set up for a
future memcmp range leaving only QNAME (host name) as the field to match*/
var endptr = asnqstr.byteLength - 4;
resp = await resp;
console.log("b",performance.now());
/* don't error check the 1.1.1.1 HTTP server, unimaginable it goes down */
var bufmetaobj = await resp.arrayBuffer();
console.log("c",performance.now());
var bufdv = new DataView(bufmetaobj);
/*QR bit 0x8000, Recur desire 0x100
(0x200 is truncate, error if on, check is free CPU wise),
recur available 0x80, start at offset 2, skipping 16b ID */
if ((bufdv.getUint16(2) & 0x8380) == 0x8180
/* questions count and answer count */
&&
bufdv.getUint32(4) == 0x10001
/* NS count and additional record count , 2 16b zeros*/
&&
bufdv.getUint32(8) == 0) {
let i, equal_flag, i_ptr;
/* https://code.woboq.org/userspace/glibc/resolv/res_send.c.html#266
glibc res_nameinquery() checks the question section in the response
against what it sent out on the wire to make sure its identical
do that here through a memcmp()*/
equal_flag = 1;
for (i = 0; i < asnqstr.byteLength; i++) {
if (asnqstr[i] !== bufdv.getUint8(i + 12)) {
equal_flag = 0;
break;
}
}
if (equal_flag) {
//pointer is on 1st byte after question section now
i += 12;
let ansdomainlabelptr;
if ((bufdv.getUint8(i) & 0xC0) == 0xC0) {
/* LABEL_POINTER aka Message compression */
/* https://github.com/tjfontaine/native-dns-packet/blob/master/packet.js#L75 */
ansdomainlabelptr = bufdv.getUint16(i) & ~0xC000;
i_ptr = i + 2;
} else {
ansdomainlabelptr = i;
i_ptr = i + endptr;
}
equal_flag = 1;
for (i = 0; i < endptr; i++) {
if (asnqstr[i] !== bufdv.getUint8(i + ansdomainlabelptr)) {
equal_flag = 0;
break;
}
}
if (equal_flag) {
/* 0x10 TXT record, 0x01 class internet */
if (bufdv.getUint32(i_ptr) == 0x00100001) {
/*skip 16b QTYPE, 16b QCLASS, and 32b TTL */
i_ptr += 8;
/* check 16b RDLENGTH for sanity*/
if (bufdv.getUint16(i_ptr) + (i_ptr += 2) == bufdv.byteLength) {
/* check 8b <character-string> node for sanity*/
if (bufdv.getUint8(i_ptr) + (i_ptr += 1) == bufdv.byteLength) {
return mkJSResp("Your ISP: "+ip+" | AS"+new TextDecoder().decode(new Uint8Array(bufdv
.buffer, i_ptr)),{etag: etag});
}
}
}
}
}
}
return mkJSResp("ERROR: raw data: "+new TextDecoder().decode(new Uint8Array(bufmetaobj)),{});
}
/* throws in CF, prints JS in browser dev console */
//try{handleRequest().then(function(r){r.text().then(function(s){console.log(s)})})}
//catch(e){}
async function updateRoutes (env, ctx) {
var i = 0,
ghkey,
e, /* entry */
etag,
resp,
resp_min,
new_resp_min,
routes_escaped,
new_resp
resp = fetch('http://otp-mta-prod.camsys-apps.com/otp/routers/default/index/routes?apikey=Z276E3rCeTzOQEoBPPN4JCEc6GfvdnYE');
resp = await resp;
if (resp.status === 200) {
resp = resp.json();
resp = await resp;
//MTA origin randomly includes these null fields, must be different
//version load balancer serializers, normalize the data so etags
//stay the same
for (; i < resp.length; i++) {
e = resp[i];
if (e.longName === null) {
delete e.longName;
}
if (e.shortName === null) {
delete e.shortName;
}
if (e.color === null) {
delete e.color;
}
}
//resp.unshift({"id":"TINYMTA:" + (new Date()).toString()});
resp = mapper.buildServiceRoutes(resp);
/*
drawhtml routes DB mandatory fields
agency (needed for drawhtml, unlikely it can be removed)
inService DONE (complicated if needed, hardwired-on in MTA UI in generating Routes DB, not a backend MTA JSON field, overridden by RT alert summary text to "No Scheduled Service" for belmont line, only bus & rail has it on MTA UI API, not sub, sub MTA UI already doesnt have the field, probably could be removed b/c alerts service delivers the flag (status "no scheduled") indirectly)
April 2023, Belmont Branch was removed as a route by MTA, probably after Elmont-UBS station opened
so no more permanent Mercury alert saying "No Scheduled Service" for belmont line, so just remove
.inService totally
isExpressBus (remove it, unused in UI) DONE
routeId (id is correct, unk purpose) DONE
route (same as id) DONE
id (neeeded for drawhtml maybe can be removed, investigate more) CANT REMOVE, its internal route ID for mercury/LMM alerts
shortName (removed, name and shortName identical) DONE
longName (remove it, unused in UI, only used in building routes, maybe one day re-add it if bus routes UI needs full name) DONE
agencyName (remove it, unused in UI) DONE
paramId (remove it, unused in UI) DONE
sortOrder (remove for bus & rail, always 0, not used in UI, only used by subway) DONE
routeType (remove it, unused in UI, or replace mode (Bus/rail/sub) with integer routeType? routeType for bus separates local vs express vs subway shuttle, already missing for subway) DONE
regionalFareCardAccepted (remove it, unused in UI) DONE
agencyId (remove it, unused in UI) DONE
containsExpress (remove it, unused in UI) DONE
agency (can't be removed b/c RAIL and BUS, don't bother adding/splitting it from ID at UI runtime)
-original 2270 bytes gz, all gz sizes
-Bx->BX, and display name dupe drop to 1662 bytes
-drop 5 slice subway to 3 slice (rmv ,s) drop to 1657 bytes
-non-false for rail+bus, agency 99, display names 43
-agency vs display name flip for bus and rail drop to 1652 bytes (rmv ,s)
-subway sort order before color, drop color if null, 1652->1646
-H, FS, SI are missing colors in MTA routes DB
-rmv subway colors from routes DB, b/c unused & need agency in same slot
-we inc our own color DB anyways in HTML 1646->1600
*/
resp = JSON.stringify(resp);
//make JS obj literal notation, not JSON to save bytes, must eval() on client
resp = 'var R;!function(E,B){for(E=R,R='+resp.replace(/null/g, '').replace(/,?\]/g,']')+',E&&E(),E=document.documentElement.firstChild.lastChild;E;E=E.previousSibling)if((B=E.src)&&B.lastIndexOf("routes.js")===B.length-9){E.parentNode.removeChild(E);break}}();';
//resp = resp.replace(/\[/, '[{"id":"TINYMTA:' + (new Date()).toString() + '","longName":"","mode":"BUS","color":"CAE4F1","agencyName":"","paramId":"AMK__42920","sortOrder":0,"routeType":3,"regionalFareCardAccepted":false},');
etag = await crypto.subtle.digest('MD5', textEnc.encode(resp));
//lock-hazard, update globals no promises
etag = 'W/"' + btoa(String.fromCharCode.apply(null, new Uint8Array(etag))) + '"';
//console.log('at etag upd comp');
if (routesEtag !== etag) {
//console.log('etag mismatch');
try {
ghkey = env.GHAPISECRET
} catch (e) {
if(!(ghkey = url.searchParams.get('key'))) {
console.log("GHAPI key is invalid="+ghkey)
}
ghkey = 'Basic '+ghkey;
}
//ghkey = '';
//atomic hazard
routesEtag = etag;
gRoutes = resp;
//patch ourself
//TODO also patch .min
resp = fetch("https://raw.githubusercontent.com/bulk88/tinymta/master/cloudflare_as_name.js", {cf: {cacheTtlByStatus: -1}});
resp_min = fetch("https://raw.githubusercontent.com/bulk88/tinymta/master/cloudflare_as_name.min.js", {cf: {cacheTtlByStatus: -1}});
resp = await resp;
resp_min = await resp_min;
console.log('got old gh script');
if (resp.status == 200 && resp_min.status == 200) {
resp = await resp.text();
resp_min = await resp_min.text();
//not injection safe, not binary or \n safe
//https://github.com/terser/terser/blob/master/lib/output.js#L319
//x27 == '
routes_escaped = gRoutes.replace(/\x27/g, "\\'");
//update to new RESP
new_resp = resp.replace(/let (\w+)='[^']*',(\w+)='[^']*';$/, "let $1='"+etag+"',$2='"+routes_escaped+"';");
if(new_resp == resp) {
console.log('failed to patch full size cfw src');
}
//minify prefers double quotes, always reset to single to minimize chars
new_resp_min = resp_min.replace(/let (\w+)=(?:'[^']*'|"[^"]*"),(\w+)=(?:'[^']*'|"[^"]*");$/, "let $1='"+etag+"',$2='"+routes_escaped+"';");
if(new_resp_min == resp_min) {
console.log('failed to patch mini cfw src');
}
//\x20 is space
//resp = resp.replace(/let\x20routesEtag='[^']?'/, "let routes"+"Etag='"+etag+"'")
//resp = resp.replace(/,gRoutes='[^']?';/, ",gRou"+"tes='"+resp+"';")
/* git auth token extracted like this from windows box
sh-4.4$ GIT_TRACE=1 GIT_TRACE_PACK_ACCESS=1 GIT_TRACE_PACKET=1 GIT_TRACE_PERFORMANCE=1 GIT_TRACE_SETUP=1 GIT_MERGE_VERBOSITY=1 GIT_CURL_VERBOSE=1 GIT_TRACE_SHALLOW=1 GCM_TRACE=1 GIT_TRACE_REDACT=0 git push
code taken from
https://github.com/renovatebot/renovate/blob/5f213255d088054500cdd980b62092f4d22f5f4c/lib/platform/github/storage.js
*/
var get = {};
async function got(url, options) {
return ajaxRun("GET", url, options)
}
async function post(url, options) {
return ajaxRun("POST", url, options)
}
async function patch(url, options) {
return ajaxRun("PATCH", url, options)
}
async function ajaxRun(method, url, options) {
var resp = await fetch('https://api.github.com/' + url, {
method: method,
headers: {
authorization: ghkey,
'user-agent': 'tinymta_cfw'
},
...(options && {
body: JSON.stringify(options)
})
});
if(resp.status >= 300) {
console.log('failed status='+resp.status+' ct='+resp.headers.get('content-type')+' url='+url);
resp = await resp.text();
console.log(resp);
return resp;
} else {
return await resp.json();
}
};
var config = {
repository: 'bulk88/tinymta',
};
let branchFiles = {};
var global = {
gitAuthor: {
name: "RoutesBot",
email: "[email protected]",
}
};
//need time zone like moment.js does
function toIsoString(date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function (num) {
return (num < 10 ? '0' : '') + num;
};
return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
dif + pad(Math.floor(Math.abs(tzo) / 60)) +
':' + pad(Math.abs(tzo) % 60);
}
// Create a commit and return commit SHA
async function createCommit(parent, tree, message) {
/* unused
const {
gitPrivateKey
} = config;
*/
/* const now = moment(); */
let author;
if (global.gitAuthor) {
author = {
name: global.gitAuthor.name,
email: global.gitAuthor.email,
date: toIsoString(new Date()) /* now.format() */,
};
}
const body = {
message,
parents: [parent],
tree,
};
if (author) {
body.author = author;
/* unused
if (gitPrivateKey) {
const privKeyObj = openpgp.key.readArmored(gitPrivateKey).keys[0];
const commit = `tree ${tree}\nparent ${parent}\nauthor ${
author.name
} <${author.email}> ${now.format('X ZZ')}\ncommitter ${
author.name
} <${author.email}> ${now.format('X ZZ')}\n\n${message}`;
const {
signature
} = await openpgp.sign({
data: openpgp.util.str2Uint8Array(commit),
privateKeys: privKeyObj,
detached: true,
armor: true,
});
body.signature = signature;
}
*/
}
return (await post(`repos/${config.repository}/git/commits`, body))
.sha;
}
// Internal: Updates an existing branch to new commit sha
async function updateBranch(branchName, commit) {
const options = {
sha: commit,
force: true,
};
try {
await patch(
`repos/${config.repository}/git/refs/heads/${branchName}`,
options);
} catch (err) {
if (err.statusCode === 422) {
console.log(err + ' Branch no longer exists - exiting');
throw new Error('repository-changed');
}
throw err;
}
}
// Low-level commit operations
// Return the commit SHA for a branch
async function getBranchCommit(branchName) {
try {
const res = await got(
`repos/${config.repository}/git/refs/heads/${branchName}`);
return res.object.sha;
} catch (err) {
if (err.statusCode === 404) {
throw new Error('repository-changed');
}
if (err.statusCode === 409) {
throw new Error('empty');
}
throw err;
}
}
// Return the tree SHA for a commit
async function getCommitTree(commit) {
return (await got(`repos/${config.repository}/git/commits/${commit}`))
.tree.sha;
}
async function createBlob(fileContents) {
const options = {
encoding: 'base64',
content: btoa(fileContents)
};
return (await post(`repos/${config.repository}/git/blobs`, options))