prebid-universal-creative 1.17.0 → 1.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3140 @@
1
+ /******/ (function(modules) { // webpackBootstrap
2
+ /******/ // The module cache
3
+ /******/ var installedModules = {};
4
+ /******/
5
+ /******/ // The require function
6
+ /******/ function __webpack_require__(moduleId) {
7
+ /******/
8
+ /******/ // Check if module is in cache
9
+ /******/ if(installedModules[moduleId]) {
10
+ /******/ return installedModules[moduleId].exports;
11
+ /******/ }
12
+ /******/ // Create a new module (and put it into the cache)
13
+ /******/ var module = installedModules[moduleId] = {
14
+ /******/ i: moduleId,
15
+ /******/ l: false,
16
+ /******/ exports: {}
17
+ /******/ };
18
+ /******/
19
+ /******/ // Execute the module function
20
+ /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
21
+ /******/
22
+ /******/ // Flag the module as loaded
23
+ /******/ module.l = true;
24
+ /******/
25
+ /******/ // Return the exports of the module
26
+ /******/ return module.exports;
27
+ /******/ }
28
+ /******/
29
+ /******/
30
+ /******/ // expose the modules object (__webpack_modules__)
31
+ /******/ __webpack_require__.m = modules;
32
+ /******/
33
+ /******/ // expose the module cache
34
+ /******/ __webpack_require__.c = installedModules;
35
+ /******/
36
+ /******/ // define getter function for harmony exports
37
+ /******/ __webpack_require__.d = function(exports, name, getter) {
38
+ /******/ if(!__webpack_require__.o(exports, name)) {
39
+ /******/ Object.defineProperty(exports, name, {
40
+ /******/ configurable: false,
41
+ /******/ enumerable: true,
42
+ /******/ get: getter
43
+ /******/ });
44
+ /******/ }
45
+ /******/ };
46
+ /******/
47
+ /******/ // getDefaultExport function for compatibility with non-harmony modules
48
+ /******/ __webpack_require__.n = function(module) {
49
+ /******/ var getter = module && module.__esModule ?
50
+ /******/ function getDefault() { return module['default']; } :
51
+ /******/ function getModuleExports() { return module; };
52
+ /******/ __webpack_require__.d(getter, 'a', getter);
53
+ /******/ return getter;
54
+ /******/ };
55
+ /******/
56
+ /******/ // Object.prototype.hasOwnProperty.call
57
+ /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
58
+ /******/
59
+ /******/ // __webpack_public_path__
60
+ /******/ __webpack_require__.p = "";
61
+ /******/
62
+ /******/ // Load entry module and return exports
63
+ /******/ return __webpack_require__(__webpack_require__.s = 4);
64
+ /******/ })
65
+ /************************************************************************/
66
+ /******/ ([
67
+ /* 0 */
68
+ /***/ (function(module, __webpack_exports__, __webpack_require__) {
69
+
70
+ "use strict";
71
+ /* harmony export (immutable) */ __webpack_exports__["i"] = triggerPixel;
72
+ /* harmony export (immutable) */ __webpack_exports__["a"] = createTrackPixelHtml;
73
+ /* harmony export (immutable) */ __webpack_exports__["j"] = writeAdUrl;
74
+ /* harmony export (immutable) */ __webpack_exports__["g"] = sendRequest;
75
+ /* harmony export (immutable) */ __webpack_exports__["d"] = getUUID;
76
+ /* harmony export (immutable) */ __webpack_exports__["e"] = loadScript;
77
+ /* harmony export (immutable) */ __webpack_exports__["b"] = getCreativeComment;
78
+ /* harmony export (immutable) */ __webpack_exports__["c"] = getCreativeCommentMarkup;
79
+ /* harmony export (immutable) */ __webpack_exports__["h"] = transformAuctionTargetingData;
80
+ /* harmony export (immutable) */ __webpack_exports__["f"] = parseUrl;
81
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__domHelper__ = __webpack_require__(1);
82
+
83
+
84
+ /**
85
+ * Inserts an image pixel with the specified `url` for cookie sync
86
+ * @param {string} url URL string of the image pixel to load
87
+ * @param {function} [done] an optional exit callback, used when this usersync pixel is added during an async process
88
+ */
89
+ function triggerPixel(url, done) {
90
+ var img = new Image();
91
+ if (done && typeof done === 'function') {
92
+ img.addEventListener('load', done);
93
+ img.addEventListener('error', done);
94
+ }
95
+ img.src = url;
96
+ }
97
+ function createTrackPixelHtml(url) {
98
+ if (!url) {
99
+ return '';
100
+ }
101
+ var escapedUrl = encodeURI(url);
102
+ var img = "<div style=\"position:absolute;left:0px;top:0px;visibility:hidden;\"><img src=\"".concat(escapedUrl, "\"></div>");
103
+ return img;
104
+ }
105
+ function writeAdUrl(adUrl, width, height) {
106
+ var iframe = __WEBPACK_IMPORTED_MODULE_0__domHelper__["a" /* getEmptyIframe */](height, width);
107
+ iframe.src = adUrl;
108
+ document.body.appendChild(iframe);
109
+ }
110
+ function sendRequest(url, callback) {
111
+ function reqListener() {
112
+ callback(oReq.responseText);
113
+ }
114
+ var oReq = new XMLHttpRequest();
115
+ oReq.addEventListener('load', reqListener);
116
+ oReq.open('GET', url);
117
+ oReq.send();
118
+ }
119
+ function getUUID() {
120
+ var d = new Date().getTime();
121
+ var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
122
+ var r = (d + Math.random() * 16) % 16 | 0;
123
+ d = Math.floor(d / 16);
124
+ return (c === 'x' ? r : r & 0x3 | 0x8).toString(16);
125
+ });
126
+ return uuid;
127
+ }
128
+ ;
129
+ function loadScript(currentWindow, tagSrc, successCallback, errorCallback) {
130
+ var doc = currentWindow.document;
131
+ var scriptTag = doc.createElement('script');
132
+ scriptTag.type = 'text/javascript';
133
+
134
+ // Execute success callback if necessary
135
+ if (successCallback && typeof successCallback === 'function') {
136
+ if (scriptTag.readyState) {
137
+ scriptTag.onreadystatechange = function () {
138
+ if (scriptTag.readyState === 'loaded' || scriptTag.readyState === 'complete') {
139
+ scriptTag.onreadystatechange = null;
140
+ successCallback();
141
+ }
142
+ };
143
+ } else {
144
+ scriptTag.onload = function () {
145
+ successCallback();
146
+ };
147
+ }
148
+ }
149
+
150
+ // Execute error callback if necessary
151
+ if (errorCallback && typeof errorCallback === 'function') {
152
+ scriptTag.onerror = function () {
153
+ errorCallback();
154
+ };
155
+ }
156
+ scriptTag.src = tagSrc;
157
+
158
+ //add the new script tag to the page
159
+ var elToAppend = doc.getElementsByTagName('head');
160
+ elToAppend = elToAppend.length ? elToAppend : doc.getElementsByTagName('body');
161
+ if (elToAppend.length) {
162
+ elToAppend = elToAppend[0];
163
+ elToAppend.insertBefore(scriptTag, elToAppend.firstChild);
164
+ }
165
+ return scriptTag;
166
+ }
167
+ ;
168
+
169
+ /**
170
+ * Return comment element
171
+ * @param {*} bid
172
+ */
173
+ function getCreativeComment(bid) {
174
+ return document.createComment("Creative ".concat(bid.crid, " served by Prebid.js Header Bidding"));
175
+ }
176
+
177
+ /**
178
+ * Returns comment element markup
179
+ * @param {*} bid
180
+ */
181
+ function getCreativeCommentMarkup(bid) {
182
+ var creativeComment = getCreativeComment(bid);
183
+ var wrapper = document.createElement('div');
184
+ wrapper.appendChild(creativeComment);
185
+ return wrapper.innerHTML;
186
+ }
187
+ function transformAuctionTargetingData(tagData) {
188
+ // this map object translates the Prebid.js auction keys to their equivalent Prebid Universal Creative keys
189
+ // when the publisher uses their adserver's generic macro that provides all targeting keys (ie tagData.targetingMap), we need to convert the keys
190
+ var auctionKeyMap = {
191
+ hb_adid: 'adId',
192
+ hb_cache_host: 'cacheHost',
193
+ hb_cache_path: 'cachePath',
194
+ hb_cache_id: 'uuid',
195
+ hb_format: 'mediaType',
196
+ hb_env: 'env',
197
+ hb_size: 'size',
198
+ hb_pb: 'hbPb'
199
+ };
200
+
201
+ /**
202
+ * Determine if the supplied property of the tagData object exists and is populated with its own values/properties according to its type
203
+ * @param {string} paramName name of the property to check (eg tagData.targetingMap)
204
+ * @returns true/false
205
+ */
206
+ function isMacroPresent(paramName) {
207
+ return !!(tagData[paramName] && (isPlainObject(tagData[paramName]) && Object.keys(tagData[paramName]).length > 0 || isStr(tagData[paramName]) && tagData[paramName] !== ''));
208
+ }
209
+
210
+ /**
211
+ * Converts the specifically formatted object of keypairs to a more generalized structure
212
+ * It specifically extracts the keyvalue from an array and stores it as a normal string
213
+ * @param {object} tarMap object of keys with the keyvalue stored in an array; eg {"hb_adid":["26566ee8c7f251"], ...}
214
+ * @returns {object} result is an object map like the following: {"hb_cache_id":"123456", "other_key":"other_value", ...}
215
+ */
216
+ function convertTargetingMapToNormalMap(tarMap) {
217
+ var newTarMap = {};
218
+ Object.keys(tarMap).forEach(function (key) {
219
+ if (Array.isArray(tarMap[key]) && tarMap[key].length > 0) {
220
+ newTarMap[key] = tarMap[key][0];
221
+ }
222
+ });
223
+ return newTarMap;
224
+ }
225
+
226
+ /**
227
+ * Converts a specifically formatted string of keypairs to a specifically formatted object map
228
+ * @param {String} keywordsStr string of keypairs; eg "hb_cache_id:123456,other_key:other_value"
229
+ * @returns {object} result is an object map like the following: {"hb_cache_id":"123456", "other_key":"other_value", ...}
230
+ */
231
+ function convertKeyPairStringToMap(keywordsStr) {
232
+ var keywordsMap = {};
233
+ var keywordsArr = keywordsStr.split(',');
234
+ if (keywordsArr.length > 0) {
235
+ keywordsArr.forEach(function (keyPairStr) {
236
+ var keyPairArr = keyPairStr.split(':');
237
+ if (keyPairArr.length === 2) {
238
+ var k = keyPairArr[0];
239
+ var v = keyPairArr[1];
240
+ keywordsMap[k] = v;
241
+ }
242
+ });
243
+ }
244
+ return keywordsMap;
245
+ }
246
+
247
+ /**
248
+ * Rename key if it's part of the auctionKeyMap object; if not, leave key as is
249
+ * Store the resultant keypair in the auctionData object for later use in renderingManager.renderAd()
250
+ * @param {object} adServerKeyMap incoming object map of the auction keys from the UC tag; eg {'key1':'value1', 'key2':'value2', ...}
251
+ */
252
+ function renameKnownAuctionKeys(adServerKeyMap) {
253
+ Object.keys(adServerKeyMap).forEach(function (key) {
254
+ var internalKey = auctionKeyMap[key] || key;
255
+ auctionData[internalKey] = adServerKeyMap[key];
256
+ });
257
+ }
258
+ var auctionData = {};
259
+ var formattedKeyMap = {};
260
+ if (isMacroPresent('targetingMap')) {
261
+ formattedKeyMap = convertTargetingMapToNormalMap(tagData.targetingMap);
262
+ } else if (isMacroPresent('targetingKeywords')) {
263
+ formattedKeyMap = convertKeyPairStringToMap(tagData.targetingKeywords);
264
+ }
265
+ renameKnownAuctionKeys(formattedKeyMap);
266
+
267
+ // set keys not in defined map macros (eg targetingMap) and/or the keys setup within a non-DFP adserver
268
+ Object.keys(tagData).forEach(function (key) {
269
+ if (key !== 'targetingMap' && key !== 'targetingKeywords' && isStr(tagData[key]) && tagData[key] !== '') {
270
+ auctionData[key] = tagData[key];
271
+ }
272
+ });
273
+ return auctionData;
274
+ }
275
+ function parseUrl(url) {
276
+ var parsed = document.createElement('a');
277
+ parsed.href = decodeURIComponent(url);
278
+ return {
279
+ href: parsed.href,
280
+ protocol: (parsed.protocol || '').replace(/:$/, ''),
281
+ hostname: parsed.hostname,
282
+ port: +parsed.port,
283
+ pathname: parsed.pathname.replace(/^(?!\/)/, '/'),
284
+ hash: (parsed.hash || '').replace(/^#/, ''),
285
+ host: (parsed.host || window.location.host).replace(/:(443|80)$/, '')
286
+ };
287
+ }
288
+ function isA(object, _t) {
289
+ return Object.prototype.toString.call(object) === '[object ' + _t + ']';
290
+ }
291
+ ;
292
+ function isPlainObject(object) {
293
+ return isA(object, 'Object');
294
+ }
295
+ function isStr(object) {
296
+ return isA(object, 'String');
297
+ }
298
+ ;
299
+
300
+ /***/ }),
301
+ /* 1 */
302
+ /***/ (function(module, __webpack_exports__, __webpack_require__) {
303
+
304
+ "use strict";
305
+ /* harmony export (immutable) */ __webpack_exports__["c"] = makeIframe;
306
+ /* harmony export (immutable) */ __webpack_exports__["a"] = getEmptyIframe;
307
+ /* harmony export (immutable) */ __webpack_exports__["b"] = insertElement;
308
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
309
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
310
+ function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
311
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
312
+ function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
313
+ /**
314
+ * domHelper: a collection of helpful dom things
315
+ */
316
+
317
+ /**
318
+ * returns a empty iframe element with specified attributes.
319
+ */
320
+ function makeIframe(doc) {
321
+ var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
322
+ var frame = doc.createElement('iframe');
323
+ Object.entries(_extends({
324
+ frameborder: 0,
325
+ scrolling: 'no',
326
+ marginheight: 0,
327
+ marginwidth: 0,
328
+ TOPMARGIN: 0,
329
+ LEFTMARGIN: 0,
330
+ allowtransparency: 'true'
331
+ }, attrs)).forEach(function (_ref) {
332
+ var _ref2 = _slicedToArray(_ref, 2),
333
+ attr = _ref2[0],
334
+ value = _ref2[1];
335
+ frame.setAttribute(attr, value);
336
+ });
337
+ return frame;
338
+ }
339
+
340
+ /**
341
+ * returns a empty iframe element with specified height/width
342
+ * @param {Number} height height iframe set to
343
+ * @param {Number} width width iframe set to
344
+ * @returns {Element} iframe DOM element
345
+ */
346
+ function getEmptyIframe(height, width) {
347
+ return makeIframe(document, {
348
+ height: height,
349
+ width: width
350
+ });
351
+ }
352
+
353
+ /**
354
+ * Insert element to passed target
355
+ * @param {object} elm
356
+ * @param {object} doc
357
+ * @param {string} target
358
+ */
359
+ function insertElement(elm, doc, target) {
360
+ doc = doc || document;
361
+ var elToAppend;
362
+ if (target) {
363
+ elToAppend = doc.getElementsByTagName(target);
364
+ } else {
365
+ elToAppend = doc.getElementsByTagName('head');
366
+ }
367
+ try {
368
+ elToAppend = elToAppend.length ? elToAppend : doc.getElementsByTagName('body');
369
+ if (elToAppend.length) {
370
+ elToAppend = elToAppend[0];
371
+ elToAppend.insertBefore(elm, elToAppend.firstChild);
372
+ }
373
+ } catch (e) {}
374
+ }
375
+
376
+ /***/ }),
377
+ /* 2 */
378
+ /***/ (function(module, __webpack_exports__, __webpack_require__) {
379
+
380
+ "use strict";
381
+ /* harmony export (immutable) */ __webpack_exports__["b"] = isAmp;
382
+ /* harmony export (immutable) */ __webpack_exports__["d"] = isSafeFrame;
383
+ /* unused harmony export isCrossDomain */
384
+ /* unused harmony export canInspectWindow */
385
+ /* harmony export (immutable) */ __webpack_exports__["a"] = canLocatePrebid;
386
+ /* harmony export (immutable) */ __webpack_exports__["c"] = isMobileApp;
387
+ /***************************************
388
+ * Detect Environment Helper Functions
389
+ ***************************************/
390
+
391
+ /**
392
+ * Functions to detect below environments:
393
+ * Amp: google Accelerate Mobile Pages ampproject.org
394
+ * SafeFrame: SafeFrame
395
+ * CrossDomain: An iframe that can't get to the top window
396
+ * Mobile App: function to detect mobile app environment
397
+ */
398
+
399
+ /**
400
+ * @param {String} uuid key value from auction, contains the cache id of the winning bid stored in prebid cache
401
+ * @returns true if there is an AMP context object
402
+ */
403
+ function isAmp(uuid, win) {
404
+ // TODO Use amp context once it is available in cross domain
405
+ // https://github.com/ampproject/amphtml/issues/6829
406
+ return typeof uuid === 'string' && uuid !== "" && isCrossDomain(win);
407
+ }
408
+
409
+ /**
410
+ * @returns true if the environment is a SafeFrame.
411
+ */
412
+ function isSafeFrame(win) {
413
+ return !!(win.$sf && win.$sf.ext);
414
+ }
415
+
416
+ /**
417
+ * Return true if we are in an iframe and can't access the top window.
418
+ * @returns true if the environment is a Cross Domain
419
+ */
420
+ function isCrossDomain(win) {
421
+ return win.top !== win && !canInspectWindow(win);
422
+ }
423
+
424
+ /**
425
+ * Returns true if win's properties can be accessed and win is defined.
426
+ * This functioned is used to determine if a window is cross-domained
427
+ * from the perspective of the current window.
428
+ * @param {!Window} win
429
+ * @return {boolean}
430
+ */
431
+ function canInspectWindow(win) {
432
+ try {
433
+ // force an exception in x-domain environments. #1509
434
+ win.top.location.toString();
435
+ return true;
436
+ } catch (e) {
437
+ return false;
438
+ }
439
+ }
440
+
441
+ /**
442
+ * Returns true if we can find the prebid global object (eg pbjs) as we
443
+ * climb the accessible windows. Return false if it's not found.
444
+ * @returns {boolean}
445
+ */
446
+ function canLocatePrebid(win) {
447
+ var result = false;
448
+ var currentWindow = win;
449
+ while (!result) {
450
+ try {
451
+ if (currentWindow.pbjs) {
452
+ result = true;
453
+ break;
454
+ }
455
+ } catch (e) {}
456
+ if (currentWindow === window.top) break;
457
+ currentWindow = currentWindow.parent;
458
+ }
459
+ return result;
460
+ }
461
+
462
+ /**
463
+ * @param {String} env key value from auction, indicates the environment where tag is served
464
+ * @returns true if env exists and is equal to the string 'mobile-app'
465
+ */
466
+ function isMobileApp(env) {
467
+ return env && env === 'mobile-app';
468
+ }
469
+
470
+ /***/ }),
471
+ /* 3 */
472
+ /***/ (function(module, __webpack_exports__, __webpack_require__) {
473
+
474
+ "use strict";
475
+ /* unused harmony export PREBID_EVENT */
476
+ /* unused harmony export AD_RENDER_SUCCEEDED */
477
+ /* unused harmony export AD_RENDER_FAILED */
478
+ /* harmony export (immutable) */ __webpack_exports__["a"] = prebidMessenger;
479
+ /* harmony export (immutable) */ __webpack_exports__["b"] = renderEventMessage;
480
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_js__ = __webpack_require__(0);
481
+ function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
482
+
483
+ var PREBID_EVENT = 'Prebid Event';
484
+ var AD_RENDER_SUCCEEDED = 'adRenderSucceeded';
485
+ var AD_RENDER_FAILED = 'adRenderFailed';
486
+ function prebidMessenger(publisherURL) {
487
+ var win = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window;
488
+ var prebidDomain = function () {
489
+ if (publisherURL == null) {
490
+ return null;
491
+ }
492
+ var parsedUrl = Object(__WEBPACK_IMPORTED_MODULE_0__utils_js__["f" /* parseUrl */])(publisherURL);
493
+ return parsedUrl.protocol + '://' + parsedUrl.host;
494
+ }();
495
+ function isPrebidWindow(win) {
496
+ return win && win.frames && win.frames.__pb_locator__;
497
+ }
498
+ var target = win.parent;
499
+ try {
500
+ while (target != null && target !== win.top && !isPrebidWindow(target)) {
501
+ target = target.parent;
502
+ }
503
+ if (!isPrebidWindow(target)) target = win.parent;
504
+ } catch (e) {}
505
+ return function sendMessage(message, onResponse) {
506
+ if (prebidDomain == null) {
507
+ throw new Error('Missing pubUrl');
508
+ }
509
+ message = JSON.stringify(message);
510
+ var messagePort;
511
+ if (onResponse == null) {
512
+ target.postMessage(message, prebidDomain);
513
+ } else {
514
+ var channel = new MessageChannel();
515
+ messagePort = channel.port1;
516
+ messagePort.onmessage = onResponse;
517
+ win.addEventListener('message', windowListener);
518
+ target.postMessage(message, prebidDomain, [channel.port2]);
519
+ }
520
+ return function stopListening() {
521
+ if (messagePort != null) {
522
+ win.removeEventListener('message', windowListener);
523
+ messagePort.onmessage = null;
524
+ messagePort = null;
525
+ }
526
+ };
527
+ function windowListener(ev) {
528
+ if ((ev.origin || ev.originalEvent && ev.originalEvent.origin) === prebidDomain) {
529
+ onResponse(ev);
530
+ }
531
+ }
532
+ };
533
+ }
534
+ function renderEventMessage(adId, errorInfo) {
535
+ return _extends({
536
+ adId: adId,
537
+ message: PREBID_EVENT,
538
+ event: errorInfo ? AD_RENDER_FAILED : AD_RENDER_SUCCEEDED
539
+ }, errorInfo ? {
540
+ info: errorInfo
541
+ } : null);
542
+ }
543
+
544
+ /***/ }),
545
+ /* 4 */
546
+ /***/ (function(module, __webpack_exports__, __webpack_require__) {
547
+
548
+ "use strict";
549
+ Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
550
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__(0);
551
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__renderingManager__ = __webpack_require__(5);
552
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__mobileAndAmpRender__ = __webpack_require__(7);
553
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__environment__ = __webpack_require__(2);
554
+ /**
555
+ * legacy.js
556
+ * This is deprecated code, publishers should not use one .js creative to handle all different types of creative.
557
+ * To reduce bytes transfered for each ad, publishers should use specific .js based on hb_format targeting key-value.
558
+ *
559
+ * This file is inserted into the prebid creative as a placeholder for the winning prebid creative. It should support the following formats:
560
+ * - Banner
561
+ * - AMP
562
+ * - Mobile
563
+ * - Outstream Video
564
+ * - All safeFrame creatives
565
+ */
566
+
567
+
568
+
569
+
570
+
571
+ window.ucTag = window.ucTag || {};
572
+ window.ucTag.renderAd = function (doc, dataObject) {
573
+ var targetingData = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["h" /* transformAuctionTargetingData */])(dataObject);
574
+ if (Object(__WEBPACK_IMPORTED_MODULE_3__environment__["c" /* isMobileApp */])(targetingData.env) || Object(__WEBPACK_IMPORTED_MODULE_3__environment__["b" /* isAmp */])(targetingData.uuid, window)) {
575
+ Object(__WEBPACK_IMPORTED_MODULE_2__mobileAndAmpRender__["a" /* renderAmpOrMobileAd */])(dataObject);
576
+ } else {
577
+ Object(__WEBPACK_IMPORTED_MODULE_1__renderingManager__["a" /* renderBannerOrDisplayAd */])(doc, dataObject);
578
+ }
579
+ };
580
+
581
+ /***/ }),
582
+ /* 5 */
583
+ /***/ (function(module, __webpack_exports__, __webpack_require__) {
584
+
585
+ "use strict";
586
+ /* harmony export (immutable) */ __webpack_exports__["a"] = renderBannerOrDisplayAd;
587
+ /* unused harmony export renderLegacy */
588
+ /* unused harmony export renderCrossDomain */
589
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__(0);
590
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__environment__ = __webpack_require__(2);
591
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__domHelper__ = __webpack_require__(1);
592
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__messaging_js__ = __webpack_require__(3);
593
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__dynamicRenderer_js__ = __webpack_require__(6);
594
+
595
+
596
+
597
+
598
+
599
+ function renderBannerOrDisplayAd(doc, dataObject) {
600
+ var targetingData = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["h" /* transformAuctionTargetingData */])(dataObject);
601
+ if (!Object(__WEBPACK_IMPORTED_MODULE_1__environment__["a" /* canLocatePrebid */])(window)) {
602
+ renderCrossDomain(window, targetingData.adId, targetingData.adServerDomain, targetingData.pubUrl);
603
+ } else {
604
+ renderLegacy(doc, targetingData.adId);
605
+ }
606
+ }
607
+
608
+ /**
609
+ * Calls prebid.js renderAd function to render ad
610
+ * @param {Object} doc Document
611
+ * @param {string} adId Id of creative to render
612
+ */
613
+ function renderLegacy(doc, adId) {
614
+ var found = false;
615
+ var w = window;
616
+ for (var i = 0; i < 10; i++) {
617
+ w = w.parent;
618
+ if (w.pbjs) {
619
+ try {
620
+ w.pbjs.renderAd(doc, adId);
621
+ found = true;
622
+ break;
623
+ } catch (e) {
624
+ continue;
625
+ }
626
+ }
627
+ }
628
+ if (!found) {
629
+ console.error("Unable to locate pbjs.renderAd function!");
630
+ }
631
+ }
632
+
633
+ /**
634
+ * Render ad in safeframe using postmessage
635
+ * @param {string} adId Id of creative to render
636
+ * @param {string} pubAdServerDomain publisher adserver domain name
637
+ * @param {string} pubUrl Url of publisher page
638
+ */
639
+ function renderCrossDomain(win, adId) {
640
+ var pubAdServerDomain = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
641
+ var pubUrl = arguments.length > 3 ? arguments[3] : undefined;
642
+ var windowLocation = win.location;
643
+ var adServerDomain = pubAdServerDomain || win.location.hostname;
644
+ var fullAdServerDomain = windowLocation.protocol + '//' + adServerDomain;
645
+ var sendMessage = Object(__WEBPACK_IMPORTED_MODULE_3__messaging_js__["a" /* prebidMessenger */])(pubUrl, win);
646
+ var signalRenderResult = function signalRenderResult(errorInfo) {
647
+ return sendMessage(Object(__WEBPACK_IMPORTED_MODULE_3__messaging_js__["b" /* renderEventMessage */])(adId, errorInfo));
648
+ };
649
+ function renderAd(ev) {
650
+ var key = ev.message ? "message" : "data";
651
+ var adObject = {};
652
+ try {
653
+ adObject = JSON.parse(ev[key]);
654
+ } catch (e) {
655
+ return;
656
+ }
657
+ if (adObject.message && adObject.message === "Prebid Response" && adObject.adId === adId) {
658
+ if (Object(__WEBPACK_IMPORTED_MODULE_4__dynamicRenderer_js__["a" /* hasDynamicRenderer */])(adObject)) {
659
+ Object(__WEBPACK_IMPORTED_MODULE_4__dynamicRenderer_js__["b" /* runDynamicRenderer */])(adId, adObject, sendMessage, win);
660
+ return;
661
+ }
662
+ try {
663
+ var body = win.document.body;
664
+ var ad = adObject.ad;
665
+ var url = adObject.adUrl;
666
+ var width = adObject.width;
667
+ var height = adObject.height;
668
+ if (adObject.mediaType === "video") {
669
+ signalRenderResult({
670
+ reason: "preventWritingOnMainDocument",
671
+ message: "Cannot render video ad ".concat(adId)
672
+ });
673
+ console.log("Error trying to write ad.");
674
+ } else if (ad) {
675
+ var iframe = Object(__WEBPACK_IMPORTED_MODULE_2__domHelper__["a" /* getEmptyIframe */])(adObject.height, adObject.width);
676
+ body.appendChild(iframe);
677
+ iframe.contentDocument.open();
678
+ iframe.contentDocument.write(ad);
679
+ iframe.contentDocument.close();
680
+ signalRenderResult();
681
+ } else if (url) {
682
+ var _iframe = Object(__WEBPACK_IMPORTED_MODULE_2__domHelper__["a" /* getEmptyIframe */])(height, width);
683
+ _iframe.style.display = "inline";
684
+ _iframe.style.overflow = "hidden";
685
+ _iframe.src = url;
686
+ Object(__WEBPACK_IMPORTED_MODULE_2__domHelper__["b" /* insertElement */])(_iframe, document, "body");
687
+ signalRenderResult();
688
+ } else {
689
+ signalRenderResult({
690
+ reason: "noAd",
691
+ message: "No ad for ".concat(adId)
692
+ });
693
+ console.log("Error trying to write ad. No ad markup or adUrl for ".concat(adId));
694
+ }
695
+ } catch (e) {
696
+ signalRenderResult({
697
+ reason: "exception",
698
+ message: e.message
699
+ });
700
+ console.log("Error in rendering ad", e);
701
+ }
702
+ }
703
+ }
704
+ function requestAdFromPrebid() {
705
+ var message = {
706
+ message: 'Prebid Request',
707
+ adId: adId,
708
+ adServerDomain: fullAdServerDomain
709
+ };
710
+ sendMessage(message, renderAd);
711
+ }
712
+ requestAdFromPrebid();
713
+ }
714
+
715
+ /***/ }),
716
+ /* 6 */
717
+ /***/ (function(module, __webpack_exports__, __webpack_require__) {
718
+
719
+ "use strict";
720
+ /* unused harmony export MIN_RENDERER_VERSION */
721
+ /* harmony export (immutable) */ __webpack_exports__["a"] = hasDynamicRenderer;
722
+ /* harmony export (immutable) */ __webpack_exports__["b"] = runDynamicRenderer;
723
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__domHelper_js__ = __webpack_require__(1);
724
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__messaging_js__ = __webpack_require__(3);
725
+ function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
726
+
727
+
728
+ var MIN_RENDERER_VERSION = 3;
729
+ function hasDynamicRenderer(message) {
730
+ return typeof message.renderer === 'string' && parseInt(message.rendererVersion, 10) >= MIN_RENDERER_VERSION;
731
+ }
732
+ function runDynamicRenderer(adId, data, _sendMessage) {
733
+ var win = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : window;
734
+ var mkFrame = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : __WEBPACK_IMPORTED_MODULE_0__domHelper_js__["c" /* makeIframe */];
735
+ var renderer = mkFrame(win.document, {
736
+ width: 0,
737
+ height: 0,
738
+ style: 'display: none',
739
+ srcdoc: "<script>".concat(data.renderer, "</script>"),
740
+ name: '__pb_renderer__'
741
+ });
742
+ return new Promise(function (resolve, reject) {
743
+ function onError() {
744
+ var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
745
+ _sendMessage(Object(__WEBPACK_IMPORTED_MODULE_1__messaging_js__["b" /* renderEventMessage */])(adId, {
746
+ reason: e.reason || 'exception',
747
+ message: e.message
748
+ }));
749
+ e.stack && console.error(e);
750
+ reject(e);
751
+ }
752
+ function guard(fn) {
753
+ return function () {
754
+ try {
755
+ return fn.apply(this, arguments);
756
+ } catch (e) {
757
+ onError(e);
758
+ }
759
+ };
760
+ }
761
+ renderer.onload = guard(function () {
762
+ var W = renderer.contentWindow;
763
+ // NOTE: on Firefox, `Promise.resolve(P)` or `new Promise((resolve) => resolve(P))`
764
+ // does not appear to work if P comes from another frame
765
+ W.Promise.resolve(W.render(data, {
766
+ mkFrame: mkFrame,
767
+ sendMessage: function sendMessage(type, payload, onResponse) {
768
+ return _sendMessage(_extends({
769
+ adId: adId,
770
+ message: type
771
+ }, payload), onResponse ? guard(onResponse) : undefined);
772
+ }
773
+ }, win)).then(function () {
774
+ return _sendMessage(Object(__WEBPACK_IMPORTED_MODULE_1__messaging_js__["b" /* renderEventMessage */])(adId));
775
+ }, onError).then(resolve);
776
+ });
777
+ win.document.body.appendChild(renderer);
778
+ });
779
+ }
780
+
781
+ /***/ }),
782
+ /* 7 */
783
+ /***/ (function(module, __webpack_exports__, __webpack_require__) {
784
+
785
+ "use strict";
786
+ /* harmony export (immutable) */ __webpack_exports__["a"] = renderAmpOrMobileAd;
787
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__(0);
788
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__environment__ = __webpack_require__(2);
789
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__domHelper__ = __webpack_require__(1);
790
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__postscribeRender__ = __webpack_require__(8);
791
+
792
+
793
+
794
+
795
+ var DEFAULT_CACHE_HOST = 'prebid.adnxs.com';
796
+ var DEFAULT_CACHE_PATH = '/pbc/v1/cache';
797
+
798
+ /**
799
+ * Render mobile or amp ad
800
+ * @param {string} cacheHost Cache host
801
+ * @param {string} cachePath Cache path
802
+ * @param {string} uuid id to render response from cache endpoint
803
+ * @param {string} size size of the creative
804
+ * @param {string} hbPb final price of the winning bid
805
+ * @param {Bool} isMobileApp flag to detect mobile app
806
+ */
807
+ function renderAmpOrMobileAd(dataObject) {
808
+ var targetingData = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["h" /* transformAuctionTargetingData */])(dataObject);
809
+ var cacheHost = targetingData.cacheHost,
810
+ cachePath = targetingData.cachePath,
811
+ uuid = targetingData.uuid,
812
+ size = targetingData.size,
813
+ hbPb = targetingData.hbPb;
814
+ uuid = uuid || '';
815
+ // For MoPub, creative is stored in localStorage via SDK.
816
+ var search = 'Prebid_';
817
+ if (uuid.substr(0, search.length) === search) {
818
+ loadFromLocalCache(uuid);
819
+ //register creative right away to not miss initial geom-update
820
+ updateIframe(size);
821
+ } else {
822
+ var adUrl = "".concat(getCacheEndpoint(cacheHost, cachePath), "?uuid=").concat(uuid);
823
+ //register creative right away to not miss initial geom-update
824
+ updateIframe(size);
825
+ Object(__WEBPACK_IMPORTED_MODULE_0__utils__["g" /* sendRequest */])(adUrl, responseCallback(Object(__WEBPACK_IMPORTED_MODULE_1__environment__["c" /* isMobileApp */])(targetingData.env), hbPb));
826
+ }
827
+ }
828
+
829
+ /**
830
+ * Load response from localStorage. In case of MoPub, sdk caches response
831
+ * @param {string} cacheId
832
+ */
833
+ function loadFromLocalCache(cacheId) {
834
+ var bid = window.localStorage.getItem(cacheId);
835
+ var displayFn = responseCallback(true);
836
+ displayFn(bid);
837
+ }
838
+
839
+ /**
840
+ * update iframe by using size string to resize
841
+ * @param {string} size
842
+ */
843
+ function updateIframe(size) {
844
+ if (size) {
845
+ var sizeArr = size.split('x').map(Number);
846
+ resizeIframe(sizeArr[0], sizeArr[1]);
847
+ } else {
848
+ console.log('Targeting key hb_size not found to resize creative');
849
+ }
850
+ }
851
+
852
+ /**
853
+ * Resize container iframe
854
+ * @param {Number} width width of creative
855
+ * @param {Number} height height of creative
856
+ */
857
+ function resizeIframe(width, height) {
858
+ var iframeWidth = window.innerWidth;
859
+ var iframeHeight = window.innerHeight;
860
+ if (iframeWidth !== width || iframeHeight !== height) {
861
+ if (Object(__WEBPACK_IMPORTED_MODULE_1__environment__["d" /* isSafeFrame */])(window)) {
862
+ var resize = function resize(status) {
863
+ var newWidth = width - iframeWidth;
864
+ var newHeight = height - iframeHeight;
865
+ window.$sf.ext.expand({
866
+ r: newWidth,
867
+ b: newHeight,
868
+ push: true
869
+ });
870
+ };
871
+ window.$sf.ext.register(width, height, resize);
872
+ }
873
+ // AMP resize request in case the parent is AMP
874
+ window.parent.postMessage({
875
+ sentinel: 'amp',
876
+ type: 'embed-size',
877
+ width: width,
878
+ height: height
879
+ }, '*');
880
+ }
881
+ }
882
+
883
+ /**
884
+ * Returns cache endpoint concatenated with cache path
885
+ * @param {string} cacheHost Cache Endpoint host
886
+ * @param {string} cachePath Cache Endpoint path
887
+ */
888
+ function getCacheEndpoint(cacheHost, cachePath) {
889
+ var host = typeof cacheHost === 'undefined' || cacheHost === "" ? DEFAULT_CACHE_HOST : cacheHost;
890
+ var path = typeof cachePath === 'undefined' || cachePath === "" ? DEFAULT_CACHE_PATH : cachePath;
891
+ return "https://".concat(host).concat(path);
892
+ }
893
+
894
+ /**
895
+ * Cache request Callback to display creative
896
+ * @param {Bool} isMobileApp
897
+ * @param {string} hbPb final price of the winning bid
898
+ * @returns {function} a callback function that parses response
899
+ */
900
+ function responseCallback(isMobileApp, hbPb) {
901
+ return function (response) {
902
+ var bidObject = parseResponse(response);
903
+ var auctionPrice = bidObject.price || hbPb;
904
+ var ad = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["c" /* getCreativeCommentMarkup */])(bidObject);
905
+ var width = bidObject.width ? bidObject.width : bidObject.w;
906
+ var height = bidObject.height ? bidObject.height : bidObject.h;
907
+
908
+ // When Prebid Universal Creative reads from Prebid Cache, we need to have it check for the existence of the wurl parameter. If it exists, hit it.
909
+ if (bidObject.wurl) {
910
+ Object(__WEBPACK_IMPORTED_MODULE_0__utils__["i" /* triggerPixel */])(decodeURIComponent(bidObject.wurl));
911
+ }
912
+ if (bidObject.adm) {
913
+ if (auctionPrice) {
914
+ // replace ${AUCTION_PRICE} macro with the bidObject.price or hb_pb.
915
+ bidObject.adm = bidObject.adm.replace('${AUCTION_PRICE}', auctionPrice);
916
+ } else {
917
+ /*
918
+ From OpenRTB spec 2.5: If the source value is an optional parameter that was not specified, the macro will simply be removed (i.e., replaced with a zero-length string).
919
+ */
920
+ bidObject.adm = bidObject.adm.replace('${AUCTION_PRICE}', '');
921
+ }
922
+ ad += isMobileApp ? constructMarkup(bidObject.adm, width, height) : bidObject.adm;
923
+ if (bidObject.nurl) {
924
+ ad += Object(__WEBPACK_IMPORTED_MODULE_0__utils__["a" /* createTrackPixelHtml */])(decodeURIComponent(bidObject.nurl));
925
+ }
926
+ if (bidObject.burl) {
927
+ var triggerBurl = function triggerBurl() {
928
+ Object(__WEBPACK_IMPORTED_MODULE_0__utils__["i" /* triggerPixel */])(bidObject.burl);
929
+ };
930
+ if (isMobileApp) {
931
+ var mraidScript = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["e" /* loadScript */])(window, 'mraid.js', function () {
932
+ // Success loading MRAID
933
+ var result = registerMRAIDViewableEvent(triggerBurl);
934
+ if (!result) {
935
+ triggerBurl(); // Error registering event
936
+ }
937
+ }, triggerBurl // Error loading MRAID
938
+ );
939
+ } else {
940
+ triggerBurl(); // Not a mobile app
941
+ }
942
+ }
943
+
944
+ Object(__WEBPACK_IMPORTED_MODULE_3__postscribeRender__["a" /* writeAdHtml */])(ad);
945
+ } else if (bidObject.nurl) {
946
+ if (isMobileApp) {
947
+ var adhtml = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["e" /* loadScript */])(window, bidObject.nurl);
948
+ ad += constructMarkup(adhtml.outerHTML, width, height);
949
+ Object(__WEBPACK_IMPORTED_MODULE_3__postscribeRender__["a" /* writeAdHtml */])(ad);
950
+ } else {
951
+ var nurl = bidObject.nurl;
952
+ var commentElm = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["b" /* getCreativeComment */])(bidObject);
953
+ Object(__WEBPACK_IMPORTED_MODULE_2__domHelper__["b" /* insertElement */])(commentElm, document, 'body');
954
+ Object(__WEBPACK_IMPORTED_MODULE_0__utils__["j" /* writeAdUrl */])(nurl, width, height);
955
+ }
956
+ }
957
+ };
958
+ }
959
+ ;
960
+
961
+ /**
962
+ * Parse response
963
+ * @param {string} response
964
+ * @returns {Object} bidObject parsed response
965
+ */
966
+ function parseResponse(response) {
967
+ var bidObject;
968
+ try {
969
+ bidObject = JSON.parse(response);
970
+ } catch (error) {
971
+ console.log("Error parsing response from cache host: ".concat(error));
972
+ }
973
+ return bidObject;
974
+ }
975
+
976
+ /**
977
+ * Wrap mobile app creative in div
978
+ * @param {string} ad html for creative
979
+ * @param {Number} width width of creative
980
+ * @param {Number} height height of creative
981
+ * @returns {string} creative markup
982
+ */
983
+ function constructMarkup(ad, width, height) {
984
+ var id = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["d" /* getUUID */])();
985
+ return "<div id=\"".concat(id, "\" style=\"border-style: none; position: absolute; width:100%; height:100%;\">\n <div id=\"").concat(id, "_inner\" style=\"margin: 0 auto; width:").concat(width, "px; height:").concat(height, "px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);\">").concat(ad, "</div>\n </div>");
986
+ }
987
+ function registerMRAIDViewableEvent(callback) {
988
+ function exposureChangeListener(exposure) {
989
+ if (exposure > 0) {
990
+ mraid.removeEventListener('exposureChange', exposureChangeListener);
991
+ callback();
992
+ }
993
+ }
994
+ function viewableChangeListener(viewable) {
995
+ if (viewable) {
996
+ mraid.removeEventListener('viewableChange', viewableChangeListener);
997
+ callback();
998
+ }
999
+ }
1000
+ function registerViewableChecks() {
1001
+ if (window.MRAID_ENV && parseFloat(window.MRAID_ENV.version) >= 3) {
1002
+ mraid.addEventListener('exposureChange', exposureChangeListener);
1003
+ } else if (window.MRAID_ENV && parseFloat(window.MRAID_ENV.version) < 3) {
1004
+ if (mraid.isViewable()) {
1005
+ callback();
1006
+ } else {
1007
+ mraid.addEventListener('viewableChange', viewableChangeListener);
1008
+ }
1009
+ }
1010
+ }
1011
+ function readyListener() {
1012
+ mraid.removeEventListener('ready', readyListener);
1013
+ registerViewableChecks();
1014
+ }
1015
+ if (window.mraid && window.MRAID_ENV) {
1016
+ if (mraid.getState() == 'loading') {
1017
+ mraid.addEventListener('ready', readyListener);
1018
+ } else {
1019
+ registerViewableChecks();
1020
+ }
1021
+ return true;
1022
+ } else {
1023
+ return false;
1024
+ }
1025
+ }
1026
+
1027
+ /***/ }),
1028
+ /* 8 */
1029
+ /***/ (function(module, __webpack_exports__, __webpack_require__) {
1030
+
1031
+ "use strict";
1032
+ /* harmony export (immutable) */ __webpack_exports__["a"] = writeAdHtml;
1033
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_postscribe__ = __webpack_require__(9);
1034
+ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_postscribe___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_postscribe__);
1035
+
1036
+ function writeAdHtml(markup) {
1037
+ var ps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : __WEBPACK_IMPORTED_MODULE_0_postscribe___default.a;
1038
+ // remove <?xml> and <!doctype> tags
1039
+ // https://github.com/prebid/prebid-universal-creative/issues/134
1040
+ markup = markup.replace(/\<(\?xml|(\!DOCTYPE[^\>\[]+(\[[^\]]+)?))+[^>]+\>/gi, '');
1041
+ ps(document.body, markup, {
1042
+ error: console.error
1043
+ });
1044
+ }
1045
+
1046
+ /***/ }),
1047
+ /* 9 */
1048
+ /***/ (function(module, exports, __webpack_require__) {
1049
+
1050
+ /**
1051
+ * @file postscribe
1052
+ * @description Asynchronously write javascript, even with document.write.
1053
+ * @version v2.0.8
1054
+ * @see {@link https://krux.github.io/postscribe}
1055
+ * @license MIT
1056
+ * @author Derek Brans
1057
+ * @copyright 2016 Krux Digital, Inc
1058
+ */
1059
+ (function webpackUniversalModuleDefinition(root, factory) {
1060
+ if(true)
1061
+ module.exports = factory();
1062
+ else if(typeof define === 'function' && define.amd)
1063
+ define([], factory);
1064
+ else if(typeof exports === 'object')
1065
+ exports["postscribe"] = factory();
1066
+ else
1067
+ root["postscribe"] = factory();
1068
+ })(this, function() {
1069
+ return /******/ (function(modules) { // webpackBootstrap
1070
+ /******/ // The module cache
1071
+ /******/ var installedModules = {};
1072
+ /******/
1073
+ /******/ // The require function
1074
+ /******/ function __webpack_require__(moduleId) {
1075
+ /******/
1076
+ /******/ // Check if module is in cache
1077
+ /******/ if(installedModules[moduleId])
1078
+ /******/ return installedModules[moduleId].exports;
1079
+ /******/
1080
+ /******/ // Create a new module (and put it into the cache)
1081
+ /******/ var module = installedModules[moduleId] = {
1082
+ /******/ exports: {},
1083
+ /******/ id: moduleId,
1084
+ /******/ loaded: false
1085
+ /******/ };
1086
+ /******/
1087
+ /******/ // Execute the module function
1088
+ /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
1089
+ /******/
1090
+ /******/ // Flag the module as loaded
1091
+ /******/ module.loaded = true;
1092
+ /******/
1093
+ /******/ // Return the exports of the module
1094
+ /******/ return module.exports;
1095
+ /******/ }
1096
+ /******/
1097
+ /******/
1098
+ /******/ // expose the modules object (__webpack_modules__)
1099
+ /******/ __webpack_require__.m = modules;
1100
+ /******/
1101
+ /******/ // expose the module cache
1102
+ /******/ __webpack_require__.c = installedModules;
1103
+ /******/
1104
+ /******/ // __webpack_public_path__
1105
+ /******/ __webpack_require__.p = "";
1106
+ /******/
1107
+ /******/ // Load entry module and return exports
1108
+ /******/ return __webpack_require__(0);
1109
+ /******/ })
1110
+ /************************************************************************/
1111
+ /******/ ([
1112
+ /* 0 */
1113
+ /***/ function(module, exports, __webpack_require__) {
1114
+
1115
+ 'use strict';
1116
+
1117
+ var _postscribe = __webpack_require__(1);
1118
+
1119
+ var _postscribe2 = _interopRequireDefault(_postscribe);
1120
+
1121
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
1122
+
1123
+ module.exports = _postscribe2['default'];
1124
+
1125
+ /***/ },
1126
+ /* 1 */
1127
+ /***/ function(module, exports, __webpack_require__) {
1128
+
1129
+ 'use strict';
1130
+
1131
+ exports.__esModule = true;
1132
+
1133
+ var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
1134
+
1135
+ exports['default'] = postscribe;
1136
+
1137
+ var _writeStream = __webpack_require__(2);
1138
+
1139
+ var _writeStream2 = _interopRequireDefault(_writeStream);
1140
+
1141
+ var _utils = __webpack_require__(4);
1142
+
1143
+ var utils = _interopRequireWildcard(_utils);
1144
+
1145
+ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
1146
+
1147
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
1148
+
1149
+ /**
1150
+ * A function that intentionally does nothing.
1151
+ */
1152
+ function doNothing() {}
1153
+
1154
+ /**
1155
+ * Available options and defaults.
1156
+ *
1157
+ * @type {Object}
1158
+ */
1159
+ var OPTIONS = {
1160
+ /**
1161
+ * Called when an async script has loaded.
1162
+ */
1163
+ afterAsync: doNothing,
1164
+
1165
+ /**
1166
+ * Called immediately before removing from the write queue.
1167
+ */
1168
+ afterDequeue: doNothing,
1169
+
1170
+ /**
1171
+ * Called sync after a stream's first thread release.
1172
+ */
1173
+ afterStreamStart: doNothing,
1174
+
1175
+ /**
1176
+ * Called after writing buffered document.write calls.
1177
+ */
1178
+ afterWrite: doNothing,
1179
+
1180
+ /**
1181
+ * Allows disabling the autoFix feature of prescribe
1182
+ */
1183
+ autoFix: true,
1184
+
1185
+ /**
1186
+ * Called immediately before adding to the write queue.
1187
+ */
1188
+ beforeEnqueue: doNothing,
1189
+
1190
+ /**
1191
+ * Called before writing a token.
1192
+ *
1193
+ * @param {Object} tok The token
1194
+ */
1195
+ beforeWriteToken: function beforeWriteToken(tok) {
1196
+ return tok;
1197
+ },
1198
+
1199
+ /**
1200
+ * Called before writing buffered document.write calls.
1201
+ *
1202
+ * @param {String} str The string
1203
+ */
1204
+ beforeWrite: function beforeWrite(str) {
1205
+ return str;
1206
+ },
1207
+
1208
+ /**
1209
+ * Called when evaluation is finished.
1210
+ */
1211
+ done: doNothing,
1212
+
1213
+ /**
1214
+ * Called when a write results in an error.
1215
+ *
1216
+ * @param {Error} e The error
1217
+ */
1218
+ error: function error(e) {
1219
+ throw new Error(e.msg);
1220
+ },
1221
+
1222
+
1223
+ /**
1224
+ * Whether to let scripts w/ async attribute set fall out of the queue.
1225
+ */
1226
+ releaseAsync: false
1227
+ };
1228
+
1229
+ var nextId = 0;
1230
+ var queue = [];
1231
+ var active = null;
1232
+
1233
+ function nextStream() {
1234
+ var args = queue.shift();
1235
+ if (args) {
1236
+ var options = utils.last(args);
1237
+
1238
+ options.afterDequeue();
1239
+ args.stream = runStream.apply(undefined, args);
1240
+ options.afterStreamStart();
1241
+ }
1242
+ }
1243
+
1244
+ function runStream(el, html, options) {
1245
+ active = new _writeStream2['default'](el, options);
1246
+
1247
+ // Identify this stream.
1248
+ active.id = nextId++;
1249
+ active.name = options.name || active.id;
1250
+ postscribe.streams[active.name] = active;
1251
+
1252
+ // Override document.write.
1253
+ var doc = el.ownerDocument;
1254
+
1255
+ var stash = {
1256
+ close: doc.close,
1257
+ open: doc.open,
1258
+ write: doc.write,
1259
+ writeln: doc.writeln
1260
+ };
1261
+
1262
+ function _write(str) {
1263
+ str = options.beforeWrite(str);
1264
+ active.write(str);
1265
+ options.afterWrite(str);
1266
+ }
1267
+
1268
+ _extends(doc, {
1269
+ close: doNothing,
1270
+ open: doNothing,
1271
+ write: function write() {
1272
+ for (var _len = arguments.length, str = Array(_len), _key = 0; _key < _len; _key++) {
1273
+ str[_key] = arguments[_key];
1274
+ }
1275
+
1276
+ return _write(str.join(''));
1277
+ },
1278
+ writeln: function writeln() {
1279
+ for (var _len2 = arguments.length, str = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
1280
+ str[_key2] = arguments[_key2];
1281
+ }
1282
+
1283
+ return _write(str.join('') + '\n');
1284
+ }
1285
+ });
1286
+
1287
+ // Override window.onerror
1288
+ var oldOnError = active.win.onerror || doNothing;
1289
+
1290
+ // This works together with the try/catch around WriteStream::insertScript
1291
+ // In modern browsers, exceptions in tag scripts go directly to top level
1292
+ active.win.onerror = function (msg, url, line) {
1293
+ options.error({ msg: msg + ' - ' + url + ': ' + line });
1294
+ oldOnError.apply(active.win, [msg, url, line]);
1295
+ };
1296
+
1297
+ // Write to the stream
1298
+ active.write(html, function () {
1299
+ // restore document.write
1300
+ _extends(doc, stash);
1301
+
1302
+ // restore window.onerror
1303
+ active.win.onerror = oldOnError;
1304
+
1305
+ options.done();
1306
+ active = null;
1307
+ nextStream();
1308
+ });
1309
+
1310
+ return active;
1311
+ }
1312
+
1313
+ function postscribe(el, html, options) {
1314
+ if (utils.isFunction(options)) {
1315
+ options = { done: options };
1316
+ } else if (options === 'clear') {
1317
+ queue = [];
1318
+ active = null;
1319
+ nextId = 0;
1320
+ return;
1321
+ }
1322
+
1323
+ options = utils.defaults(options, OPTIONS);
1324
+
1325
+ // id selector
1326
+ if (/^#/.test(el)) {
1327
+ el = window.document.getElementById(el.substr(1));
1328
+ } else {
1329
+ el = el.jquery ? el[0] : el;
1330
+ }
1331
+
1332
+ var args = [el, html, options];
1333
+
1334
+ el.postscribe = {
1335
+ cancel: function cancel() {
1336
+ if (args.stream) {
1337
+ args.stream.abort();
1338
+ } else {
1339
+ args[1] = doNothing;
1340
+ }
1341
+ }
1342
+ };
1343
+
1344
+ options.beforeEnqueue(args);
1345
+ queue.push(args);
1346
+
1347
+ if (!active) {
1348
+ nextStream();
1349
+ }
1350
+
1351
+ return el.postscribe;
1352
+ }
1353
+
1354
+ _extends(postscribe, {
1355
+ // Streams by name.
1356
+ streams: {},
1357
+ // Queue of streams.
1358
+ queue: queue,
1359
+ // Expose internal classes.
1360
+ WriteStream: _writeStream2['default']
1361
+ });
1362
+
1363
+ /***/ },
1364
+ /* 2 */
1365
+ /***/ function(module, exports, __webpack_require__) {
1366
+
1367
+ 'use strict';
1368
+
1369
+ exports.__esModule = true;
1370
+
1371
+ var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
1372
+
1373
+ var _prescribe = __webpack_require__(3);
1374
+
1375
+ var _prescribe2 = _interopRequireDefault(_prescribe);
1376
+
1377
+ var _utils = __webpack_require__(4);
1378
+
1379
+ var utils = _interopRequireWildcard(_utils);
1380
+
1381
+ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
1382
+
1383
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
1384
+
1385
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1386
+
1387
+ /**
1388
+ * Turn on to debug how each chunk affected the DOM.
1389
+ * @type {boolean}
1390
+ */
1391
+ var DEBUG_CHUNK = false;
1392
+
1393
+ /**
1394
+ * Prefix for data attributes on DOM elements.
1395
+ * @type {string}
1396
+ */
1397
+ var BASEATTR = 'data-ps-';
1398
+
1399
+ /**
1400
+ * ID for the style proxy
1401
+ * @type {string}
1402
+ */
1403
+ var PROXY_STYLE = 'ps-style';
1404
+
1405
+ /**
1406
+ * ID for the script proxy
1407
+ * @type {string}
1408
+ */
1409
+ var PROXY_SCRIPT = 'ps-script';
1410
+
1411
+ /**
1412
+ * Get data attributes
1413
+ *
1414
+ * @param {Object} el The DOM element.
1415
+ * @param {String} name The attribute name.
1416
+ * @returns {String}
1417
+ */
1418
+ function getData(el, name) {
1419
+ var attr = BASEATTR + name;
1420
+
1421
+ var val = el.getAttribute(attr);
1422
+
1423
+ // IE 8 returns a number if it's a number
1424
+ return !utils.existy(val) ? val : String(val);
1425
+ }
1426
+
1427
+ /**
1428
+ * Set data attributes
1429
+ *
1430
+ * @param {Object} el The DOM element.
1431
+ * @param {String} name The attribute name.
1432
+ * @param {null|*} value The attribute value.
1433
+ */
1434
+ function setData(el, name) {
1435
+ var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
1436
+
1437
+ var attr = BASEATTR + name;
1438
+
1439
+ if (utils.existy(value) && value !== '') {
1440
+ el.setAttribute(attr, value);
1441
+ } else {
1442
+ el.removeAttribute(attr);
1443
+ }
1444
+ }
1445
+
1446
+ /**
1447
+ * Stream static html to an element, where "static html" denotes "html
1448
+ * without scripts".
1449
+ *
1450
+ * This class maintains a *history of writes devoid of any attributes* or
1451
+ * "proxy history".
1452
+ *
1453
+ * Injecting the proxy history into a temporary div has no side-effects,
1454
+ * other than to create proxy elements for previously written elements.
1455
+ *
1456
+ * Given the `staticHtml` of a new write, a `tempDiv`'s innerHTML is set to
1457
+ * `proxy_history + staticHtml`.
1458
+ * The *structure* of `tempDiv`'s contents, (i.e., the placement of new nodes
1459
+ * beside or inside of proxy elements), reflects the DOM structure that would
1460
+ * have resulted if all writes had been squashed into a single write.
1461
+ *
1462
+ * For each descendent `node` of `tempDiv` whose parentNode is a *proxy*,
1463
+ * `node` is appended to the corresponding *real* element within the DOM.
1464
+ *
1465
+ * Proxy elements are mapped to *actual* elements in the DOM by injecting a
1466
+ * `data-id` attribute into each start tag in `staticHtml`.
1467
+ *
1468
+ */
1469
+
1470
+ var WriteStream = function () {
1471
+ /**
1472
+ * Constructor.
1473
+ *
1474
+ * @param {Object} root The root element
1475
+ * @param {?Object} options The options
1476
+ */
1477
+ function WriteStream(root) {
1478
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1479
+
1480
+ _classCallCheck(this, WriteStream);
1481
+
1482
+ this.root = root;
1483
+ this.options = options;
1484
+ this.doc = root.ownerDocument;
1485
+ this.win = this.doc.defaultView || this.doc.parentWindow;
1486
+ this.parser = new _prescribe2['default']('', { autoFix: options.autoFix });
1487
+
1488
+ // Actual elements by id.
1489
+ this.actuals = [root];
1490
+
1491
+ // Embodies the "structure" of what's been written so far,
1492
+ // devoid of attributes.
1493
+ this.proxyHistory = '';
1494
+
1495
+ // Create a proxy of the root element.
1496
+ this.proxyRoot = this.doc.createElement(root.nodeName);
1497
+
1498
+ this.scriptStack = [];
1499
+ this.writeQueue = [];
1500
+
1501
+ setData(this.proxyRoot, 'proxyof', 0);
1502
+ }
1503
+
1504
+ /**
1505
+ * Writes the given strings.
1506
+ *
1507
+ * @param {...String} str The strings to write
1508
+ */
1509
+
1510
+
1511
+ WriteStream.prototype.write = function write() {
1512
+ var _writeQueue;
1513
+
1514
+ (_writeQueue = this.writeQueue).push.apply(_writeQueue, arguments);
1515
+
1516
+ // Process writes
1517
+ // When new script gets pushed or pending this will stop
1518
+ // because new writeQueue gets pushed
1519
+ while (!this.deferredRemote && this.writeQueue.length) {
1520
+ var arg = this.writeQueue.shift();
1521
+
1522
+ if (utils.isFunction(arg)) {
1523
+ this._callFunction(arg);
1524
+ } else {
1525
+ this._writeImpl(arg);
1526
+ }
1527
+ }
1528
+ };
1529
+
1530
+ /**
1531
+ * Calls the given function.
1532
+ *
1533
+ * @param {Function} fn The function to call
1534
+ * @private
1535
+ */
1536
+
1537
+
1538
+ WriteStream.prototype._callFunction = function _callFunction(fn) {
1539
+ var tok = { type: 'function', value: fn.name || fn.toString() };
1540
+ this._onScriptStart(tok);
1541
+ fn.call(this.win, this.doc);
1542
+ this._onScriptDone(tok);
1543
+ };
1544
+
1545
+ /**
1546
+ * The write implementation
1547
+ *
1548
+ * @param {String} html The HTML to write.
1549
+ * @private
1550
+ */
1551
+
1552
+
1553
+ WriteStream.prototype._writeImpl = function _writeImpl(html) {
1554
+ this.parser.append(html);
1555
+
1556
+ var tok = void 0;
1557
+ var script = void 0;
1558
+ var style = void 0;
1559
+ var tokens = [];
1560
+
1561
+ // stop if we see a script token
1562
+ while ((tok = this.parser.readToken()) && !(script = utils.isScript(tok)) && !(style = utils.isStyle(tok))) {
1563
+ tok = this.options.beforeWriteToken(tok);
1564
+
1565
+ if (tok) {
1566
+ tokens.push(tok);
1567
+ }
1568
+ }
1569
+
1570
+ if (tokens.length > 0) {
1571
+ this._writeStaticTokens(tokens);
1572
+ }
1573
+
1574
+ if (script) {
1575
+ this._handleScriptToken(tok);
1576
+ }
1577
+
1578
+ if (style) {
1579
+ this._handleStyleToken(tok);
1580
+ }
1581
+ };
1582
+
1583
+ /**
1584
+ * Write contiguous non-script tokens (a chunk)
1585
+ *
1586
+ * @param {Array<Object>} tokens The tokens
1587
+ * @returns {{tokens, raw, actual, proxy}|null}
1588
+ * @private
1589
+ */
1590
+
1591
+
1592
+ WriteStream.prototype._writeStaticTokens = function _writeStaticTokens(tokens) {
1593
+ var chunk = this._buildChunk(tokens);
1594
+
1595
+ if (!chunk.actual) {
1596
+ // e.g., no tokens, or a noscript that got ignored
1597
+ return null;
1598
+ }
1599
+
1600
+ chunk.html = this.proxyHistory + chunk.actual;
1601
+ this.proxyHistory += chunk.proxy;
1602
+ this.proxyRoot.innerHTML = chunk.html;
1603
+
1604
+ if (DEBUG_CHUNK) {
1605
+ chunk.proxyInnerHTML = this.proxyRoot.innerHTML;
1606
+ }
1607
+
1608
+ this._walkChunk();
1609
+
1610
+ if (DEBUG_CHUNK) {
1611
+ chunk.actualInnerHTML = this.root.innerHTML;
1612
+ }
1613
+
1614
+ return chunk;
1615
+ };
1616
+
1617
+ /**
1618
+ * Build a chunk.
1619
+ *
1620
+ * @param {Array<Object>} tokens The tokens to use.
1621
+ * @returns {{tokens: *, raw: string, actual: string, proxy: string}}
1622
+ * @private
1623
+ */
1624
+
1625
+
1626
+ WriteStream.prototype._buildChunk = function _buildChunk(tokens) {
1627
+ var nextId = this.actuals.length;
1628
+
1629
+ // The raw html of this chunk.
1630
+ var raw = [];
1631
+
1632
+ // The html to create the nodes in the tokens (with id's injected).
1633
+ var actual = [];
1634
+
1635
+ // Html that can later be used to proxy the nodes in the tokens.
1636
+ var proxy = [];
1637
+
1638
+ var len = tokens.length;
1639
+ for (var i = 0; i < len; i++) {
1640
+ var tok = tokens[i];
1641
+ var tokenRaw = tok.toString();
1642
+
1643
+ raw.push(tokenRaw);
1644
+
1645
+ if (tok.attrs) {
1646
+ // tok.attrs <==> startTag or atomicTag or cursor
1647
+ // Ignore noscript tags. They are atomic, so we don't have to worry about children.
1648
+ if (!/^noscript$/i.test(tok.tagName)) {
1649
+ var id = nextId++;
1650
+
1651
+ // Actual: inject id attribute: replace '>' at end of start tag with id attribute + '>'
1652
+ actual.push(tokenRaw.replace(/(\/?>)/, ' ' + BASEATTR + 'id=' + id + ' $1'));
1653
+
1654
+ // Don't proxy scripts: they have no bearing on DOM structure.
1655
+ if (tok.attrs.id !== PROXY_SCRIPT && tok.attrs.id !== PROXY_STYLE) {
1656
+ // Proxy: strip all attributes and inject proxyof attribute
1657
+ proxy.push(
1658
+ // ignore atomic tags (e.g., style): they have no "structural" effect
1659
+ tok.type === 'atomicTag' ? '' : '<' + tok.tagName + ' ' + BASEATTR + 'proxyof=' + id + (tok.unary ? ' />' : '>'));
1660
+ }
1661
+ }
1662
+ } else {
1663
+ // Visit any other type of token
1664
+ // Actual: append.
1665
+ actual.push(tokenRaw);
1666
+
1667
+ // Proxy: append endTags. Ignore everything else.
1668
+ proxy.push(tok.type === 'endTag' ? tokenRaw : '');
1669
+ }
1670
+ }
1671
+
1672
+ return {
1673
+ tokens: tokens,
1674
+ raw: raw.join(''),
1675
+ actual: actual.join(''),
1676
+ proxy: proxy.join('')
1677
+ };
1678
+ };
1679
+
1680
+ /**
1681
+ * Walk the chunks.
1682
+ *
1683
+ * @private
1684
+ */
1685
+
1686
+
1687
+ WriteStream.prototype._walkChunk = function _walkChunk() {
1688
+ var node = void 0;
1689
+ var stack = [this.proxyRoot];
1690
+
1691
+ // use shift/unshift so that children are walked in document order
1692
+ while (utils.existy(node = stack.shift())) {
1693
+ var isElement = node.nodeType === 1;
1694
+ var isProxy = isElement && getData(node, 'proxyof');
1695
+
1696
+ // Ignore proxies
1697
+ if (!isProxy) {
1698
+ if (isElement) {
1699
+ // New actual element: register it and remove the the id attr.
1700
+ this.actuals[getData(node, 'id')] = node;
1701
+ setData(node, 'id');
1702
+ }
1703
+
1704
+ // Is node's parent a proxy?
1705
+ var parentIsProxyOf = node.parentNode && getData(node.parentNode, 'proxyof');
1706
+ if (parentIsProxyOf) {
1707
+ // Move node under actual parent.
1708
+ this.actuals[parentIsProxyOf].appendChild(node);
1709
+ }
1710
+ }
1711
+
1712
+ // prepend childNodes to stack
1713
+ stack.unshift.apply(stack, utils.toArray(node.childNodes));
1714
+ }
1715
+ };
1716
+
1717
+ /**
1718
+ * Handles Script tokens
1719
+ *
1720
+ * @param {Object} tok The token
1721
+ */
1722
+
1723
+
1724
+ WriteStream.prototype._handleScriptToken = function _handleScriptToken(tok) {
1725
+ var _this = this;
1726
+
1727
+ var remainder = this.parser.clear();
1728
+
1729
+ if (remainder) {
1730
+ // Write remainder immediately behind this script.
1731
+ this.writeQueue.unshift(remainder);
1732
+ }
1733
+
1734
+ tok.src = tok.attrs.src || tok.attrs.SRC;
1735
+
1736
+ tok = this.options.beforeWriteToken(tok);
1737
+ if (!tok) {
1738
+ // User has removed this token
1739
+ return;
1740
+ }
1741
+
1742
+ if (tok.src && this.scriptStack.length) {
1743
+ // Defer this script until scriptStack is empty.
1744
+ // Assumption 1: This script will not start executing until
1745
+ // scriptStack is empty.
1746
+ this.deferredRemote = tok;
1747
+ } else {
1748
+ this._onScriptStart(tok);
1749
+ }
1750
+
1751
+ // Put the script node in the DOM.
1752
+ this._writeScriptToken(tok, function () {
1753
+ _this._onScriptDone(tok);
1754
+ });
1755
+ };
1756
+
1757
+ /**
1758
+ * Handles style tokens
1759
+ *
1760
+ * @param {Object} tok The token
1761
+ */
1762
+
1763
+
1764
+ WriteStream.prototype._handleStyleToken = function _handleStyleToken(tok) {
1765
+ var remainder = this.parser.clear();
1766
+
1767
+ if (remainder) {
1768
+ // Write remainder immediately behind this style.
1769
+ this.writeQueue.unshift(remainder);
1770
+ }
1771
+
1772
+ tok.type = tok.attrs.type || tok.attrs.TYPE || 'text/css';
1773
+
1774
+ tok = this.options.beforeWriteToken(tok);
1775
+
1776
+ if (tok) {
1777
+ // Put the style node in the DOM.
1778
+ this._writeStyleToken(tok);
1779
+ }
1780
+
1781
+ if (remainder) {
1782
+ this.write();
1783
+ }
1784
+ };
1785
+
1786
+ /**
1787
+ * Build a style and insert it into the DOM.
1788
+ *
1789
+ * @param {Object} tok The token
1790
+ */
1791
+
1792
+
1793
+ WriteStream.prototype._writeStyleToken = function _writeStyleToken(tok) {
1794
+ var el = this._buildStyle(tok);
1795
+
1796
+ this._insertCursor(el, PROXY_STYLE);
1797
+
1798
+ // Set content
1799
+ if (tok.content) {
1800
+ if (el.styleSheet && !el.sheet) {
1801
+ el.styleSheet.cssText = tok.content;
1802
+ } else {
1803
+ el.appendChild(this.doc.createTextNode(tok.content));
1804
+ }
1805
+ }
1806
+ };
1807
+
1808
+ /**
1809
+ * Build a style element from an atomic style token.
1810
+ *
1811
+ * @param {Object} tok The token
1812
+ * @returns {Element}
1813
+ */
1814
+
1815
+
1816
+ WriteStream.prototype._buildStyle = function _buildStyle(tok) {
1817
+ var el = this.doc.createElement(tok.tagName);
1818
+
1819
+ el.setAttribute('type', tok.type);
1820
+
1821
+ // Set attributes
1822
+ utils.eachKey(tok.attrs, function (name, value) {
1823
+ el.setAttribute(name, value);
1824
+ });
1825
+
1826
+ return el;
1827
+ };
1828
+
1829
+ /**
1830
+ * Append a span to the stream. That span will act as a cursor
1831
+ * (i.e. insertion point) for the element.
1832
+ *
1833
+ * @param {Object} el The element
1834
+ * @param {string} which The type of proxy element
1835
+ */
1836
+
1837
+
1838
+ WriteStream.prototype._insertCursor = function _insertCursor(el, which) {
1839
+ this._writeImpl('<span id="' + which + '"/>');
1840
+
1841
+ var cursor = this.doc.getElementById(which);
1842
+
1843
+ if (cursor) {
1844
+ cursor.parentNode.replaceChild(el, cursor);
1845
+ }
1846
+ };
1847
+
1848
+ /**
1849
+ * Called when a script is started.
1850
+ *
1851
+ * @param {Object} tok The token
1852
+ * @private
1853
+ */
1854
+
1855
+
1856
+ WriteStream.prototype._onScriptStart = function _onScriptStart(tok) {
1857
+ tok.outerWrites = this.writeQueue;
1858
+ this.writeQueue = [];
1859
+ this.scriptStack.unshift(tok);
1860
+ };
1861
+
1862
+ /**
1863
+ * Called when a script is done.
1864
+ *
1865
+ * @param {Object} tok The token
1866
+ * @private
1867
+ */
1868
+
1869
+
1870
+ WriteStream.prototype._onScriptDone = function _onScriptDone(tok) {
1871
+ // Pop script and check nesting.
1872
+ if (tok !== this.scriptStack[0]) {
1873
+ this.options.error({ msg: 'Bad script nesting or script finished twice' });
1874
+ return;
1875
+ }
1876
+
1877
+ this.scriptStack.shift();
1878
+
1879
+ // Append outer writes to queue and process them.
1880
+ this.write.apply(this, tok.outerWrites);
1881
+
1882
+ // Check for pending remote
1883
+
1884
+ // Assumption 2: if remote_script1 writes remote_script2 then
1885
+ // the we notice remote_script1 finishes before remote_script2 starts.
1886
+ // I think this is equivalent to assumption 1
1887
+ if (!this.scriptStack.length && this.deferredRemote) {
1888
+ this._onScriptStart(this.deferredRemote);
1889
+ this.deferredRemote = null;
1890
+ }
1891
+ };
1892
+
1893
+ /**
1894
+ * Build a script and insert it into the DOM.
1895
+ * Done is called once script has executed.
1896
+ *
1897
+ * @param {Object} tok The token
1898
+ * @param {Function} done The callback when complete
1899
+ */
1900
+
1901
+
1902
+ WriteStream.prototype._writeScriptToken = function _writeScriptToken(tok, done) {
1903
+ var el = this._buildScript(tok);
1904
+ var asyncRelease = this._shouldRelease(el);
1905
+ var afterAsync = this.options.afterAsync;
1906
+
1907
+ if (tok.src) {
1908
+ // Fix for attribute "SRC" (capitalized). IE does not recognize it.
1909
+ el.src = tok.src;
1910
+ this._scriptLoadHandler(el, !asyncRelease ? function () {
1911
+ done();
1912
+ afterAsync();
1913
+ } : afterAsync);
1914
+ }
1915
+
1916
+ try {
1917
+ this._insertCursor(el, PROXY_SCRIPT);
1918
+ if (!el.src || asyncRelease) {
1919
+ done();
1920
+ }
1921
+ } catch (e) {
1922
+ this.options.error(e);
1923
+ done();
1924
+ }
1925
+ };
1926
+
1927
+ /**
1928
+ * Build a script element from an atomic script token.
1929
+ *
1930
+ * @param {Object} tok The token
1931
+ * @returns {Element}
1932
+ */
1933
+
1934
+
1935
+ WriteStream.prototype._buildScript = function _buildScript(tok) {
1936
+ var el = this.doc.createElement(tok.tagName);
1937
+
1938
+ // Set attributes
1939
+ utils.eachKey(tok.attrs, function (name, value) {
1940
+ el.setAttribute(name, value);
1941
+ });
1942
+
1943
+ // Set content
1944
+ if (tok.content) {
1945
+ el.text = tok.content;
1946
+ }
1947
+
1948
+ return el;
1949
+ };
1950
+
1951
+ /**
1952
+ * Setup the script load handler on an element.
1953
+ *
1954
+ * @param {Object} el The element
1955
+ * @param {Function} done The callback
1956
+ * @private
1957
+ */
1958
+
1959
+
1960
+ WriteStream.prototype._scriptLoadHandler = function _scriptLoadHandler(el, done) {
1961
+ function cleanup() {
1962
+ el = el.onload = el.onreadystatechange = el.onerror = null;
1963
+ }
1964
+
1965
+ var error = this.options.error;
1966
+
1967
+ function success() {
1968
+ cleanup();
1969
+ if (done != null) {
1970
+ done();
1971
+ }
1972
+ done = null;
1973
+ }
1974
+
1975
+ function failure(err) {
1976
+ cleanup();
1977
+ error(err);
1978
+ if (done != null) {
1979
+ done();
1980
+ }
1981
+ done = null;
1982
+ }
1983
+
1984
+ function reattachEventListener(el, evt) {
1985
+ var handler = el['on' + evt];
1986
+ if (handler != null) {
1987
+ el['_on' + evt] = handler;
1988
+ }
1989
+ }
1990
+
1991
+ reattachEventListener(el, 'load');
1992
+ reattachEventListener(el, 'error');
1993
+
1994
+ _extends(el, {
1995
+ onload: function onload() {
1996
+ if (el._onload) {
1997
+ try {
1998
+ el._onload.apply(this, Array.prototype.slice.call(arguments, 0));
1999
+ } catch (err) {
2000
+ failure({ msg: 'onload handler failed ' + err + ' @ ' + el.src });
2001
+ }
2002
+ }
2003
+ success();
2004
+ },
2005
+ onerror: function onerror() {
2006
+ if (el._onerror) {
2007
+ try {
2008
+ el._onerror.apply(this, Array.prototype.slice.call(arguments, 0));
2009
+ } catch (err) {
2010
+ failure({ msg: 'onerror handler failed ' + err + ' @ ' + el.src });
2011
+ return;
2012
+ }
2013
+ }
2014
+ failure({ msg: 'remote script failed ' + el.src });
2015
+ },
2016
+ onreadystatechange: function onreadystatechange() {
2017
+ if (/^(loaded|complete)$/.test(el.readyState)) {
2018
+ success();
2019
+ }
2020
+ }
2021
+ });
2022
+ };
2023
+
2024
+ /**
2025
+ * Determines whether to release.
2026
+ *
2027
+ * @param {Object} el The element
2028
+ * @returns {boolean}
2029
+ * @private
2030
+ */
2031
+
2032
+
2033
+ WriteStream.prototype._shouldRelease = function _shouldRelease(el) {
2034
+ var isScript = /^script$/i.test(el.nodeName);
2035
+ return !isScript || !!(this.options.releaseAsync && el.src && el.hasAttribute('async'));
2036
+ };
2037
+
2038
+ return WriteStream;
2039
+ }();
2040
+
2041
+ exports['default'] = WriteStream;
2042
+
2043
+ /***/ },
2044
+ /* 3 */
2045
+ /***/ function(module, exports, __webpack_require__) {
2046
+
2047
+ /**
2048
+ * @file prescribe
2049
+ * @description Tiny, forgiving HTML parser
2050
+ * @version vundefined
2051
+ * @see {@link https://github.com/krux/prescribe/}
2052
+ * @license MIT
2053
+ * @author Derek Brans
2054
+ * @copyright 2016 Krux Digital, Inc
2055
+ */
2056
+ (function webpackUniversalModuleDefinition(root, factory) {
2057
+ if(true)
2058
+ module.exports = factory();
2059
+ else if(typeof define === 'function' && define.amd)
2060
+ define([], factory);
2061
+ else if(typeof exports === 'object')
2062
+ exports["Prescribe"] = factory();
2063
+ else
2064
+ root["Prescribe"] = factory();
2065
+ })(this, function() {
2066
+ return /******/ (function(modules) { // webpackBootstrap
2067
+ /******/ // The module cache
2068
+ /******/ var installedModules = {};
2069
+
2070
+ /******/ // The require function
2071
+ /******/ function __webpack_require__(moduleId) {
2072
+
2073
+ /******/ // Check if module is in cache
2074
+ /******/ if(installedModules[moduleId])
2075
+ /******/ return installedModules[moduleId].exports;
2076
+
2077
+ /******/ // Create a new module (and put it into the cache)
2078
+ /******/ var module = installedModules[moduleId] = {
2079
+ /******/ exports: {},
2080
+ /******/ id: moduleId,
2081
+ /******/ loaded: false
2082
+ /******/ };
2083
+
2084
+ /******/ // Execute the module function
2085
+ /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
2086
+
2087
+ /******/ // Flag the module as loaded
2088
+ /******/ module.loaded = true;
2089
+
2090
+ /******/ // Return the exports of the module
2091
+ /******/ return module.exports;
2092
+ /******/ }
2093
+
2094
+
2095
+ /******/ // expose the modules object (__webpack_modules__)
2096
+ /******/ __webpack_require__.m = modules;
2097
+
2098
+ /******/ // expose the module cache
2099
+ /******/ __webpack_require__.c = installedModules;
2100
+
2101
+ /******/ // __webpack_public_path__
2102
+ /******/ __webpack_require__.p = "";
2103
+
2104
+ /******/ // Load entry module and return exports
2105
+ /******/ return __webpack_require__(0);
2106
+ /******/ })
2107
+ /************************************************************************/
2108
+ /******/ ([
2109
+ /* 0 */
2110
+ /***/ function(module, exports, __webpack_require__) {
2111
+
2112
+ 'use strict';
2113
+
2114
+ var _HtmlParser = __webpack_require__(1);
2115
+
2116
+ var _HtmlParser2 = _interopRequireDefault(_HtmlParser);
2117
+
2118
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
2119
+
2120
+ module.exports = _HtmlParser2['default'];
2121
+
2122
+ /***/ },
2123
+ /* 1 */
2124
+ /***/ function(module, exports, __webpack_require__) {
2125
+
2126
+ 'use strict';
2127
+
2128
+ exports.__esModule = true;
2129
+
2130
+ var _supports = __webpack_require__(2);
2131
+
2132
+ var supports = _interopRequireWildcard(_supports);
2133
+
2134
+ var _streamReaders = __webpack_require__(3);
2135
+
2136
+ var streamReaders = _interopRequireWildcard(_streamReaders);
2137
+
2138
+ var _fixedReadTokenFactory = __webpack_require__(6);
2139
+
2140
+ var _fixedReadTokenFactory2 = _interopRequireDefault(_fixedReadTokenFactory);
2141
+
2142
+ var _utils = __webpack_require__(5);
2143
+
2144
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
2145
+
2146
+ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
2147
+
2148
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2149
+
2150
+ /**
2151
+ * Detection regular expressions.
2152
+ *
2153
+ * Order of detection matters: detection of one can only
2154
+ * succeed if detection of previous didn't
2155
+
2156
+ * @type {Object}
2157
+ */
2158
+ var detect = {
2159
+ comment: /^<!--/,
2160
+ endTag: /^<\//,
2161
+ atomicTag: /^<\s*(script|style|noscript|iframe|textarea)[\s\/>]/i,
2162
+ startTag: /^</,
2163
+ chars: /^[^<]/
2164
+ };
2165
+
2166
+ /**
2167
+ * HtmlParser provides the capability to parse HTML and return tokens
2168
+ * representing the tags and content.
2169
+ */
2170
+
2171
+ var HtmlParser = function () {
2172
+ /**
2173
+ * Constructor.
2174
+ *
2175
+ * @param {string} stream The initial parse stream contents.
2176
+ * @param {Object} options The options
2177
+ * @param {boolean} options.autoFix Set to true to automatically fix errors
2178
+ */
2179
+ function HtmlParser() {
2180
+ var _this = this;
2181
+
2182
+ var stream = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
2183
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2184
+
2185
+ _classCallCheck(this, HtmlParser);
2186
+
2187
+ this.stream = stream;
2188
+
2189
+ var fix = false;
2190
+ var fixedTokenOptions = {};
2191
+
2192
+ for (var key in supports) {
2193
+ if (supports.hasOwnProperty(key)) {
2194
+ if (options.autoFix) {
2195
+ fixedTokenOptions[key + 'Fix'] = true; // !supports[key];
2196
+ }
2197
+ fix = fix || fixedTokenOptions[key + 'Fix'];
2198
+ }
2199
+ }
2200
+
2201
+ if (fix) {
2202
+ this._readToken = (0, _fixedReadTokenFactory2['default'])(this, fixedTokenOptions, function () {
2203
+ return _this._readTokenImpl();
2204
+ });
2205
+ this._peekToken = (0, _fixedReadTokenFactory2['default'])(this, fixedTokenOptions, function () {
2206
+ return _this._peekTokenImpl();
2207
+ });
2208
+ } else {
2209
+ this._readToken = this._readTokenImpl;
2210
+ this._peekToken = this._peekTokenImpl;
2211
+ }
2212
+ }
2213
+
2214
+ /**
2215
+ * Appends the given string to the parse stream.
2216
+ *
2217
+ * @param {string} str The string to append
2218
+ */
2219
+
2220
+
2221
+ HtmlParser.prototype.append = function append(str) {
2222
+ this.stream += str;
2223
+ };
2224
+
2225
+ /**
2226
+ * Prepends the given string to the parse stream.
2227
+ *
2228
+ * @param {string} str The string to prepend
2229
+ */
2230
+
2231
+
2232
+ HtmlParser.prototype.prepend = function prepend(str) {
2233
+ this.stream = str + this.stream;
2234
+ };
2235
+
2236
+ /**
2237
+ * The implementation of the token reading.
2238
+ *
2239
+ * @private
2240
+ * @returns {?Token}
2241
+ */
2242
+
2243
+
2244
+ HtmlParser.prototype._readTokenImpl = function _readTokenImpl() {
2245
+ var token = this._peekTokenImpl();
2246
+ if (token) {
2247
+ this.stream = this.stream.slice(token.length);
2248
+ return token;
2249
+ }
2250
+ };
2251
+
2252
+ /**
2253
+ * The implementation of token peeking.
2254
+ *
2255
+ * @returns {?Token}
2256
+ */
2257
+
2258
+
2259
+ HtmlParser.prototype._peekTokenImpl = function _peekTokenImpl() {
2260
+ for (var type in detect) {
2261
+ if (detect.hasOwnProperty(type)) {
2262
+ if (detect[type].test(this.stream)) {
2263
+ var token = streamReaders[type](this.stream);
2264
+
2265
+ if (token) {
2266
+ if (token.type === 'startTag' && /script|style/i.test(token.tagName)) {
2267
+ return null;
2268
+ } else {
2269
+ token.text = this.stream.substr(0, token.length);
2270
+ return token;
2271
+ }
2272
+ }
2273
+ }
2274
+ }
2275
+ }
2276
+ };
2277
+
2278
+ /**
2279
+ * The public token peeking interface. Delegates to the basic token peeking
2280
+ * or a version that performs fixups depending on the `autoFix` setting in
2281
+ * options.
2282
+ *
2283
+ * @returns {object}
2284
+ */
2285
+
2286
+
2287
+ HtmlParser.prototype.peekToken = function peekToken() {
2288
+ return this._peekToken();
2289
+ };
2290
+
2291
+ /**
2292
+ * The public token reading interface. Delegates to the basic token reading
2293
+ * or a version that performs fixups depending on the `autoFix` setting in
2294
+ * options.
2295
+ *
2296
+ * @returns {object}
2297
+ */
2298
+
2299
+
2300
+ HtmlParser.prototype.readToken = function readToken() {
2301
+ return this._readToken();
2302
+ };
2303
+
2304
+ /**
2305
+ * Read tokens and hand to the given handlers.
2306
+ *
2307
+ * @param {Object} handlers The handlers to use for the different tokens.
2308
+ */
2309
+
2310
+
2311
+ HtmlParser.prototype.readTokens = function readTokens(handlers) {
2312
+ var tok = void 0;
2313
+ while (tok = this.readToken()) {
2314
+ // continue until we get an explicit "false" return
2315
+ if (handlers[tok.type] && handlers[tok.type](tok) === false) {
2316
+ return;
2317
+ }
2318
+ }
2319
+ };
2320
+
2321
+ /**
2322
+ * Clears the parse stream.
2323
+ *
2324
+ * @returns {string} The contents of the parse stream before clearing.
2325
+ */
2326
+
2327
+
2328
+ HtmlParser.prototype.clear = function clear() {
2329
+ var rest = this.stream;
2330
+ this.stream = '';
2331
+ return rest;
2332
+ };
2333
+
2334
+ /**
2335
+ * Returns the rest of the parse stream.
2336
+ *
2337
+ * @returns {string} The contents of the parse stream.
2338
+ */
2339
+
2340
+
2341
+ HtmlParser.prototype.rest = function rest() {
2342
+ return this.stream;
2343
+ };
2344
+
2345
+ return HtmlParser;
2346
+ }();
2347
+
2348
+ exports['default'] = HtmlParser;
2349
+
2350
+
2351
+ HtmlParser.tokenToString = function (tok) {
2352
+ return tok.toString();
2353
+ };
2354
+
2355
+ HtmlParser.escapeAttributes = function (attrs) {
2356
+ var escapedAttrs = {};
2357
+
2358
+ for (var name in attrs) {
2359
+ if (attrs.hasOwnProperty(name)) {
2360
+ escapedAttrs[name] = (0, _utils.escapeQuotes)(attrs[name], null);
2361
+ }
2362
+ }
2363
+
2364
+ return escapedAttrs;
2365
+ };
2366
+
2367
+ HtmlParser.supports = supports;
2368
+
2369
+ for (var key in supports) {
2370
+ if (supports.hasOwnProperty(key)) {
2371
+ HtmlParser.browserHasFlaw = HtmlParser.browserHasFlaw || !supports[key] && key;
2372
+ }
2373
+ }
2374
+
2375
+ /***/ },
2376
+ /* 2 */
2377
+ /***/ function(module, exports) {
2378
+
2379
+ 'use strict';
2380
+
2381
+ exports.__esModule = true;
2382
+ var tagSoup = false;
2383
+ var selfClose = false;
2384
+
2385
+ var work = window.document.createElement('div');
2386
+
2387
+ try {
2388
+ var html = '<P><I></P></I>';
2389
+ work.innerHTML = html;
2390
+ exports.tagSoup = tagSoup = work.innerHTML !== html;
2391
+ } catch (e) {
2392
+ exports.tagSoup = tagSoup = false;
2393
+ }
2394
+
2395
+ try {
2396
+ work.innerHTML = '<P><i><P></P></i></P>';
2397
+ exports.selfClose = selfClose = work.childNodes.length === 2;
2398
+ } catch (e) {
2399
+ exports.selfClose = selfClose = false;
2400
+ }
2401
+
2402
+ work = null;
2403
+
2404
+ exports.tagSoup = tagSoup;
2405
+ exports.selfClose = selfClose;
2406
+
2407
+ /***/ },
2408
+ /* 3 */
2409
+ /***/ function(module, exports, __webpack_require__) {
2410
+
2411
+ 'use strict';
2412
+
2413
+ exports.__esModule = true;
2414
+
2415
+ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
2416
+
2417
+ exports.comment = comment;
2418
+ exports.chars = chars;
2419
+ exports.startTag = startTag;
2420
+ exports.atomicTag = atomicTag;
2421
+ exports.endTag = endTag;
2422
+
2423
+ var _tokens = __webpack_require__(4);
2424
+
2425
+ /**
2426
+ * Regular Expressions for parsing tags and attributes
2427
+ *
2428
+ * @type {Object}
2429
+ */
2430
+ var REGEXES = {
2431
+ startTag: /^<([\-A-Za-z0-9_]+)((?:\s+[\w\-]+(?:\s*=?\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
2432
+ endTag: /^<\/([\-A-Za-z0-9_]+)[^>]*>/,
2433
+ attr: /(?:([\-A-Za-z0-9_]+)\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))|(?:([\-A-Za-z0-9_]+)(\s|$)+)/g,
2434
+ fillAttr: /^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noresize|noshade|nowrap|readonly|selected)$/i
2435
+ };
2436
+
2437
+ /**
2438
+ * Reads a comment token
2439
+ *
2440
+ * @param {string} stream The input stream
2441
+ * @returns {CommentToken}
2442
+ */
2443
+ function comment(stream) {
2444
+ var index = stream.indexOf('-->');
2445
+ if (index >= 0) {
2446
+ return new _tokens.CommentToken(stream.substr(4, index - 1), index + 3);
2447
+ }
2448
+ }
2449
+
2450
+ /**
2451
+ * Reads non-tag characters.
2452
+ *
2453
+ * @param {string} stream The input stream
2454
+ * @returns {CharsToken}
2455
+ */
2456
+ function chars(stream) {
2457
+ var index = stream.indexOf('<');
2458
+ return new _tokens.CharsToken(index >= 0 ? index : stream.length);
2459
+ }
2460
+
2461
+ /**
2462
+ * Reads start tag token.
2463
+ *
2464
+ * @param {string} stream The input stream
2465
+ * @returns {StartTagToken}
2466
+ */
2467
+ function startTag(stream) {
2468
+ var endTagIndex = stream.indexOf('>');
2469
+ if (endTagIndex !== -1) {
2470
+ var match = stream.match(REGEXES.startTag);
2471
+ if (match) {
2472
+ var _ret = function () {
2473
+ var attrs = {};
2474
+ var booleanAttrs = {};
2475
+ var rest = match[2];
2476
+
2477
+ match[2].replace(REGEXES.attr, function (match, name) {
2478
+ if (!(arguments[2] || arguments[3] || arguments[4] || arguments[5])) {
2479
+ attrs[name] = '';
2480
+ } else if (arguments[5]) {
2481
+ attrs[arguments[5]] = '';
2482
+ booleanAttrs[arguments[5]] = true;
2483
+ } else {
2484
+ attrs[name] = arguments[2] || arguments[3] || arguments[4] || REGEXES.fillAttr.test(name) && name || '';
2485
+ }
2486
+
2487
+ rest = rest.replace(match, '');
2488
+ });
2489
+
2490
+ return {
2491
+ v: new _tokens.StartTagToken(match[1], match[0].length, attrs, booleanAttrs, !!match[3], rest.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''))
2492
+ };
2493
+ }();
2494
+
2495
+ if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
2496
+ }
2497
+ }
2498
+ }
2499
+
2500
+ /**
2501
+ * Reads atomic tag token.
2502
+ *
2503
+ * @param {string} stream The input stream
2504
+ * @returns {AtomicTagToken}
2505
+ */
2506
+ function atomicTag(stream) {
2507
+ var start = startTag(stream);
2508
+ if (start) {
2509
+ var rest = stream.slice(start.length);
2510
+ // for optimization, we check first just for the end tag
2511
+ if (rest.match(new RegExp('<\/\\s*' + start.tagName + '\\s*>', 'i'))) {
2512
+ // capturing the content is inefficient, so we do it inside the if
2513
+ var match = rest.match(new RegExp('([\\s\\S]*?)<\/\\s*' + start.tagName + '\\s*>', 'i'));
2514
+ if (match) {
2515
+ return new _tokens.AtomicTagToken(start.tagName, match[0].length + start.length, start.attrs, start.booleanAttrs, match[1]);
2516
+ }
2517
+ }
2518
+ }
2519
+ }
2520
+
2521
+ /**
2522
+ * Reads an end tag token.
2523
+ *
2524
+ * @param {string} stream The input stream
2525
+ * @returns {EndTagToken}
2526
+ */
2527
+ function endTag(stream) {
2528
+ var match = stream.match(REGEXES.endTag);
2529
+ if (match) {
2530
+ return new _tokens.EndTagToken(match[1], match[0].length);
2531
+ }
2532
+ }
2533
+
2534
+ /***/ },
2535
+ /* 4 */
2536
+ /***/ function(module, exports, __webpack_require__) {
2537
+
2538
+ 'use strict';
2539
+
2540
+ exports.__esModule = true;
2541
+ exports.EndTagToken = exports.AtomicTagToken = exports.StartTagToken = exports.TagToken = exports.CharsToken = exports.CommentToken = exports.Token = undefined;
2542
+
2543
+ var _utils = __webpack_require__(5);
2544
+
2545
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2546
+
2547
+ /**
2548
+ * Token is a base class for all token types parsed. Note we don't actually
2549
+ * use intheritance due to IE8's non-existent ES5 support.
2550
+ */
2551
+ var Token =
2552
+ /**
2553
+ * Constructor.
2554
+ *
2555
+ * @param {string} type The type of the Token.
2556
+ * @param {Number} length The length of the Token text.
2557
+ */
2558
+ exports.Token = function Token(type, length) {
2559
+ _classCallCheck(this, Token);
2560
+
2561
+ this.type = type;
2562
+ this.length = length;
2563
+ this.text = '';
2564
+ };
2565
+
2566
+ /**
2567
+ * CommentToken represents comment tags.
2568
+ */
2569
+
2570
+
2571
+ var CommentToken = exports.CommentToken = function () {
2572
+ /**
2573
+ * Constructor.
2574
+ *
2575
+ * @param {string} content The content of the comment
2576
+ * @param {Number} length The length of the Token text.
2577
+ */
2578
+ function CommentToken(content, length) {
2579
+ _classCallCheck(this, CommentToken);
2580
+
2581
+ this.type = 'comment';
2582
+ this.length = length || (content ? content.length : 0);
2583
+ this.text = '';
2584
+ this.content = content;
2585
+ }
2586
+
2587
+ CommentToken.prototype.toString = function toString() {
2588
+ return '<!--' + this.content;
2589
+ };
2590
+
2591
+ return CommentToken;
2592
+ }();
2593
+
2594
+ /**
2595
+ * CharsToken represents non-tag characters.
2596
+ */
2597
+
2598
+
2599
+ var CharsToken = exports.CharsToken = function () {
2600
+ /**
2601
+ * Constructor.
2602
+ *
2603
+ * @param {Number} length The length of the Token text.
2604
+ */
2605
+ function CharsToken(length) {
2606
+ _classCallCheck(this, CharsToken);
2607
+
2608
+ this.type = 'chars';
2609
+ this.length = length;
2610
+ this.text = '';
2611
+ }
2612
+
2613
+ CharsToken.prototype.toString = function toString() {
2614
+ return this.text;
2615
+ };
2616
+
2617
+ return CharsToken;
2618
+ }();
2619
+
2620
+ /**
2621
+ * TagToken is a base class for all tag-based Tokens.
2622
+ */
2623
+
2624
+
2625
+ var TagToken = exports.TagToken = function () {
2626
+ /**
2627
+ * Constructor.
2628
+ *
2629
+ * @param {string} type The type of the token.
2630
+ * @param {string} tagName The tag name.
2631
+ * @param {Number} length The length of the Token text.
2632
+ * @param {Object} attrs The dictionary of attributes and values
2633
+ * @param {Object} booleanAttrs If an entry has 'true' then the attribute
2634
+ * is a boolean attribute
2635
+ */
2636
+ function TagToken(type, tagName, length, attrs, booleanAttrs) {
2637
+ _classCallCheck(this, TagToken);
2638
+
2639
+ this.type = type;
2640
+ this.length = length;
2641
+ this.text = '';
2642
+ this.tagName = tagName;
2643
+ this.attrs = attrs;
2644
+ this.booleanAttrs = booleanAttrs;
2645
+ this.unary = false;
2646
+ this.html5Unary = false;
2647
+ }
2648
+
2649
+ /**
2650
+ * Formats the given token tag.
2651
+ *
2652
+ * @param {TagToken} tok The TagToken to format.
2653
+ * @param {?string} [content=null] The content of the token.
2654
+ * @returns {string} The formatted tag.
2655
+ */
2656
+
2657
+
2658
+ TagToken.formatTag = function formatTag(tok) {
2659
+ var content = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
2660
+
2661
+ var str = '<' + tok.tagName;
2662
+ for (var key in tok.attrs) {
2663
+ if (tok.attrs.hasOwnProperty(key)) {
2664
+ str += ' ' + key;
2665
+
2666
+ var val = tok.attrs[key];
2667
+ if (typeof tok.booleanAttrs === 'undefined' || typeof tok.booleanAttrs[key] === 'undefined') {
2668
+ str += '="' + (0, _utils.escapeQuotes)(val) + '"';
2669
+ }
2670
+ }
2671
+ }
2672
+
2673
+ if (tok.rest) {
2674
+ str += ' ' + tok.rest;
2675
+ }
2676
+
2677
+ if (tok.unary && !tok.html5Unary) {
2678
+ str += '/>';
2679
+ } else {
2680
+ str += '>';
2681
+ }
2682
+
2683
+ if (content !== undefined && content !== null) {
2684
+ str += content + '</' + tok.tagName + '>';
2685
+ }
2686
+
2687
+ return str;
2688
+ };
2689
+
2690
+ return TagToken;
2691
+ }();
2692
+
2693
+ /**
2694
+ * StartTagToken represents a start token.
2695
+ */
2696
+
2697
+
2698
+ var StartTagToken = exports.StartTagToken = function () {
2699
+ /**
2700
+ * Constructor.
2701
+ *
2702
+ * @param {string} tagName The tag name.
2703
+ * @param {Number} length The length of the Token text
2704
+ * @param {Object} attrs The dictionary of attributes and values
2705
+ * @param {Object} booleanAttrs If an entry has 'true' then the attribute
2706
+ * is a boolean attribute
2707
+ * @param {boolean} unary True if the tag is a unary tag
2708
+ * @param {string} rest The rest of the content.
2709
+ */
2710
+ function StartTagToken(tagName, length, attrs, booleanAttrs, unary, rest) {
2711
+ _classCallCheck(this, StartTagToken);
2712
+
2713
+ this.type = 'startTag';
2714
+ this.length = length;
2715
+ this.text = '';
2716
+ this.tagName = tagName;
2717
+ this.attrs = attrs;
2718
+ this.booleanAttrs = booleanAttrs;
2719
+ this.html5Unary = false;
2720
+ this.unary = unary;
2721
+ this.rest = rest;
2722
+ }
2723
+
2724
+ StartTagToken.prototype.toString = function toString() {
2725
+ return TagToken.formatTag(this);
2726
+ };
2727
+
2728
+ return StartTagToken;
2729
+ }();
2730
+
2731
+ /**
2732
+ * AtomicTagToken represents an atomic tag.
2733
+ */
2734
+
2735
+
2736
+ var AtomicTagToken = exports.AtomicTagToken = function () {
2737
+ /**
2738
+ * Constructor.
2739
+ *
2740
+ * @param {string} tagName The name of the tag.
2741
+ * @param {Number} length The length of the tag text.
2742
+ * @param {Object} attrs The attributes.
2743
+ * @param {Object} booleanAttrs If an entry has 'true' then the attribute
2744
+ * is a boolean attribute
2745
+ * @param {string} content The content of the tag.
2746
+ */
2747
+ function AtomicTagToken(tagName, length, attrs, booleanAttrs, content) {
2748
+ _classCallCheck(this, AtomicTagToken);
2749
+
2750
+ this.type = 'atomicTag';
2751
+ this.length = length;
2752
+ this.text = '';
2753
+ this.tagName = tagName;
2754
+ this.attrs = attrs;
2755
+ this.booleanAttrs = booleanAttrs;
2756
+ this.unary = false;
2757
+ this.html5Unary = false;
2758
+ this.content = content;
2759
+ }
2760
+
2761
+ AtomicTagToken.prototype.toString = function toString() {
2762
+ return TagToken.formatTag(this, this.content);
2763
+ };
2764
+
2765
+ return AtomicTagToken;
2766
+ }();
2767
+
2768
+ /**
2769
+ * EndTagToken represents an end tag.
2770
+ */
2771
+
2772
+
2773
+ var EndTagToken = exports.EndTagToken = function () {
2774
+ /**
2775
+ * Constructor.
2776
+ *
2777
+ * @param {string} tagName The name of the tag.
2778
+ * @param {Number} length The length of the tag text.
2779
+ */
2780
+ function EndTagToken(tagName, length) {
2781
+ _classCallCheck(this, EndTagToken);
2782
+
2783
+ this.type = 'endTag';
2784
+ this.length = length;
2785
+ this.text = '';
2786
+ this.tagName = tagName;
2787
+ }
2788
+
2789
+ EndTagToken.prototype.toString = function toString() {
2790
+ return '</' + this.tagName + '>';
2791
+ };
2792
+
2793
+ return EndTagToken;
2794
+ }();
2795
+
2796
+ /***/ },
2797
+ /* 5 */
2798
+ /***/ function(module, exports) {
2799
+
2800
+ 'use strict';
2801
+
2802
+ exports.__esModule = true;
2803
+ exports.escapeQuotes = escapeQuotes;
2804
+
2805
+ /**
2806
+ * Escape quotes in the given value.
2807
+ *
2808
+ * @param {string} value The value to escape.
2809
+ * @param {string} [defaultValue=''] The default value to return if value is falsy.
2810
+ * @returns {string}
2811
+ */
2812
+ function escapeQuotes(value) {
2813
+ var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
2814
+
2815
+ // There's no lookback in JS, so /(^|[^\\])"/ only matches the first of two `"`s.
2816
+ // Instead, just match anything before a double-quote and escape if it's not already escaped.
2817
+ return !value ? defaultValue : value.replace(/([^"]*)"/g, function (_, prefix) {
2818
+ return (/\\/.test(prefix) ? prefix + '"' : prefix + '\\"'
2819
+ );
2820
+ });
2821
+ }
2822
+
2823
+ /***/ },
2824
+ /* 6 */
2825
+ /***/ function(module, exports) {
2826
+
2827
+ 'use strict';
2828
+
2829
+ exports.__esModule = true;
2830
+ exports['default'] = fixedReadTokenFactory;
2831
+ /**
2832
+ * Empty Elements - HTML 4.01
2833
+ *
2834
+ * @type {RegExp}
2835
+ */
2836
+ var EMPTY = /^(AREA|BASE|BASEFONT|BR|COL|FRAME|HR|IMG|INPUT|ISINDEX|LINK|META|PARAM|EMBED)$/i;
2837
+
2838
+ /**
2839
+ * Elements that you can intentionally leave open (and which close themselves)
2840
+ *
2841
+ * @type {RegExp}
2842
+ */
2843
+ var CLOSESELF = /^(COLGROUP|DD|DT|LI|OPTIONS|P|TD|TFOOT|TH|THEAD|TR)$/i;
2844
+
2845
+ /**
2846
+ * Corrects a token.
2847
+ *
2848
+ * @param {Token} tok The token to correct
2849
+ * @returns {Token} The corrected token
2850
+ */
2851
+ function correct(tok) {
2852
+ if (tok && tok.type === 'startTag') {
2853
+ tok.unary = EMPTY.test(tok.tagName) || tok.unary;
2854
+ tok.html5Unary = !/\/>$/.test(tok.text);
2855
+ }
2856
+ return tok;
2857
+ }
2858
+
2859
+ /**
2860
+ * Peeks at the next token in the parser.
2861
+ *
2862
+ * @param {HtmlParser} parser The parser
2863
+ * @param {Function} readTokenImpl The underlying readToken implementation
2864
+ * @returns {Token} The next token
2865
+ */
2866
+ function peekToken(parser, readTokenImpl) {
2867
+ var tmp = parser.stream;
2868
+ var tok = correct(readTokenImpl());
2869
+ parser.stream = tmp;
2870
+ return tok;
2871
+ }
2872
+
2873
+ /**
2874
+ * Closes the last token.
2875
+ *
2876
+ * @param {HtmlParser} parser The parser
2877
+ * @param {Array<Token>} stack The stack
2878
+ */
2879
+ function closeLast(parser, stack) {
2880
+ var tok = stack.pop();
2881
+
2882
+ // prepend close tag to stream.
2883
+ parser.prepend('</' + tok.tagName + '>');
2884
+ }
2885
+
2886
+ /**
2887
+ * Create a new token stack.
2888
+ *
2889
+ * @returns {Array<Token>}
2890
+ */
2891
+ function newStack() {
2892
+ var stack = [];
2893
+
2894
+ stack.last = function () {
2895
+ return this[this.length - 1];
2896
+ };
2897
+
2898
+ stack.lastTagNameEq = function (tagName) {
2899
+ var last = this.last();
2900
+ return last && last.tagName && last.tagName.toUpperCase() === tagName.toUpperCase();
2901
+ };
2902
+
2903
+ stack.containsTagName = function (tagName) {
2904
+ for (var i = 0, tok; tok = this[i]; i++) {
2905
+ if (tok.tagName === tagName) {
2906
+ return true;
2907
+ }
2908
+ }
2909
+ return false;
2910
+ };
2911
+
2912
+ return stack;
2913
+ }
2914
+
2915
+ /**
2916
+ * Return a readToken implementation that fixes input.
2917
+ *
2918
+ * @param {HtmlParser} parser The parser
2919
+ * @param {Object} options Options for fixing
2920
+ * @param {boolean} options.tagSoupFix True to fix tag soup scenarios
2921
+ * @param {boolean} options.selfCloseFix True to fix self-closing tags
2922
+ * @param {Function} readTokenImpl The underlying readToken implementation
2923
+ * @returns {Function}
2924
+ */
2925
+ function fixedReadTokenFactory(parser, options, readTokenImpl) {
2926
+ var stack = newStack();
2927
+
2928
+ var handlers = {
2929
+ startTag: function startTag(tok) {
2930
+ var tagName = tok.tagName;
2931
+
2932
+ if (tagName.toUpperCase() === 'TR' && stack.lastTagNameEq('TABLE')) {
2933
+ parser.prepend('<TBODY>');
2934
+ prepareNextToken();
2935
+ } else if (options.selfCloseFix && CLOSESELF.test(tagName) && stack.containsTagName(tagName)) {
2936
+ if (stack.lastTagNameEq(tagName)) {
2937
+ closeLast(parser, stack);
2938
+ } else {
2939
+ parser.prepend('</' + tok.tagName + '>');
2940
+ prepareNextToken();
2941
+ }
2942
+ } else if (!tok.unary) {
2943
+ stack.push(tok);
2944
+ }
2945
+ },
2946
+ endTag: function endTag(tok) {
2947
+ var last = stack.last();
2948
+ if (last) {
2949
+ if (options.tagSoupFix && !stack.lastTagNameEq(tok.tagName)) {
2950
+ // cleanup tag soup
2951
+ closeLast(parser, stack);
2952
+ } else {
2953
+ stack.pop();
2954
+ }
2955
+ } else if (options.tagSoupFix) {
2956
+ // cleanup tag soup part 2: skip this token
2957
+ readTokenImpl();
2958
+ prepareNextToken();
2959
+ }
2960
+ }
2961
+ };
2962
+
2963
+ function prepareNextToken() {
2964
+ var tok = peekToken(parser, readTokenImpl);
2965
+ if (tok && handlers[tok.type]) {
2966
+ handlers[tok.type](tok);
2967
+ }
2968
+ }
2969
+
2970
+ return function fixedReadToken() {
2971
+ prepareNextToken();
2972
+ return correct(readTokenImpl());
2973
+ };
2974
+ }
2975
+
2976
+ /***/ }
2977
+ /******/ ])
2978
+ });
2979
+ ;
2980
+
2981
+ /***/ },
2982
+ /* 4 */
2983
+ /***/ function(module, exports) {
2984
+
2985
+ 'use strict';
2986
+
2987
+ exports.__esModule = true;
2988
+
2989
+ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
2990
+
2991
+ exports.existy = existy;
2992
+ exports.isFunction = isFunction;
2993
+ exports.each = each;
2994
+ exports.eachKey = eachKey;
2995
+ exports.defaults = defaults;
2996
+ exports.toArray = toArray;
2997
+ exports.last = last;
2998
+ exports.isTag = isTag;
2999
+ exports.isScript = isScript;
3000
+ exports.isStyle = isStyle;
3001
+ /**
3002
+ * Determine if the thing is not undefined and not null.
3003
+ *
3004
+ * @param {*} thing The thing to test
3005
+ * @returns {boolean} True if the thing is not undefined and not null.
3006
+ */
3007
+ function existy(thing) {
3008
+ return thing !== void 0 && thing !== null;
3009
+ }
3010
+
3011
+ /**
3012
+ * Is this a function?
3013
+ *
3014
+ * @param {*} x The variable to test
3015
+ * @returns {boolean} True if the variable is a function
3016
+ */
3017
+ function isFunction(x) {
3018
+ return 'function' === typeof x;
3019
+ }
3020
+
3021
+ /**
3022
+ * Loop over each item in an array-like value.
3023
+ *
3024
+ * @param {Array<*>} arr The array to loop over
3025
+ * @param {Function} fn The function to call
3026
+ * @param {?Object} target The object to bind to the function
3027
+ */
3028
+ function each(arr, fn, target) {
3029
+ var i = void 0;
3030
+ var len = arr && arr.length || 0;
3031
+ for (i = 0; i < len; i++) {
3032
+ fn.call(target, arr[i], i);
3033
+ }
3034
+ }
3035
+
3036
+ /**
3037
+ * Loop over each key/value pair in a hash.
3038
+ *
3039
+ * @param {Object} obj The object
3040
+ * @param {Function} fn The function to call
3041
+ * @param {?Object} target The object to bind to the function
3042
+ */
3043
+ function eachKey(obj, fn, target) {
3044
+ for (var key in obj) {
3045
+ if (obj.hasOwnProperty(key)) {
3046
+ fn.call(target, key, obj[key]);
3047
+ }
3048
+ }
3049
+ }
3050
+
3051
+ /**
3052
+ * Set default options where some option was not specified.
3053
+ *
3054
+ * @param {Object} options The destination
3055
+ * @param {Object} _defaults The defaults
3056
+ * @returns {Object}
3057
+ */
3058
+ function defaults(options, _defaults) {
3059
+ options = options || {};
3060
+ eachKey(_defaults, function (key, val) {
3061
+ if (!existy(options[key])) {
3062
+ options[key] = val;
3063
+ }
3064
+ });
3065
+ return options;
3066
+ }
3067
+
3068
+ /**
3069
+ * Convert value (e.g., a NodeList) to an array.
3070
+ *
3071
+ * @param {*} obj The object
3072
+ * @returns {Array<*>}
3073
+ */
3074
+ function toArray(obj) {
3075
+ try {
3076
+ return Array.prototype.slice.call(obj);
3077
+ } catch (e) {
3078
+ var _ret = function () {
3079
+ var ret = [];
3080
+ each(obj, function (val) {
3081
+ ret.push(val);
3082
+ });
3083
+ return {
3084
+ v: ret
3085
+ };
3086
+ }();
3087
+
3088
+ if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
3089
+ }
3090
+ }
3091
+
3092
+ /**
3093
+ * Get the last item in an array
3094
+ *
3095
+ * @param {Array<*>} array The array
3096
+ * @returns {*} The last item in the array
3097
+ */
3098
+ function last(array) {
3099
+ return array[array.length - 1];
3100
+ }
3101
+
3102
+ /**
3103
+ * Test if token is a script tag.
3104
+ *
3105
+ * @param {Object} tok The token
3106
+ * @param {String} tag The tag name
3107
+ * @returns {boolean} True if the token is a script tag
3108
+ */
3109
+ function isTag(tok, tag) {
3110
+ return !tok || !(tok.type === 'startTag' || tok.type === 'atomicTag') || !('tagName' in tok) ? !1 : !!~tok.tagName.toLowerCase().indexOf(tag);
3111
+ }
3112
+
3113
+ /**
3114
+ * Test if token is a script tag.
3115
+ *
3116
+ * @param {Object} tok The token
3117
+ * @returns {boolean} True if the token is a script tag
3118
+ */
3119
+ function isScript(tok) {
3120
+ return isTag(tok, 'script');
3121
+ }
3122
+
3123
+ /**
3124
+ * Test if token is a style tag.
3125
+ *
3126
+ * @param {Object} tok The token
3127
+ * @returns {boolean} True if the token is a style tag
3128
+ */
3129
+ function isStyle(tok) {
3130
+ return isTag(tok, 'style');
3131
+ }
3132
+
3133
+ /***/ }
3134
+ /******/ ])
3135
+ });
3136
+ ;
3137
+ //# sourceMappingURL=postscribe.js.map
3138
+
3139
+ /***/ })
3140
+ /******/ ]);