-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
log.js
980 lines (912 loc) · 26.4 KB
/
log.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
/**
* Copyright 2015 The AMP HTML 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.
*/
import {getMode} from './mode';
import {internalRuntimeVersion} from './internal-version';
import {isArray, isEnumValue} from './types';
import {once} from './utils/function';
import {urls} from './config';
const noop = () => {};
/**
* Triple zero width space.
*
* This is added to user error messages, so that we can later identify
* them, when the only thing that we have is the message. This is the
* case in many browsers when the global exception handler is invoked.
*
* @const {string}
*/
export const USER_ERROR_SENTINEL = '\u200B\u200B\u200B';
/**
* Four zero width space.
*
* @const {string}
*/
export const USER_ERROR_EMBED_SENTINEL = '\u200B\u200B\u200B\u200B';
/**
* @param {string} message
* @return {boolean} Whether this message was a user error.
*/
export function isUserErrorMessage(message) {
return message.indexOf(USER_ERROR_SENTINEL) >= 0;
}
/**
* @param {string} message
* @return {string} The new message without USER_ERROR_SENTINEL
*/
export function stripUserError(message) {
return message.replace(USER_ERROR_SENTINEL, '');
}
/**
* @param {string} message
* @return {boolean} Whether this message was a a user error from an iframe embed.
*/
export function isUserErrorEmbed(message) {
return message.indexOf(USER_ERROR_EMBED_SENTINEL) >= 0;
}
/**
* @enum {number}
*/
export const LogLevel = {
OFF: 0,
ERROR: 1,
WARN: 2,
INFO: 3,
FINE: 4,
};
/**
* Sets reportError function. Called from error.js to break cyclic
* dependency.
* @param {function(*, !Element=)|undefined} fn
*/
export function setReportError(fn) {
self.__AMP_REPORT_ERROR = fn;
}
/**
* @type {!LogLevel|undefined}
* @private
*/
let levelOverride_ = undefined;
/**
* @param {!LogLevel} level
*/
export function overrideLogLevel(level) {
levelOverride_ = level;
}
/**
* Prefixes `internalRuntimeVersion` with the `01` channel signifier (for prod.) for
* extracted message URLs.
* (Specific channel is irrelevant: message tables are invariant on internal version.)
* @return {string}
*/
const messageUrlRtv = () => `01${internalRuntimeVersion()}`;
/**
* Gets a URL to display a message on amp.dev.
* @param {string} id
* @param {!Array} interpolatedParts
* @return {string}
*/
const externalMessageUrl = (id, interpolatedParts) =>
interpolatedParts.reduce(
(prefix, arg) => `${prefix}&s[]=${messageArgToEncodedComponent(arg)}`,
`https://log.amp.dev/?v=${messageUrlRtv()}&id=${encodeURIComponent(id)}`
);
/**
* URL to simple log messages table JSON file, which contains an Object<string, string>
* which maps message id to full message template.
* @return {string}
*/
const externalMessagesSimpleTableUrl = () =>
`${urls.cdn}/rtv/${messageUrlRtv()}/log-messages.simple.json`;
/**
* @param {*} arg
* @return {string}
*/
const messageArgToEncodedComponent = (arg) =>
encodeURIComponent(String(elementStringOrPassthru(arg)));
/**
* Logging class. Use of sentinel string instead of a boolean to check user/dev
* errors because errors could be rethrown by some native code as a new error,
* and only a message would survive. Also, some browser don’t support a 5th
* error object argument in window.onerror. List of supporting browser can be
* found here:
* https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror.html
* @final
* @private Visible for testing only.
*/
export class Log {
/**
* opt_suffix will be appended to error message to identify the type of the
* error message. We can't rely on the error object to pass along the type
* because some browsers do not have this param in its window.onerror API.
* See:
* https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror.html
*
* @param {!Window} win
* @param {function(number, boolean):!LogLevel} levelFunc
* @param {string=} opt_suffix
*/
constructor(win, levelFunc, opt_suffix = '') {
/**
* In tests we use the main test window instead of the iframe where
* the tests runs because only the former is relayed to the console.
* @const {!Window}
*/
this.win = getMode().test && win.__AMP_TEST_IFRAME ? win.parent : win;
/** @private @const {function(number, boolean):!LogLevel} */
this.levelFunc_ = levelFunc;
/** @private @const {!LogLevel} */
this.level_ = this.defaultLevel_();
/** @private @const {string} */
this.suffix_ = opt_suffix;
/** @private {?JsonObject} */
this.messages_ = null;
this.fetchExternalMessagesOnce_ = once(() => {
win
.fetch(externalMessagesSimpleTableUrl())
.then((response) => response.json(), noop)
.then((opt_messages) => {
if (opt_messages) {
this.messages_ = /** @type {!JsonObject} */ (opt_messages);
}
});
});
}
/**
* @return {!LogLevel}
* @private
*/
getLevel_() {
return levelOverride_ !== undefined ? levelOverride_ : this.level_;
}
/**
* @return {!LogLevel}
* @private
*/
defaultLevel_() {
// No console - can't enable logging.
if (!this.win.console || !this.win.console.log) {
return LogLevel.OFF;
}
// Logging has been explicitly disabled.
if (getMode().log == '0') {
return LogLevel.OFF;
}
// Logging is enabled for tests directly.
if (getMode().test && this.win.ENABLE_LOG) {
return LogLevel.FINE;
}
// LocalDev by default allows INFO level, unless overriden by `#log`.
if (getMode().localDev && !getMode().log) {
return LogLevel.INFO;
}
return this.defaultLevelWithFunc_();
}
/**
* @return {!LogLevel}
* @private
*/
defaultLevelWithFunc_() {
// Delegate to the specific resolver.
return this.levelFunc_(parseInt(getMode().log, 10), getMode().development);
}
/**
* @param {string} tag
* @param {string} level
* @param {!Array} messages
*/
msg_(tag, level, messages) {
if (this.getLevel_() != LogLevel.OFF) {
let fn = this.win.console.log;
if (level == 'ERROR') {
fn = this.win.console.error || fn;
} else if (level == 'INFO') {
fn = this.win.console.info || fn;
} else if (level == 'WARN') {
fn = this.win.console.warn || fn;
}
const args = this.maybeExpandMessageArgs_(messages);
// Prefix console message with "[tag]".
const prefix = `[${tag}]`;
if (typeof args[0] === 'string') {
// Prepend string to avoid breaking string substitutions e.g. %s.
args[0] = prefix + ' ' + args[0];
} else {
args.unshift(prefix);
}
fn.apply(this.win.console, args);
}
}
/**
* Whether the logging is enabled.
* @return {boolean}
*/
isEnabled() {
return this.getLevel_() != LogLevel.OFF;
}
/**
* Reports a fine-grained message.
* @param {string} tag
* @param {...*} var_args
*/
fine(tag, var_args) {
if (this.getLevel_() >= LogLevel.FINE) {
this.msg_(tag, 'FINE', Array.prototype.slice.call(arguments, 1));
}
}
/**
* Reports a informational message.
* @param {string} tag
* @param {...*} var_args
*/
info(tag, var_args) {
if (this.getLevel_() >= LogLevel.INFO) {
this.msg_(tag, 'INFO', Array.prototype.slice.call(arguments, 1));
}
}
/**
* Reports a warning message.
* @param {string} tag
* @param {...*} var_args
*/
warn(tag, var_args) {
if (this.getLevel_() >= LogLevel.WARN) {
this.msg_(tag, 'WARN', Array.prototype.slice.call(arguments, 1));
}
}
/**
* Reports an error message. If the logging is disabled, the error is rethrown
* asynchronously.
* @param {string} tag
* @param {...*} var_args
* @return {!Error|undefined}
* @private
*/
error_(tag, var_args) {
if (this.getLevel_() >= LogLevel.ERROR) {
this.msg_(tag, 'ERROR', Array.prototype.slice.call(arguments, 1));
} else {
const error = createErrorVargs.apply(
null,
Array.prototype.slice.call(arguments, 1)
);
this.prepareError_(error);
return error;
}
}
/**
* Reports an error message.
* @param {string} tag
* @param {...*} var_args
*/
error(tag, var_args) {
const error = this.error_.apply(this, arguments);
if (error) {
error.name = tag || error.name;
// __AMP_REPORT_ERROR is installed globally per window in the entry point.
self.__AMP_REPORT_ERROR(error);
}
}
/**
* Reports an error message and marks with an expected property. If the
* logging is disabled, the error is rethrown asynchronously.
* @param {string} unusedTag
* @param {...*} var_args
*/
expectedError(unusedTag, var_args) {
const error = this.error_.apply(this, arguments);
if (error) {
error.expected = true;
// __AMP_REPORT_ERROR is installed globally per window in the entry point.
self.__AMP_REPORT_ERROR(error);
}
}
/**
* Creates an error object.
* @param {...*} var_args
* @return {!Error}
*/
createError(var_args) {
const error = createErrorVargs.apply(null, arguments);
this.prepareError_(error);
return error;
}
/**
* Creates an error object with its expected property set to true.
* @param {...*} var_args
* @return {!Error}
*/
createExpectedError(var_args) {
const error = createErrorVargs.apply(null, arguments);
this.prepareError_(error);
error.expected = true;
return error;
}
/**
* Throws an error if the first argument isn't trueish.
*
* Supports argument substitution into the message via %s placeholders.
*
* Throws an error object that has two extra properties:
* - associatedElement: This is the first element provided in the var args.
* It can be used for improved display of error messages.
* - messageArray: The elements of the substituted message as non-stringified
* elements in an array. When e.g. passed to console.error this yields
* native displays of things like HTML elements.
*
* @param {T} shouldBeTrueish The value to assert. The assert fails if it does
* not evaluate to true.
* @param {!Array|string=} opt_message The assertion message
* @param {...*} var_args Arguments substituted into %s in the message.
* @return {T} The value of shouldBeTrueish.
* @throws {!Error} When `value` is falsey.
* @template T
* @closurePrimitive {asserts.truthy}
*/
assert(shouldBeTrueish, opt_message, var_args) {
let firstElement;
if (isArray(opt_message)) {
return this.assert.apply(
this,
[shouldBeTrueish].concat(
this.expandMessageArgs_(/** @type {!Array} */ (opt_message))
)
);
}
if (!shouldBeTrueish) {
const message = opt_message || 'Assertion failed';
const splitMessage = message.split('%s');
const first = splitMessage.shift();
let formatted = first;
const messageArray = [];
let i = 2;
pushIfNonEmpty(messageArray, first);
while (splitMessage.length > 0) {
const nextConstant = splitMessage.shift();
const val = arguments[i++];
if (val && val.tagName) {
firstElement = val;
}
messageArray.push(val);
pushIfNonEmpty(messageArray, nextConstant.trim());
formatted += stringOrElementString(val) + nextConstant;
}
const e = new Error(formatted);
e.fromAssert = true;
e.associatedElement = firstElement;
e.messageArray = messageArray;
this.prepareError_(e);
// __AMP_REPORT_ERROR is installed globally per window in the entry point.
self.__AMP_REPORT_ERROR(e);
throw e;
}
return shouldBeTrueish;
}
/**
* Throws an error if the first argument isn't an Element
*
* Otherwise see `assert` for usage
*
* @param {*} shouldBeElement
* @param {!Array|string=} opt_message The assertion message
* @return {!Element} The value of shouldBeTrueish.
* @template T
* @closurePrimitive {asserts.matchesReturn}
*/
assertElement(shouldBeElement, opt_message) {
const shouldBeTrueish = shouldBeElement && shouldBeElement.nodeType == 1;
this.assertType_(
shouldBeElement,
shouldBeTrueish,
'Element expected',
opt_message
);
return /** @type {!Element} */ (shouldBeElement);
}
/**
* Throws an error if the first argument isn't a string. The string can
* be empty.
*
* For more details see `assert`.
*
* @param {*} shouldBeString
* @param {!Array|string=} opt_message The assertion message
* @return {string} The string value. Can be an empty string.
* @closurePrimitive {asserts.matchesReturn}
*/
assertString(shouldBeString, opt_message) {
this.assertType_(
shouldBeString,
typeof shouldBeString == 'string',
'String expected',
opt_message
);
return /** @type {string} */ (shouldBeString);
}
/**
* Throws an error if the first argument isn't a number. The allowed values
* include `0` and `NaN`.
*
* For more details see `assert`.
*
* @param {*} shouldBeNumber
* @param {!Array|string=} opt_message The assertion message
* @return {number} The number value. The allowed values include `0`
* and `NaN`.
* @closurePrimitive {asserts.matchesReturn}
*/
assertNumber(shouldBeNumber, opt_message) {
this.assertType_(
shouldBeNumber,
typeof shouldBeNumber == 'number',
'Number expected',
opt_message
);
return /** @type {number} */ (shouldBeNumber);
}
/**
* Throws an error if the first argument is not an array.
* The array can be empty.
*
* @param {*} shouldBeArray
* @param {!Array|string=} opt_message The assertion message
* @return {!Array} The array value
* @closurePrimitive {asserts.matchesReturn}
*/
assertArray(shouldBeArray, opt_message) {
this.assertType_(
shouldBeArray,
isArray(shouldBeArray),
'Array expected',
opt_message
);
return /** @type {!Array} */ (shouldBeArray);
}
/**
* Throws an error if the first argument isn't a boolean.
*
* For more details see `assert`.
*
* @param {*} shouldBeBoolean
* @param {!Array|string=} opt_message The assertion message
* @return {boolean} The boolean value.
* @closurePrimitive {asserts.matchesReturn}
*/
assertBoolean(shouldBeBoolean, opt_message) {
this.assertType_(
shouldBeBoolean,
!!shouldBeBoolean === shouldBeBoolean,
'Boolean expected',
opt_message
);
return /** @type {boolean} */ (shouldBeBoolean);
}
/**
* Asserts and returns the enum value. If the enum doesn't contain such a
* value, the error is thrown.
*
* @param {!Object<T>} enumObj
* @param {string} s
* @param {string=} opt_enumName
* @return {T}
* @template T
* @closurePrimitive {asserts.matchesReturn}
*/
assertEnumValue(enumObj, s, opt_enumName) {
if (isEnumValue(enumObj, s)) {
return s;
}
this.assert(false, 'Unknown %s value: "%s"', opt_enumName || 'enum', s);
}
/**
* @param {!Error} error
* @private
*/
prepareError_(error) {
error = duplicateErrorIfNecessary(error);
if (this.suffix_) {
if (!error.message) {
error.message = this.suffix_;
} else if (error.message.indexOf(this.suffix_) == -1) {
error.message += this.suffix_;
}
} else if (isUserErrorMessage(error.message)) {
error.message = error.message.replace(USER_ERROR_SENTINEL, '');
}
}
/**
* @param {!Array} args
* @return {!Array}
* @private
*/
maybeExpandMessageArgs_(args) {
if (isArray(args[0])) {
return this.expandMessageArgs_(/** @type {!Array} */ (args[0]));
}
return args;
}
/**
* Either redirects a pair of (errorId, ...args) to a URL where the full
* message is displayed, or displays it from a fetched table.
*
* This method is used by the output of the `transform-log-methods` babel
* plugin. It should not be used directly. Use the (*error|assert*|info|warn)
* methods instead.
*
* @param {!Array} parts
* @return {!Array}
* @private
*/
expandMessageArgs_(parts) {
// First value should exist.
const id = parts.shift();
// Best effort fetch of message template table.
// Since this is async, the first few logs might be indirected to a URL even
// if in development mode. Message table is ~small so this should be a short
// gap.
if (getMode(this.win).development) {
this.fetchExternalMessagesOnce_();
}
if (this.messages_ && id in this.messages_) {
return [this.messages_[id]].concat(parts);
}
return [`More info at ${externalMessageUrl(id, parts)}`];
}
/**
* Asserts types, backbone of `assertNumber`, `assertString`, etc.
*
* It understands array-based "id"-contracted messages.
*
* Otherwise creates a sprintf syntax string containing the optional message or the
* default. An interpolation token is added at the end to include the `subject`.
* @param {*} subject
* @param {*} assertion
* @param {string} defaultMessage
* @param {!Array|string=} opt_message
* @private
*/
assertType_(subject, assertion, defaultMessage, opt_message) {
if (isArray(opt_message)) {
this.assert(assertion, opt_message.concat(subject));
} else {
this.assert(assertion, `${opt_message || defaultMessage}: %s`, subject);
}
}
}
/**
* @param {string|!Element} val
* @return {string}
*/
const stringOrElementString = (val) =>
/** @type {string} */ (elementStringOrPassthru(val));
/**
* @param {*} val
* @return {*}
*/
function elementStringOrPassthru(val) {
// Do check equivalent to `val instanceof Element` without cross-window bug
if (val && val.nodeType == 1) {
return val.tagName.toLowerCase() + (val.id ? '#' + val.id : '');
}
return val;
}
/**
* @param {!Array} array
* @param {*} val
*/
function pushIfNonEmpty(array, val) {
if (val != '') {
array.push(val);
}
}
/**
* Some exceptions (DOMException, namely) have read-only message.
* @param {!Error} error
* @return {!Error};
*/
export function duplicateErrorIfNecessary(error) {
const messageProperty = Object.getOwnPropertyDescriptor(error, 'message');
if (messageProperty && messageProperty.writable) {
return error;
}
const {message, stack} = error;
const e = new Error(message);
// Copy all the extraneous things we attach.
for (const prop in error) {
e[prop] = error[prop];
}
// Ensure these are copied.
e.stack = stack;
return e;
}
/**
* @param {...*} var_args
* @return {!Error}
* @visibleForTesting
*/
export function createErrorVargs(var_args) {
let error = null;
let message = '';
for (let i = 0; i < arguments.length; i++) {
const arg = arguments[i];
if (arg instanceof Error && !error) {
error = duplicateErrorIfNecessary(arg);
} else {
if (message) {
message += ' ';
}
message += arg;
}
}
if (!error) {
error = new Error(message);
} else if (message) {
error.message = message + ': ' + error.message;
}
return error;
}
/**
* Rethrows the error without terminating the current context. This preserves
* whether the original error designation is a user error or a dev error.
* @param {...*} var_args
*/
export function rethrowAsync(var_args) {
const error = createErrorVargs.apply(null, arguments);
setTimeout(() => {
// reportError is installed globally per window in the entry point.
self.__AMP_REPORT_ERROR(error);
throw error;
});
}
/**
* Cache for logs. We do not use a Service since the service module depends
* on Log and closure literally can't even.
* @type {{user: ?Log, dev: ?Log, userForEmbed: ?Log}}
*/
self.__AMP_LOG = self.__AMP_LOG || {
user: null,
dev: null,
userForEmbed: null,
};
const logs = self.__AMP_LOG;
/**
* Eventually holds a constructor for Log objects. Lazily initialized, so we
* can avoid ever referencing the real constructor except in JS binaries
* that actually want to include the implementation.
* @type {?typeof Log}
*/
let logConstructor = null;
/**
* Initializes log constructor.
*/
export function initLogConstructor() {
logConstructor = Log;
// Initialize instances for use. If a binary (an extension for example) that
// does not call `initLogConstructor` invokes `dev()` or `user()` earlier than
// the binary that does call `initLogConstructor` (amp.js), the extension will
// throw an error as that extension will never be able to initialize the log
// instances and we also don't want it to call `initLogConstructor` either
// (since that will cause the Log implementation to be bundled into that
// binary). So we must initialize the instances eagerly so that they are ready
// for use (stored globally) after the main binary calls `initLogConstructor`.
dev();
user();
}
/**
* Resets log constructor for testing.
*/
export function resetLogConstructorForTesting() {
logConstructor = null;
}
/**
* Publisher level log.
*
* Enabled in the following conditions:
* 1. Not disabled using `#log=0`.
* 2. Development mode is enabled via `#development=1` or logging is explicitly
* enabled via `#log=D` where D >= 1.
* 3. AMP.setLogLevel(D) is called, where D >= 1.
*
* @param {!Element=} opt_element
* @return {!Log}
*/
export function user(opt_element) {
if (!logs.user) {
logs.user = getUserLogger(USER_ERROR_SENTINEL);
}
if (!isFromEmbed(logs.user.win, opt_element)) {
return logs.user;
} else {
if (logs.userForEmbed) {
return logs.userForEmbed;
}
return (logs.userForEmbed = getUserLogger(USER_ERROR_EMBED_SENTINEL));
}
}
/**
* Getter for user logger
* @param {string=} suffix
* @return {!Log}
*/
function getUserLogger(suffix) {
if (!logConstructor) {
throw new Error('failed to call initLogConstructor');
}
return new logConstructor(
self,
(logNum, development) => {
if (development || logNum >= 1) {
return LogLevel.FINE;
}
return LogLevel.WARN;
},
suffix
);
}
/**
* AMP development log. Calls to `devLog().assert` and `dev.fine` are stripped
* in the PROD binary. However, `devLog().assert` result is preserved in either
* case.
*
* Enabled in the following conditions:
* 1. Not disabled using `#log=0`.
* 2. Logging is explicitly enabled via `#log=D`, where D >= 2.
* 3. AMP.setLogLevel(D) is called, where D >= 2.
*
* @return {!Log}
*/
export function dev() {
if (logs.dev) {
return logs.dev;
}
if (!logConstructor) {
throw new Error('failed to call initLogConstructor');
}
return (logs.dev = new logConstructor(self, (logNum) => {
if (logNum >= 3) {
return LogLevel.FINE;
}
if (logNum >= 2) {
return LogLevel.INFO;
}
return LogLevel.OFF;
}));
}
/**
* @param {!Window} win
* @param {!Element=} opt_element
* @return {boolean} isEmbed
*/
export function isFromEmbed(win, opt_element) {
if (!opt_element) {
return false;
}
return opt_element.ownerDocument.defaultView != win;
}
/**
* Throws an error if the first argument isn't trueish.
*
* Supports argument substitution into the message via %s placeholders.
*
* Throws an error object that has two extra properties:
* - associatedElement: This is the first element provided in the var args.
* It can be used for improved display of error messages.
* - messageArray: The elements of the substituted message as non-stringified
* elements in an array. When e.g. passed to console.error this yields
* native displays of things like HTML elements.
*
* @param {T} shouldBeTrueish The value to assert. The assert fails if it does
* not evaluate to true.
* @param {!Array|string=} opt_message The assertion message
* @param {*=} opt_1 Optional argument (Var arg as individual params for better
* @param {*=} opt_2 Optional argument inlining)
* @param {*=} opt_3 Optional argument
* @param {*=} opt_4 Optional argument
* @param {*=} opt_5 Optional argument
* @param {*=} opt_6 Optional argument
* @param {*=} opt_7 Optional argument
* @param {*=} opt_8 Optional argument
* @param {*=} opt_9 Optional argument
* @return {T} The value of shouldBeTrueish.
* @throws {!Error} When `shouldBeTrueish` is falsey.
* @template T
* @closurePrimitive {asserts.truthy}
*/
export function devAssert(
shouldBeTrueish,
opt_message,
opt_1,
opt_2,
opt_3,
opt_4,
opt_5,
opt_6,
opt_7,
opt_8,
opt_9
) {
if (getMode().minified) {
return shouldBeTrueish;
}
return dev()./*Orig call*/ assert(
shouldBeTrueish,
opt_message,
opt_1,
opt_2,
opt_3,
opt_4,
opt_5,
opt_6,
opt_7,
opt_8,
opt_9
);
}
/**
* Throws an error if the first argument isn't trueish.
*
* Supports argument substitution into the message via %s placeholders.
*
* Throws an error object that has two extra properties:
* - associatedElement: This is the first element provided in the var args.
* It can be used for improved display of error messages.
* - messageArray: The elements of the substituted message as non-stringified
* elements in an array. When e.g. passed to console.error this yields
* native displays of things like HTML elements.
*
* @param {T} shouldBeTrueish The value to assert. The assert fails if it does
* not evaluate to true.
* @param {!Array|string=} opt_message The assertion message
* @param {*=} opt_1 Optional argument (Var arg as individual params for better
* @param {*=} opt_2 Optional argument inlining)
* @param {*=} opt_3 Optional argument
* @param {*=} opt_4 Optional argument
* @param {*=} opt_5 Optional argument
* @param {*=} opt_6 Optional argument
* @param {*=} opt_7 Optional argument
* @param {*=} opt_8 Optional argument
* @param {*=} opt_9 Optional argument
* @return {T} The value of shouldBeTrueish.
* @throws {!Error} When `shouldBeTrueish` is falsey.
* @template T
* @closurePrimitive {asserts.truthy}
*/
export function userAssert(
shouldBeTrueish,
opt_message,
opt_1,
opt_2,
opt_3,
opt_4,
opt_5,
opt_6,
opt_7,
opt_8,
opt_9
) {
return user()./*Orig call*/ assert(
shouldBeTrueish,
opt_message,
opt_1,
opt_2,
opt_3,
opt_4,
opt_5,
opt_6,
opt_7,
opt_8,
opt_9
);
}