forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.js
1022 lines (924 loc) · 27 KB
/
config.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 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/** Version: 0.1.22.45 */
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/**
* @param {!Document} doc
* @return {string}
*/
function getReadyState(doc) {
return /** @type {string} */ (doc['readyState']);
}
/**
* Whether the document is ready.
* @param {!Document} doc
* @return {boolean}
*/
function isDocumentReady(doc) {
const readyState = getReadyState(doc);
return readyState != 'loading' && readyState != 'uninitialized';
}
/**
* Calls the callback when document is ready.
* @param {!Document} doc
* @param {function(!Document)} callback
*/
function onDocumentReady(doc, callback) {
onDocumentState(doc, isDocumentReady, callback);
}
/**
* Calls the callback when document's state satisfies the stateFn.
* @param {!Document} doc
* @param {function(!Document):boolean} stateFn
* @param {function(!Document)} callback
*/
function onDocumentState(doc, stateFn, callback) {
let ready = stateFn(doc);
if (ready) {
callback(doc);
} else {
const readyListener = () => {
if (stateFn(doc)) {
if (!ready) {
ready = true;
callback(doc);
}
doc.removeEventListener('readystatechange', readyListener);
}
};
doc.addEventListener('readystatechange', readyListener);
}
}
/**
* Returns a promise that is resolved when document is ready.
* @param {!Document} doc
* @return {!Promise<!Document>}
*/
function whenDocumentReady(doc) {
return new Promise(resolve => {
onDocumentReady(doc, resolve);
});
}
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/**
* @interface
*/
class Doc {
/**
* @return {!Window}
*/
getWin() {}
/**
* The `Document` node or analog.
* @return {!Node}
*/
getRootNode() {}
/**
* The `Document.documentElement` element or analog.
* @return {!Element}
*/
getRootElement() {}
/**
* The `Document.head` element or analog. Returns `null` if not available
* yet.
* @return {!Element}
*/
getHead() {}
/**
* The `Document.body` element or analog. Returns `null` if not available
* yet.
* @return {?Element}
*/
getBody() {}
/**
* Whether the document has been fully constructed.
* @return {boolean}
*/
isReady() {}
/**
* Resolved when document has been fully constructed.
* @return {!Promise}
*/
whenReady() {}
}
/** @implements {Doc} */
class GlobalDoc {
/**
* @param {!Window|!Document} winOrDoc
*/
constructor(winOrDoc) {
const isWin = !!winOrDoc.document;
/** @private @const {!Window} */
this.win_ = isWin ?
/** @type {!Window} */ (winOrDoc) :
/** @type {!Window} */ (
(/** @type {!Document} */ (winOrDoc)).defaultView);
/** @private @const {!Document} */
this.doc_ = isWin ?
/** @type {!Window} */ (winOrDoc).document :
/** @type {!Document} */ (winOrDoc);
}
/** @override */
getWin() {
return this.win_;
}
/** @override */
getRootNode() {
return this.doc_;
}
/** @override */
getRootElement() {
return this.doc_.documentElement;
}
/** @override */
getHead() {
// `document.head` always has a chance to be parsed, at least partially.
return /** @type {!Element} */ (this.doc_.head);
}
/** @override */
getBody() {
return this.doc_.body;
}
/** @override */
isReady() {
return isDocumentReady(this.doc_);
}
/** @override */
whenReady() {
return whenDocumentReady(this.doc_);
}
}
/**
* @param {!Document|!Window|!Doc} input
* @return {!Doc}
*/
function resolveDoc(input) {
// Is it a `Document`
if ((/** @type {!Document} */ (input)).nodeType === /* DOCUMENT */ 9) {
return new GlobalDoc(/** @type {!Document} */ (input));
}
// Is it a `Window`?
if ((/** @type {!Window} */ (input)).document) {
return new GlobalDoc(/** @type {!Window} */ (input));
}
return /** @type {!Doc} */ (input);
}
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/**
*/
class PageConfig {
/**
* @param {string} productOrPublicationId
* @param {boolean} locked
*/
constructor(productOrPublicationId, locked) {
let publicationId, productId, label;
const div = productOrPublicationId.indexOf(':');
if (div != -1) {
// The argument is a product id.
productId = productOrPublicationId;
publicationId = productId.substring(0, div);
label = productId.substring(div + 1);
if (label == '*') {
throw new Error('wildcard disallowed');
}
} else {
// The argument is a publication id.
publicationId = productOrPublicationId;
productId = null;
label = null;
}
/** @private @const {string} */
this.publicationId_ = publicationId;
/** @private @const {?string} */
this.productId_ = productId;
/** @private @const {?string} */
this.label_ = label;
/** @private @const {boolean} */
this.locked_ = locked;
}
/**
* @return {string}
*/
getPublicationId() {
return this.publicationId_;
}
/**
* @return {?string}
*/
getProductId() {
return this.productId_;
}
/**
* @return {?string}
*/
getLabel() {
return this.label_;
}
/**
* @return {boolean}
*/
isLocked() {
return this.locked_;
}
}
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/**
* Whether the element have a next node in the document order.
* This means either:
* a. The element itself has a nextSibling.
* b. Any of the element ancestors has a nextSibling.
* @param {!Element} element
* @param {?Node=} opt_stopNode
* @return {boolean}
*/
function hasNextNodeInDocumentOrder(element, opt_stopNode) {
let currentElement = element;
do {
if (currentElement.nextSibling) {
return true;
}
} while ((currentElement = currentElement.parentNode) &&
currentElement != opt_stopNode);
return false;
}
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/**
* Determines if value is actually an Array.
* @param {*} value
* @return {boolean}
*/
function isArray(value) {
return Array.isArray(value);
}
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
/**
* Simple wrapper around JSON.parse that casts the return value
* to JsonObject.
* Create a new wrapper if an array return value is desired.
* @param {*} json JSON string to parse
* @return {?JsonObject|undefined} May be extend to parse arrays.
*/
function parseJson(json) {
return /** @type {?JsonObject} */(JSON.parse(/** @type {string} */ (json)));
}
/**
* Parses the given `json` string without throwing an exception if not valid.
* Returns `undefined` if parsing fails.
* Returns the `Object` corresponding to the JSON string when parsing succeeds.
* @param {*} json JSON string to parse
* @param {function(!Error)=} opt_onFailed Optional function that will be called
* with the error if parsing fails.
* @return {?JsonObject|undefined} May be extend to parse arrays.
*/
function tryParseJson(json, opt_onFailed) {
try {
return parseJson(json);
} catch (e) {
if (opt_onFailed) {
opt_onFailed(e);
}
return undefined;
}
}
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* 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.
*/
const ALREADY_SEEN = '__SWG-SEEN__';
const ALLOWED_TYPES = [
'CreativeWork',
'Article',
'NewsArticle',
'Blog',
'Comment',
'Course',
'HowTo',
'Message',
'Review',
'WebPage',
];
// RegExp for quickly scanning LD+JSON for allowed types
const RE_ALLOWED_TYPES = new RegExp(ALLOWED_TYPES.join('|'));
/**
*/
class PageConfigResolver {
/**
* @param {!Window|!Document|!Doc} winOrDoc
*/
constructor(winOrDoc) {
/** @private @const {!Doc} */
this.doc_ = resolveDoc(winOrDoc);
/** @private {?function((!PageConfig|!Promise))} */
this.configResolver_ = null;
/** @private @const {!Promise<!PageConfig>} */
this.configPromise_ = new Promise(resolve => {
this.configResolver_ = resolve;
});
/** @private @const {!MetaParser} */
this.metaParser_ = new MetaParser(this.doc_);
/** @private @const {!JsonLdParser} */
this.ldParser_ = new JsonLdParser(this.doc_);
/** @private @const {!MicrodataParser} */
this.microdataParser_ = new MicrodataParser(this.doc_);
}
/**
* @return {!Promise<!PageConfig>}
*/
resolveConfig() {
// Try resolve the config at different times.
Promise.resolve().then(this.check.bind(this));
this.doc_.whenReady().then(this.check.bind(this));
return this.configPromise_;
}
/**
* @return {?PageConfig}
*/
check() {
// Already resolved.
if (!this.configResolver_) {
return null;
}
let config = this.metaParser_.check();
if (!config) {
config = this.ldParser_.check();
}
if (!config) {
config = this.microdataParser_.check();
}
if (config) {
// Product ID has been found: initialize the rest of the config.
this.configResolver_(config);
this.configResolver_ = null;
} else if (this.doc_.isReady()) {
this.configResolver_(Promise.reject(
new Error('No config could be discovered in the page')));
this.configResolver_ = null;
}
return config;
}
}
class TypeChecker {
constructor() {
}
/**
* Check value from json
* @param {?Array|string} value
* @param {Array<string>} expectedTypes
* @return {boolean}
*/
checkValue(value, expectedTypes) {
if (!value) {
return false;
}
return this.checkArray(this.toArray_(value), expectedTypes);
}
/**
* Checks space delimited list of types
* @param {?string} itemtype
* @param {Array<string>} expectedTypes
* @return {boolean}
*/
checkString(itemtype, expectedTypes) {
if (!itemtype) {
return false;
}
return this.checkArray(itemtype.split(/\s+/), expectedTypes);
}
/**
* @param {Array<?string>} typeArray
* @param {Array<string>} expectedTypes
* @return {boolean}
*/
checkArray(typeArray, expectedTypes) {
let found = false;
typeArray.forEach(candidateType => {
found = found || expectedTypes.includes(
candidateType.replace(/^http:\/\/schema.org\//i,'')
);
});
return found;
}
/*
* @param {?Array|string} value
* @return {Array}
* @private
*/
toArray_(value) {
return isArray(value) ? value : [value];
}
}
class MetaParser {
/**
* @param {!Doc} doc
*/
constructor(doc) {
/** @private @const {!Doc} */
this.doc_ = doc;
}
/**
* @return {?PageConfig}
*/
check() {
if (!this.doc_.getBody()) {
// Wait until the whole `<head>` is parsed.
return null;
}
// Try to find product id.
const productId = getMetaTag(this.doc_.getRootNode(),
'subscriptions-product-id');
if (!productId) {
return null;
}
// Is locked?
const accessibleForFree = getMetaTag(this.doc_.getRootNode(),
'subscriptions-accessible-for-free');
const locked = (accessibleForFree &&
accessibleForFree.toLowerCase() == 'false') || false;
return new PageConfig(productId, locked);
}
}
class JsonLdParser {
/**
* @param {!Doc} doc
*/
constructor(doc) {
/** @private @const {!Doc} */
this.doc_ = doc;
/** @private @const @function */
this.checkType_ = new TypeChecker();
}
/**
* @return {?PageConfig}
*/
check() {
if (!this.doc_.getBody()) {
// Wait until the whole `<head>` is parsed.
return null;
}
const domReady = this.doc_.isReady();
// type: 'application/ld+json'
const elements = this.doc_.getRootNode().querySelectorAll(
'script[type="application/ld+json"]');
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
if (element[ALREADY_SEEN] ||
!element.textContent ||
!domReady && !hasNextNodeInDocumentOrder(element)) {
continue;
}
element[ALREADY_SEEN] = true;
if (!RE_ALLOWED_TYPES.test(element.textContent)) {
continue;
}
const possibleConfig = this.tryExtractConfig_(element);
if (possibleConfig) {
return possibleConfig;
}
}
return null;
}
/**
* @param {!Element} element
* @return {?PageConfig}
*/
tryExtractConfig_(element) {
const json = tryParseJson(element.textContent);
if (!json) {
return null;
}
// Must be an ALLOWED_TYPE
if (!this.checkType_.checkValue(json['@type'], ALLOWED_TYPES)) {
return null;
}
// Must have a isPartOf[@type=Product].
let productId = null;
const partOfArray = this.valueArray_(json, 'isPartOf');
if (partOfArray) {
for (let i = 0; i < partOfArray.length; i++) {
productId = this.discoverProductId_(partOfArray[i]);
if (productId) {
break;
}
}
}
if (!productId) {
return null;
}
// Found product id, just check for the access flag.
const isAccessibleForFree = this.bool_(
this.singleValue_(json, 'isAccessibleForFree'),
/* default */ true);
return new PageConfig(productId, !isAccessibleForFree);
}
/**
* @param {*} value
* @param {boolean} def
* @return {boolean}
*/
bool_(value, def) {
if (value == null || value === '') {
return def;
}
if (typeof value == 'boolean') {
return value;
}
if (typeof value == 'string') {
const lowercase = value.toLowerCase();
if (lowercase == 'false') {
return false;
}
if (lowercase == 'true') {
return true;
}
}
return def;
}
/**
* @param {!Object} json
* @return {?string}
*/
discoverProductId_(json) {
// Must have type `Product`.
if (!this.checkType_.checkValue(json['@type'], ['Product'])) {
return null;
}
return /** @type {?string} */ (this.singleValue_(json, 'productID'));
}
/**
* @param {!Object} json
* @param {string} name
* @return {?Array}
*/
valueArray_(json, name) {
const value = json[name];
if (value == null || value === '') {
return null;
}
return isArray(value) ? value : [value];
}
/**
* @param {!Object} json
* @param {string} name
* @return {*}
*/
singleValue_(json, name) {
const valueArray = this.valueArray_(json, name);
const value = valueArray && valueArray[0];
return (value == null || value === '') ? null : value;
}
}
class MicrodataParser {
/**
* @param {!Doc} doc
*/
constructor(doc) {
/** @private @const {!Doc} */
this.doc_ = doc;
/** @private {?boolean} */
this.access_ = null;
/** @private {?string} */
this.productId_ = null;
/** @private @const @function */
this.checkType_ = new TypeChecker();
}
/**
* Returns false if access is restricted, otherwise true
* @param {!Element} root An element that is an item of type in ALLOWED_TYPES list
* @return {?boolean} locked access
* @private
*/
discoverAccess_(root) {
const ALREADY_SEEN = 'alreadySeenForAccessInfo';
const nodeList = root
.querySelectorAll("[itemprop='isAccessibleForFree']");
for (let i = 0; nodeList[i]; i++) {
const element = nodeList[i];
const content = element.getAttribute('content') || element.textContent;
if (!content) {
continue;
}
if (this.isValidElement_(element, root, ALREADY_SEEN)) {
let accessForFree = null;
if (content.toLowerCase() == 'true') {
accessForFree = true;
} else if (content.toLowerCase() == 'false') {
accessForFree = false;
}
return accessForFree;
}
}
return null;
}
/**
* Verifies if an element is valid based on the following
* - child of an item of one the the ALLOWED_TYPES
* - not a child of an item of any other type
* - not seen before, marked using the alreadySeen tag
* @param {?Element} current the element to be verified
* @param {!Element} root the parent to track up to
* @param {!string} alreadySeen used to tag already visited nodes
* @return {!boolean} valid node
* @private
*/
isValidElement_(current, root, alreadySeen) {
for (let node = current;
node && !node[alreadySeen]; node = node.parentNode) {
node[alreadySeen] = true;
// document nodes don't have hasAttribute
if (node.hasAttribute && node.hasAttribute('itemscope')) {
/**{?string} */
const type = node.getAttribute('itemtype');
return this.checkType_.checkString(type, ALLOWED_TYPES);
}
}
return false;
}
/**
* Obtains the product ID that meets the requirements
* - child of an item of one of ALLOWED_TYPES
* - Not a child of an item of type 'Section'
* - child of an item of type 'productID'
* @param {!Element} root An element that is an item of an ALLOWED_TYPES
* @return {?string} product ID, if found
* @private
*/
discoverProductId_(root) {
const ALREADY_SEEN = 'alreadySeenForProductInfo';
const nodeList = root
.querySelectorAll('[itemprop="productID"]');
for (let i = 0; nodeList[i]; i++) {
const element = nodeList[i];
const content = element.getAttribute('content') || element.textContent;
const item = element.closest('[itemtype][itemscope]');
const type = item.getAttribute('itemtype');
if (type.indexOf('http://schema.org/Product') <= -1) {
continue;
}
if (this.isValidElement_(item.parentElement, root, ALREADY_SEEN)) {
return content;
}
}
return null;
}
/**
* Returns PageConfig if available
* @return {?PageConfig} PageConfig found so far
*/
getPageConfig_() {
let locked = null;
if (this.access_ != null) {
locked = !this.access_;
} else if (this.doc_.isReady()) {
// Default to unlocked
locked = false;
}
if (this.productId_ != null && locked != null) {
return new PageConfig(this.productId_, locked);
}
return null;
}
/**
* Extracts page config from Microdata in the DOM
* @return {?PageConfig} PageConfig found
*/
tryExtractConfig_() {
let config = this.getPageConfig_();
if (config) {
return config;
}
// Grab all the nodes with an itemtype and filter for our allowed types
const nodeList = Array.prototype.slice.call(
this.doc_.getRootNode().querySelectorAll('[itemscope][itemtype]')
).filter(
node => this.checkType_.checkString(
node.getAttribute('itemtype'), ALLOWED_TYPES)
);
for (let i = 0; nodeList[i] && config == null; i++) {
const element = nodeList[i];
if (this.access_ == null) {
this.access_ = this.discoverAccess_(element);
}
if (!this.productId_) {
this.productId_ = this.discoverProductId_(element);
}
config = this.getPageConfig_();
}
return config;
}
/**
* @return {?PageConfig}
*/
check() {
if (!this.doc_.getBody()) {
// Wait until the whole `<head>` is parsed.
return null;
}
return this.tryExtractConfig_();
}
}
/**
* Returns the value from content attribute of a meta tag with given name.
*
* If multiple tags are found, the first value is returned.
*
* @param {!Node} rootNode
* @param {string} name The tag name to look for.
* @return {?string} attribute value or empty string.
* @private
*/
function getMetaTag(rootNode, name) {
const el = rootNode.querySelector(`meta[name="${name}"]`);
if (el) {
return el.getAttribute('content');
}
return null;
}