This repository has been archived by the owner on May 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
ampbench_lib.js
2064 lines (1833 loc) · 83.9 KB
/
ampbench_lib.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
// Copyright 2015-2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
// @ts-check
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// imports
//
const os = require('os');
// const http = require('http');
// const https = require('https');
const crypto = require('crypto');
const fs = require('fs');
const http = require('follow-redirects').http;
const https = require('follow-redirects').https;
require('follow-redirects').maxRedirects = 15; // 3X the default!!! we want to know when there *really* is many
const url = require('url');
const request = require('request');
const fetch = require('node-fetch');
// https://github.com/wdavidw/node-http-status/blob/master/lib/index.js
const http_status = require('http-status');
const valid_url = require('valid-url');
// https://www.npmjs.com/package/wget-improved
const wget = require('wget-improved');
const robots_parser = require('robots-parser');
const util = require('util');
const inspect_obj = (obj) => {return util.inspect(obj, { showHidden: true, depth: null });};
const cheerio = require('cheerio');
const S = require('string');
const hasBom = require('has-bom');
// const {URL} = require('url');
const URL = require('url-parse');
const mime = require('mime-types');
const punycode = require('punycode');
const createCacheUrl = require('amp-toolbox-cache-url');
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// convenient aliases
//
const puts = console.log;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// HTTP response class
//
class HttpResponse {
constructor(url) {
this._url = null;
this._url_error = '';
this._is_https = null;
this._http_client = null;
this._stamp_on_begin = 0;
this._stamp_on_end = 0;
this._response = null;
this._http_response_code = 0;
this._http_response_text = '';
this._http_response_body = '';
this._redirects_count = 0;
this._redirects_urls = [];
this.is_https_cert_authorized = null;
this.is_https_cert_certificate = null;
this._is_https_cert_ssl_error = '';
/** @type {CheerioStatic} */
this._$ = null;
if (url) {
this._url = url;
if (check_url_is_valid(this._url)) {
this._url_error = ''; // url seems ok
} else {
this._url_error =
'URL Error: URL string appears invalid or malformed';
}
if (this._url.indexOf('http://') === 0 ||
this._url.indexOf('https://') === 0) {
// protocol seems OK
// this._url = str_rtrim_char(this._url, '/'); // ignore trailing slashes //TODO: PROBLEMATIC
} else {
this._url_error =
'URL Error: no valid transport protocol was found in the URL string';
}
this._is_https = (url.indexOf('https://') === 0);
this._http_client = (this._is_https) ? https : http;
} else {
this._url_error =
'URL Error: URL string appears blank, invalid or malformed';
}
}
setResponse(res) {
if (res) {
this._stamp_on_begin = new Date(); // set beginning timestamp
this._response = res;
this._http_response_code = res.statusCode;
this._http_response_text = 'HTTP Status: ' + res.statusCode + ' - ' + http_status[res.statusCode];
try { // best attempt at getting SSL cert info
this._redirects_count = res.fetchedUrls.length;
this._redirects_urls = res.fetchedUrls;
} catch (err) { /* pass: as a rule we want to avoid breaking */ }
if (this.statusIsOK()) {
if (this.is_https) {
try { // best attempt at getting SSL cert info - as a rule we want to avoid breaking
this.is_https_cert_authorized = res.socket.authorized;
this.is_https_cert_certificate = res.socket.getPeerCertificate();
} catch (err) { /* pass: as a rule we want to avoid breaking */ }
}
}
} else {
this._url_error =
'Response Error: HttpResponse setResponse(res) requires a valid HTTP Response parameter: this was not supplied or is invalid';
}
}
setResponseEnded() { // tel us when the response ended delivering content
this._stamp_on_end = new Date(); // set ending timestamp
}
get duration_in_milliseconds() {
return this._stamp_on_end - this._stamp_on_begin;
}
get response() {
return this._response;
}
get url() { // read-only - can only be set during instantiation!
return this._url;
}
get url_error() { // read-only - can only be set during instantiation!
return this._url_error;
}
get is_https() { // read-only!
return this._is_https;
}
get http_client() { // read-only - set during instantiation!
return this._http_client;
}
get http_response_code() {
return this._http_response_code;
}
get http_response_text() { // read-only - set in http_response_code()!
return this._http_response_text;
}
get http_response_body() {
return this._http_response_body;
}
get $() {
if (!this._$) {
if (this.http_response_body) {
this._$ = cheerio.load(this.http_response_body);
} else {
this._$ = cheerio.load('');
}
}
return this._$;
}
set http_response_body(body) {
if (body) {
this._http_response_body = body;
}
}
get redirects_count() { // read-only!
return this._redirects_count;
}
get redirects_urls() { // read-only!
return this._redirects_urls;
}
get is_https_cert_ssl_error() {
return this._is_https_cert_ssl_error;
}
set is_https_cert_ssl_error(err) {
if (err) {
if ('DEPTH_ZERO_SELF_SIGNED_CERT' === err.code) {
// "[Error: self signed certificate[DEPTH_ZERO_SELF_SIGNED_CERT]]"
// We probably want to know this, so maybe do *not* set the following?
// .. process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
this.is_https_cert_authorized = false;
// Force a 403: https://en.wikipedia.org/wiki/HTTP_403 ???
// this._http_response_code = 403;
this._http_response_text = 'Server SSL Certificate rejected';
}
this._is_https_cert_ssl_error = err.toString() + '[' + err.code + ']';
this._http_response_text += '[' + this._is_https_cert_ssl_error + ']';
}
}
urlIsOK() {
return ('' === this.url_error);
}
urlIsGoogleAmpFeed() {
return (-1 < this.url.indexOf('googleusercontent.com/amphtml'));
}
statusIsOK() {
return (200 == this.http_response_code);
}
bodyIsNotEmpty() {
return ('' !== this.http_response_body.trim());
}
wasRedirected() {
return (1 < this.redirects_count);
}
print() {
puts('=> url : ' + this.url);
puts('=> url_error : ' + this.url_error);
puts('=> is_https : ' + this.is_https);
puts('=> http_response_code : ' + this.http_response_code);
puts('=> http_response_text : ' + this.http_response_text);
puts('=> duration_in_milliseconds : ' + this.duration_in_milliseconds);
puts('=> wasRedirected : ' + this.wasRedirected());
puts('=> redirects_count : ' + this.redirects_count);
puts('=> redirects_urls :\n' + this.redirects_urls.join('\n'));
// puts('=> redirects_urls (inspect) : ' + util.inspect(this.redirects_urls));
puts('=> is_https_cert_authorized : ' + this.is_https_cert_authorized);
puts('=> is_https_cert_ssl_error : ' + this.is_https_cert_ssl_error);
}
printWithBody() {
this.print();
puts('=> http_response_body :\n' + this.http_response_body);
}
printWithCert() {
this.print();
puts('=> is_https_cert_certificate:\n' + util.inspect(this.is_https_cert_certificate));
}
printWithResponse() {
this.print();
puts('=> response:\n' + util.inspect(this._response));
}
printInspect() {
puts('=> HttpResponse:\n' + util.inspect(this));
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// app validation check status constants
//
const
CHECK_FAIL = 'FAIL',
CHECK_PASS = 'PASS',
CHECK_INFO = 'INFO',
CHECK_WARN = 'WARNING',
CHECK_NONE = 'UNKNOWN';
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// HTTP User Agent constants
// https://support.google.com/webmasters/answer/1061943?hl=en
// https://developer.chrome.com/multidevice/user-agent
// https://webmasters.googleblog.com/2016/03/updating-smartphone-user-agent-of.html
// https://deviceatlas.com/blog/list-of-user-agent-strings
// https://deviceatlas.com/blog/list-of-web-crawlers-user-agents
//
// desktop + server-side CURL
const UA_CURL = 'curl/7.43.0'; //!!! we use this User-Agent for non-crawler Googlebots
// mobile
const UA_MOBILE_ANDROID_CHROME_52 =
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2725.0 Mobile Safari/537.36';
const UA_MOBILE_IPHONE_CHROME_52 =
'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/52.0.2725.0 Mobile/13B143 Safari/601.1.46';
const UA_MOBILE_IPHONE_SAFARI =
'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B137 Safari/601.1';
// googlebot search crawlers
const UA_GOOGLEBOT =
'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
const UA_GOOGLEBOT_SMARTPHONE =
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
// user agent currently in use - - - - - - - - - - - - - - - - - - - - - - - - -
var UA_AMPBENCH = UA_MOBILE_ANDROID_CHROME_52;
var UA_AMPBENCH_NAME = 'UA_MOBILE_ANDROID_CHROME_52';
function set_global_user_agent(user_agent) {
UA_AMPBENCH = user_agent;
}
function get_global_user_agent() {
return UA_AMPBENCH;
}
function set_global_user_agent_name(user_agent_name) {
UA_AMPBENCH_NAME = user_agent_name;
}
function get_global_user_agent_name() {
return UA_AMPBENCH_NAME;
}
// const UA_AMPBENCH = UA_CURL;
// const UA_AMPBENCH_NAME = 'UA_CURL';
// const UA_AMPBENCH = UA_GOOGLEBOT_SMARTPHONE;
// const UA_AMPBENCH_NAME = 'UA_GOOGLEBOT_SMARTPHONE';
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// HTTP response content inspector
//
class HttpBodySniffer {
constructor(url, body) {
// print_dashes(60);
// console.log('=> HttpBodySniffer:constructor: ');
// console.log('=> -- url : ' + url);
// console.log('=> -- body: [' + body.substr(0,50) + '...]');
this.isValidForUse = false; // is the sniffer in a usable state - NOT in the case of bad HTTP responses!
if (!url || !body || '' === url || '' === body) {
this.isValidForUse = false; // is the sniffer in a usable state - NOT in the case of bad HTTP responses!
} else {
this.isValidForUse = true;
this._url = url;
this._body = body;
this._amphtml_rel_index = this._body.indexOf('rel="amphtml"');
this._canonical_rel_index = this._body.indexOf('rel="canonical"');
this._contains = {
amphtml_signature:
S(this._body).contains('<html ⚡') || S(this._body).contains(' ⚡>') ||
S(this._body).contains('<html amp') || S(this._body).contains('<html AMP') ||
S(this._body).contains(' amp>') || S(this._body).contains(' AMP>') ||
S(this._body).contains(' amp=') || S(this._body).contains(' AMP='),
amphtml_link:
S(this._body).contains('link rel="amphtml"'),
amphtml_link2:
S(this._body).contains(' rel="amphtml" href='),
amphtml_link3:
S(this._body).contains(' rel="amphtml"'),
canonical_link:
S(this._body).contains('link rel="canonical"'),
canonical_link2:
S(this._body).contains(' rel="canonical"'),
canonical_link3:
S(this._body).contains(' rel="canonical" href='),
amphtml_runtime:
S(this._body).contains('src="https://cdn.ampproject.org/v0.js"')
};
this._amphtml_href = this._contains.amphtml_link
? S(this._body).between('link rel="amphtml" href=', '>').s
: '';
this._amphtml_href2 = this._contains.amphtml_link2
? S(this._body).between(' rel="amphtml" href=', '>').s
: '';
this._amphtml_href3 = this._contains.amphtml_link3
? S(this._body).between(' href=', ' rel="amphtml"').s
: '';
this._canonical_href = this._contains.canonical_link
? S(this._body).between('link rel="canonical" href=', '>').s
: '';
this._canonical_href2 = this._contains.canonical_link2
? S(this._body).between(' rel="canonical" href=', '>').s
: '';
this._canonical_href3 = this._contains.canonical_link3
? S(this._body).between(' href=', ' rel="canonical"').s
: '';
this._json_ld_script_raw = this.bodyContains('type="application/ld+json"')
? S(this._body).between('type="application/ld+json">', '</script>').s
: '';
this._json_ld_script = S(this._json_ld_script_raw).strip(' ', os.EOL);
this._contains_sd = {
// AMP_SD_TYPES = ['Article', 'NewsArticle', 'BlogPosting', 'VideoObject'],
// - - look for json-ld: https://developers.google.com/schemas/formats/json-ld - -
json_ld: '' !== this._json_ld_script,
json_ld_schema_org:
this.bodyContains('"@context"') && (
this.bodyContains('"http://schema.org/"') ||
this.bodyContains('"https://schema.org/"') ),
jsonld_type: {
Article:
this.bodyContains('"@type":"Article"') ||
this.jsonldScriptContains('"@type":"Article"'),
NewsArticle:
this.bodyContains('"@type":"NewsArticle"') ||
this.jsonldScriptContains('"@type":"NewsArticle"'),
BlogPosting:
this.bodyContains('"@type":"BlogPosting"') ||
this.jsonldScriptContains('"@type":"BlogPosting"'),
WebPage:
this.bodyContains('"@type":"WebPage"') ||
this.jsonldScriptContains('"@type":"WebPage"'),
Organization:
this.bodyContains('"@type":"Organization"') ||
this.jsonldScriptContains('"@type":"Organization"'),
ImageObject:
this.bodyContains('"@type":"ImageObject"') ||
this.jsonldScriptContains('"@type":"ImageObject"'),
VideoObject:
this.bodyContains('"@type":"VideoObject"') ||
this.jsonldScriptContains('"@type":"VideoObject"')
},
// - - look for microdata: https://developers.google.com/schemas/formats/microdata - -
microdata: S(this._body).contains(' itemprop='),
microdata_schema_org:
this.bodyContains('itemtype="http://schema.org') ||
this.bodyContains('itemtype="https://schema.org'),
microdata_type: {
Article:
this.bodyContains('itemtype="http://schema.org/Article"') ||
this.bodyContains('itemtype="https://schema.org/Article"'),
NewsArticle:
this.bodyContains('itemtype="http://schema.org/NewsArticle"') ||
this.bodyContains('itemtype="https://schema.org/NewsArticle"'),
BlogPosting:
this.bodyContains('itemtype="http://schema.org/BlogPosting"') ||
this.bodyContains('itemtype="https://schema.org/BlogPosting"'),
WebPage:
this.bodyContains('itemtype="http://schema.org/WebPage"') ||
this.bodyContains('itemtype="https://schema.org/WebPage"'),
Organization:
this.bodyContains('itemtype="http://schema.org/Organization"') ||
this.bodyContains('itemtype="https://schema.org/Organization"'),
ImageObject:
this.bodyContains('itemtype="http://schema.org/ImageObject"') ||
this.bodyContains('itemtype="https://schema.org/ImageObject"'),
VideoObject:
this.bodyContains('itemtype="http://schema.org/VideoObject"') ||
this.bodyContains('itemtype="https://schema.org/VideoObject"')
}
};
this._jsonld_type_is_amp_news_carousel_main =
this._contains_sd.jsonld_type.Article ||
this._contains_sd.jsonld_type.NewsArticle ||
this._contains_sd.jsonld_type.BlogPosting ||
this._contains_sd.jsonld_type.VideoObject;
this._jsonld_type_is_amp_news_carousel_support =
this._contains_sd.jsonld_type.WebPage ||
this._contains_sd.jsonld_type.Organization ||
this._contains_sd.jsonld_type.ImageObject;
this._jsonld_type_is_amp_news_carousel =
this._jsonld_type_is_amp_news_carousel_main &&
this._jsonld_type_is_amp_news_carousel_support;
this._microdata_type_is_amp_news_carousel_main =
this._contains_sd.microdata_type.Article ||
this._contains_sd.microdata_type.NewsArticle ||
this._contains_sd.microdata_type.BlogPosting ||
this._contains_sd.microdata_type.VideoObject;
this._microdata_type_is_amp_news_carousel_support =
this._contains_sd.microdata_type.WebPage ||
this._contains_sd.microdata_type.Organization ||
this._contains_sd.microdata_type.ImageObject;
this._microdata_type_is_amp_news_carousel =
this._microdata_type_is_amp_news_carousel_main &&
this._microdata_type_is_amp_news_carousel_support;
this._sd_type_is_amp_news_carousel_main =
this._jsonld_type_is_amp_news_carousel_main ||
this._microdata_type_is_amp_news_carousel_main;
this._sd_type_is_amp_news_carousel_support =
this._jsonld_type_is_amp_news_carousel_support ||
this._microdata_type_is_amp_news_carousel_support;
this._sd_type_is_amp_news_carousel_main_without_support =
this._sd_type_is_amp_news_carousel_main &&
!this._sd_type_is_amp_news_carousel_support;
this._sd_type_is_amp_news_carousel_support_without_main =
!this._sd_type_is_amp_news_carousel_main &&
this._sd_type_is_amp_news_carousel_support;
this._sd_type_is_amp_news_carousel =
this._jsonld_type_is_amp_news_carousel ||
this._microdata_type_is_amp_news_carousel;
this._sd_amp_types_found_string = ''
+ ( this._contains_sd.jsonld_type.Article
? ' Article (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.Article
? ' Article (Microdata)' : '' )
+ ( this._contains_sd.jsonld_type.NewsArticle
? ' NewsArticle (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.NewsArticle
? ' NewsArticle (Microdata)' : '' )
+ ( this._contains_sd.jsonld_type.BlogPosting
? ' BlogPosting (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.BlogPosting
? ' BlogPosting (Microdata)' : '' )
+ ( this._contains_sd.jsonld_type.WebPage
? ' WebPage (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.WebPage
? ' WebPage (Microdata)' : '' )
+ ( this._contains_sd.jsonld_type.Organization
? ' Organization (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.Organization
? ' Organization (Microdata)' : '' )
+ ( this._contains_sd.jsonld_type.ImageObject
? ' ImageObject (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.ImageObject
? ' ImageObject (Microdata)' : '' )
+ ( this._contains_sd.jsonld_type.VideoObject
? ' VideoObject (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.VideoObject
? ' VideoObject (Microdata)' : '' );
this._sd_amp_carousel_types_found_string = ''
+ ( this._contains_sd.jsonld_type.Article
? ' Article (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.Article
? ' Article (Microdata)' : '' )
+ ( this._contains_sd.jsonld_type.NewsArticle
? ' NewsArticle (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.NewsArticle
? ' NewsArticle (Microdata)' : '' )
+ ( this._contains_sd.jsonld_type.BlogPosting
? ' BlogPosting (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.BlogPosting
? ' BlogPosting (Microdata)' : '' )
+ ( this._contains_sd.jsonld_type.VideoObject
? ' VideoObject (JSON-LD)' : '' )
+ ( this._contains_sd.microdata_type.VideoObject
? ' VideoObject (Microdata)' : '' );
this._contains_byte_order_mark = hasBom(this._body);
}
}
get url() { // read-only - can only be set during instantiation!
if (this.isValidForUse) {
return this._url;
} else {
return '';
}
}
get body() { // read-only - can only be set during instantiation!
if (this.isValidForUse) {
return this._body;
} else {
return '';
}
}
get amphtmlRelIndex() {
if (this.isValidForUse) {
return this._amphtml_rel_index;
} else {
return -1;
}
}
get amphtmlRel() {
if (this.isValidForUse && 0 < this.amphtmlRelIndex) {
return this._body.substr(this.amphtmlRelIndex - 150, 300);
} else {
return '';
}
}
get canonicalRelIndex() {
if (this.isValidForUse) {
return this._canonical_rel_index;
} else {
return -1;
}
}
get canonicalRel() {
if (this.isValidForUse && 0 < this.canonicalRelIndex) {
return this._body.substr(this.canonicalRelIndex - 150, 300);
} else {
return '';
}
}
bodyContains(text) {
if (this.isValidForUse) {
return S(this._body).contains(text);
} else {
return false;
}
}
jsonldScriptContains(text) {
if (this.isValidForUse && '' !== this._json_ld_script) {
return S(this._json_ld_script).contains(text);
} else {
return false;
}
}
get contains() { // has child fields so throw error if not valid
if (this.isValidForUse) {
return this._contains;
} else {
throw 'ERROR: HttpBodySniffer is not valid for use'; // eslint-disable-line no-throw-literal
}
}
get containsAmpHtmlSignature() {
if (this.isValidForUse) {
return this._contains.amphtml_signature;
} else {
return false;
}
}
get containsAmpHtmlLink() {
if (this.isValidForUse) {
return this._contains.amphtml_link || this._contains.amphtml_link2 || this._contains.amphtml_link3;
} else {
return false;
}
}
get containsCanonicalLink() {
// console.log('=> canonicalLink:_contains.canonical_link : ' + this._contains.canonical_link);
// console.log('=> canonicalLink:_contains.canonical_link2: ' + this._contains.canonical_link2);
// console.log('=> canonicalLink:_contains.canonical_link3: ' + this._contains.canonical_link3);
if (this.isValidForUse) {
return this._contains.canonical_link || this._contains.canonical_link2 || this._contains.canonical_link3;
} else {
return false;
}
}
get amphtmlLink() {
console.log('=> amphtmlLink:_amphtml_href : ' + this._amphtml_href.substr(0,256).trim());
console.log('=> amphtmlLink:_amphtml_href2: ' + this._amphtml_href2.substr(0,256).trim());
console.log('=> amphtmlLink:_amphtml_href3: ' + this._amphtml_href3.substr(0,256).trim());
if (this.isValidForUse) {
if (this._contains.amphtml_link3) {
return this._amphtml_href3.substr(0, 256).trim();
} else if (this._contains.amphtml_link2) {
return this._amphtml_href2.substr(0, 256).trim();
} else if (this._contains.amphtml_link) {
return this._amphtml_href.substr(0, 256).trim();
} else {return '';}
}
return '';
}
get canonicalLink() {
// console.log('=> canonicalLink:_canonical_href : ' + this._canonical_href.substr(0,256).trim());
// console.log('=> canonicalLink:_canonical_href2: ' + this._canonical_href2.substr(0,256).trim());
// console.log('=> canonicalLink:_canonical_href3: ' + this._canonical_href3.substr(0,256).trim());
if (this.isValidForUse) {
if (this._contains.canonical_link3) {
return this._canonical_href3.substr(0, 256).trim();
} else if (this._contains.canonical_link2) {
return this._canonical_href2.substr(0, 256).trim();
} else if (this._contains.canonical_link) {
return this._canonical_href.substr(0, 256).trim();
} else {return '';}
}
return '';
}
get containsJsonLd() {
return this.isValidForUse ?
this._contains_sd.json_ld_schema_org || this._contains_sd.json_ld :
false;
}
get jsonLdTypeIsAmp() {
return this.isValidForUse ?
this._jsonld_type_is_amp_news_carousel :
false;
}
get jsonLdTypeIsAmpCarousel() {
return this.isValidForUse ?
this._jsonld_type_is_amp_news_carousel_main :
false;
}
get containsMicroData() {
return this.isValidForUse ?
this._contains_sd.microdata_schema_org || this._contains_sd.microdata :
false;
}
get microdataTypeIsAmp() {
return this.isValidForUse ?
this._microdata_type_is_amp_news_carousel :
false;
}
get microdataTypeIsAmpCarousel() {
return this.isValidForUse ?
this._microdata_type_is_amp_news_carousel_main :
false;
}
get containsMixedStructuredDataMarkup() {
let _ret = {
status: false,
result: ''
};
if (this.isValidForUse) {
_ret.status = this.containsJsonLd && this.containsMicroData;
_ret.result = _ret.status
? 'Page contains Structured Data for more than one markup format (this might include non-AMP relevant items)'
: 'Page Structured Data markup appears to be of a single format';
}
return _ret;
}
get containsAmpStructuredData() {
return this.isValidForUse ?
this.jsonLdTypeIsAmp || this.microdataTypeIsAmp :
false;
}
get containsAmpCarouselStructuredData() {
return this.isValidForUse ?
this.jsonLdTypeIsAmpCarousel || this.microdataTypeIsAmpCarousel :
false;
}
get containsIncompleteAmpCarouselStructuredData() {
// SD for one of the following is missing: Article || NewsArticle || BlogPosting || VideoObject
let _ret = {
status: false,
result: ''
};
if (this.isValidForUse) {
if (this.containsAmpStructuredData && !this.containsAmpCarouselStructuredData) {
_ret.status = true;
_ret.result = 'contains AMP Structured Data: is missing AMP Carousel supporting Structured Data: ';
}
if (!this.containsAmpStructuredData && !this.containsAmpCarouselStructuredData) {
_ret.status = true;
_ret.result = 'is missing AMP Structured Data: is missing AMP Carousel supporting Structured Data: ';
}
_ret.result = _ret.status
? _ret.result + 'Page might contain incomplete Top Stories Carousel for AMP markup'
: _ret.result + 'Page appears to contain complete Top Stories Carousel for AMP markup';
}
// console.log('=> this.containsIncompleteAmpCarouselStructuredData: ' + _ret.status);
// console.log('=> this.containsAmpStructuredData : ' + this.containsAmpStructuredData);
// console.log('=> this.containsAmpCarouselStructuredData : ' + this.containsAmpCarouselStructuredData);
return _ret;
}
get ampStructuredDataTypesFound() {
return this.isValidForUse ?
this._sd_amp_types_found_string :
false;
}
get ampCarouselStructuredDataTypesFound() {
return this.isValidForUse ?
this._sd_amp_carousel_types_found_string :
false;
}
get containsAmpNewsCarouselStructuredDataTypeMain() {
return this.isValidForUse ?
this._sd_type_is_amp_news_carousel_main :
false;
}
get containsAmpNewsCarouselStructuredDataTypeSupport() {
return this.isValidForUse ?
this._sd_type_is_amp_news_carousel_support :
false;
}
get containsAmpNewsCarouselStructuredDataTypeMainWithoutSupport() {
return this.isValidForUse ?
this._sd_type_is_amp_news_carousel_main_without_support :
false;
}
get containsAmpNewsCarouselStructuredDataTypeSupportWithoutMain() {
return this.isValidForUse ?
this._sd_type_is_amp_news_carousel_support_without_main :
false;
}
get containsByteOrderMark() {
return this.isValidForUse ?
this._contains_byte_order_mark :
false;
}
}
class HttpBodyParser extends HttpBodySniffer {
constructor(url, body) {
super(url, body);
this._index_of_search = -1;
}
bodyContains(search_text) { // override super method
if (this.isValidForUse) {
this._index_of_search = this._body.indexOf(search_text);
return (-1 < this._index_of_search);
} else {
throw 'ERROR: HttpBodyParser instance is not valid for use'; // eslint-disable-line no-throw-literal
}
}
}
const amphtml_validator = require('amphtml-validator');
var amphtml_validator_instance = null; // cache the instance
var amphtml_validator_instance_time = Date.now() - (61 * 60 * 1000); // 61 minutes ago
/**
* @returns {!Object} validatorInstance
*/
function lib_load_validator(opt_force_reload) { // force reload now redundant
return amphtml_validator_instance;
}
function lib_init_validator(next) {
if (amphtml_validator_instance_time < (Date.now() - (60 * 60 * 1000))) {
amphtml_validator_instance = null;
}
if (amphtml_validator_instance === null) {
console.log('[VALIDATOR REFRESH]: validator not found or out of date, loading new validator');
amphtml_validator_instance = amphtml_validator.getInstance().then((instance) => {
amphtml_validator_instance = instance;
amphtml_validator_instance_time = Date.now();
next();
});
} else {
next();
}
}
/**
* Renders the validation results into an array of human readable strings.
* @param {!Object} validationResult
* @param {string} validate_url to use in rendering error messages.
* @return {!Array<string>}
* @export
*/
function lib_renderValidationResult(validationResult, validate_url) {
const rendered = [];
if (CHECK_PASS === validationResult.status) {
rendered.push(CHECK_PASS);
} else {
rendered.push(CHECK_FAIL);
}
for (let ii = 0; ii < validationResult.errors.length; ii++) {
const error = validationResult.errors[ii];
let msg = validate_url + ': line ' + error.line + ', col ' + error.col + ': ' + error.message;
if (error.specUrl) {
msg += ' (see ' + error.specUrl + ')';
}
rendered.push(msg);
}
return rendered;
}
function lib_validate(body, validate_url) {
let _validator = lib_load_validator();
let _results = _validator.validateString(body);
let _output = lib_renderValidationResult(_results, validate_url);
return _output; //!!!NOTE: returns an ARRAY
}
function lib_validate_lines(body, validate_url) {
let _output = lib_validate(body, validate_url);
return _output.join(os.EOL); //!!!NOTE: returns a MULTILINE STRING
}
function lib_validate_json(body, validate_url) {
let _output = lib_validate(body, validate_url);
return _output; //!!!NOTE: returns an ARRAY
}
function fetch_and_validate_url(validate_url, on_output_callback, as_json) {
let http_response = new HttpResponse(validate_url);
if (http_response.urlIsOK()) { // do not bother if not...
let full_path = validate_url;
if (full_path.indexOf('http://') === 0 ||
full_path.indexOf('https://') === 0) {
let url_parsed = url.parse(full_path),
url_parsed_path = url_parsed.pathname;
if (url_parsed.search) {
url_parsed_path = url_parsed.pathname + url_parsed.search;
}
const callback = (res) => {
let chunks = [], body = '', output = '';
http_response.setResponse(res); //!!!DO THIS IMMEDIATELY else HttpResponse class is useless
if (!http_response.statusIsOK()) { // NOT (200 == this.http_response_code)
http_response.http_response_body = '';
on_output_callback(http_response, [CHECK_FAIL]); // !!! RETURN to front-end - - - - - - - - - - - -
}
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
http_response.setResponseEnded();
body = chunks.join('');
http_response.http_response_body = body;
if (http_response.statusIsOK()) {
if (0 === as_json) { // return output as JSON or not
output = lib_validate_lines(body, full_path); //!!!NOTE: gets a MULTILINE STRING
} else {
output = lib_validate_json(body, full_path); //!!!NOTE: gets an ARRAY
}
on_output_callback(http_response, output); // !!! RETURN to front-end - - - - - - - - - - - - -
}
});
};
const http_options = {
host: url_parsed.hostname,
path: url_parsed_path,
headers: { 'User-Agent': UA_AMPBENCH },
timeout: 3000,
};
let req = http_response.http_client.request(http_options, callback);
const handler = (err) => {
http_response.is_https_cert_ssl_error = err;
on_output_callback(http_response, [CHECK_FAIL]); // !!! RETURN to front-end - - - - - - - - - - - - - -
};
req.on('timeout', handler);
req.on('error', handler);
req.end();
}
} else {
http_response.http_response_body = '';
on_output_callback(http_response, [CHECK_FAIL]); // !!! RETURN to front-end - - - - - - - - - - - - - - - - - -
}
}
function fetch_and_parse_url_for_amplinks(request_url, on_parsed_callback) {
let __return = {
status: CHECK_FAIL, // status indicates successful fetch and parse, nothing more: client checks url content
url: request_url,
canonical_url: '',
amphtml_url: '',
amphtml_urls: [],
has_dns_prefetch: false
};
let __temp = null;
let http_response = new HttpResponse(request_url);
if (http_response.urlIsOK()) { // do not bother if not...
let full_path = request_url,
url_parsed = url.parse(full_path),
url_parsed_path = url_parsed.pathname;
if (url_parsed.search) {
url_parsed_path = url_parsed.pathname + url_parsed.search;
}
if (full_path.indexOf('http://') === 0 ||
full_path.indexOf('https://') === 0) {
const callback = (res) => {
let chunks = [], body = '';
http_response.setResponse(res); //!!!DO THIS IMMEDIATELY else HttpResponse class is useless
if (!http_response.statusIsOK()) { // NOT (200 == this.http_response_code)
__return.url = full_path;
__return.canonical_url = '';
__return.amphtml_url = '';
__return.amphtml_urls = [];
__return.has_dns_prefetch = false;
__return.status = CHECK_FAIL;
http_response.http_response_body = '';
on_parsed_callback(http_response, __return); // !!! RETURN to front-end - - - - - - - - - - - - - -
}
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
http_response.setResponseEnded();
body = chunks.join('');
http_response.http_response_body = body;
__temp = parse_body_for_amplinks(body, http_response);
__return.url = full_path;
__return.canonical_url = __temp.canonical_url;
__return.amphtml_url = __temp.amphtml_url;
__return.amphtml_urls = __temp.amphtml_urls;
__return.has_dns_prefetch = __temp.has_dns_prefetch;
__return.status = __temp.amphtml_urls.length > 0 ? CHECK_WARN : CHECK_PASS;
on_parsed_callback(http_response, __return); // !!! RETURN to front-end - - - - - - - - - - - - - - -
});
};
const http_options = {
host: url_parsed.hostname,
path: url_parsed_path,
headers: { 'User-Agent': UA_AMPBENCH },
timeout: 3000,